コード例 #1
0
    def testWindowButtonClickClose(self):
        button = QPushButton()
        window = QWidget()
        window.connect(button, SIGNAL('clicked()'), SLOT('close()'))

        window.show()
        self.assert_(window.isVisible())
        button.click()
        self.assert_(not window.isVisible())
コード例 #2
0
ファイル: event_filter_test.py プロジェクト: Hasimir/PySide
 def testObjectDestructorOrder(self):
     w = QWidget()
     filt = MyFilter()
     filt.app = self.app
     w.installEventFilter(filt)
     w.show()
     w.close()
     w = None
     self.assert_(True)
コード例 #3
0
 def testObjectDestructorOrder(self):
     w = QWidget()
     filt = MyFilter()
     filt.app = self.app
     w.installEventFilter(filt)
     w.show()
     w.close()
     w = None
     self.assert_(True)
コード例 #4
0
ファイル: self_connect_test.py プロジェクト: Hasimir/PySide
    def testWindowButtonClickClose(self):
        button = QPushButton()
        window = QWidget()
        window.connect(button, SIGNAL('clicked()'), SLOT('close()'))

        window.show()
        self.assert_(window.isVisible())
        button.click()
        self.assert_(not window.isVisible())
コード例 #5
0
ファイル: pyside.py プロジェクト: spamalot/quichem
    def __init__(self):
        generic.GenericGui.__init__(self)
        window = QWidget()
        window.setWindowTitle('quichem-pyside')

        self.compiler_view = QListWidget()
        self.compiler_view.currentRowChanged.connect(self.show_source)
        self.stacked_widget = QStackedWidget()
        self.stacked_widget.setFrameStyle(QFrame.StyledPanel | QFrame.Raised)
        self.edit = QLineEdit()
        self.edit.setPlaceholderText('Type quichem input...')
        self.edit.textChanged.connect(self.change_value)
        self.view = QWebView()
        self.view.page().mainFrame().setScrollBarPolicy(Qt.Vertical,
                                                        Qt.ScrollBarAlwaysOff)
        self.view.page().action(QWebPage.Reload).setVisible(False)
        self.view.setMaximumHeight(0)
        self.view.setUrl('qrc:/web/page.html')
        self.view.setZoomFactor(2)
        self.view.page().mainFrame().contentsSizeChanged.connect(
            self._resize_view)
        # For debugging JS:
        ## from PySide.QtWebKit import QWebSettings
        ## QWebSettings.globalSettings().setAttribute(
        ##     QWebSettings.DeveloperExtrasEnabled, True)

        button_image = QPushButton('Copy as Image')
        button_image.clicked.connect(self.set_clipboard_image)
        button_image.setToolTip('Then paste into any graphics program')
        button_word = QPushButton('Copy as MS Word Equation')
        button_word.clicked.connect(self.set_clipboard_word)
        button_html = QPushButton('Copy as Formatted Text')
        button_html.clicked.connect(self.set_clipboard_html)
        line = QFrame()
        line.setFrameShape(QFrame.HLine)
        line.setFrameShadow(QFrame.Sunken)

        button_layout = QHBoxLayout()
        button_layout.addStretch()
        button_layout.addWidget(button_image)
        button_layout.addWidget(button_word)
        button_layout.addWidget(button_html)
        source_layout = QHBoxLayout()
        source_layout.addWidget(self.compiler_view)
        source_layout.addWidget(self.stacked_widget, 1)
        QVBoxLayout(window)
        window.layout().addWidget(self.edit)
        window.layout().addWidget(self.view)
        window.layout().addLayout(button_layout)
        window.layout().addWidget(line)
        window.layout().addLayout(source_layout, 1)

        window.show()
        window.resize(window.minimumWidth(), window.height())
        # To prevent garbage collection of internal Qt object.
        self._window = window
コード例 #6
0
ファイル: editor.py プロジェクト: altawu/everpad
    def show(self, flags=None, focus=True):
        QWidget.show(self)
        if self.visible:
            self.find(flags)
        else:
            self.editor.ui.centralwidget.layout().addWidget(self)
            self.visible = True

            self.find(flags)
            self.update_highlight()

        if focus:
            self.ui.edtFindText.setFocus()

        self.editor.find_action.setChecked(True)
コード例 #7
0
ファイル: actions.py プロジェクト: MikeyG/gevernote
    def show(self, flags=None, focus=True):
        QWidget.show(self)
        if self.visible:
            self.find(flags)
        else:
            self.editor.ui.centralwidget.layout().addWidget(self)
            self.visible = True

            self.find(flags)
            self.update_highlight()

        if focus:
            self.ui.edtFindText.setFocus()

        self.editor.find_action.setChecked(True)
コード例 #8
0
    def initializeWindow(self):
        window = QWidget()
        layout = QVBoxLayout()

        self.deviceBox = QComboBox(self)
        for info in QAudioDeviceInfo.availableDevices(QAudio.AudioOutput):
            self.deviceBox.addItem(info.deviceName(), info)

        self.deviceBox.activated[int].connect(self.deviceChanged)
        layout.addWidget(self.deviceBox)

        self.modeButton = QPushButton(self)
        self.modeButton.setText(PUSH_MODE_LABEL)
        self.modeButton.clicked.connect(self.toggleMode)
        layout.addWidget(self.modeButton)

        self.suspendResumeButton = QPushButton(self)
        self.suspendResumeButton.setText(SUSPEND_LABEL)
        self.suspendResumeButton.clicked.connect(self.toggleSuspendResume)
        layout.addWidget(self.suspendResumeButton)

        window.setLayout(layout)
        self.setCentralWidget(window)
        window.show()
コード例 #9
0
    def __init__(self):

        url = QLineEdit()
        quality = QLineEdit()
        urlLabel = QLabel('Url')
        qualityLabel = QLabel('Quality')
        messages = QTextEdit()
        messagesLabel = QLabel('Messages')
        links = QTableWidget(0, 2)
        linksLabel = QLabel('Links')
        clearMessages = QPushButton('Clear Messages')
        checkIfOnline = QPushButton('Check If Online')
        addSelectedLink = QPushButton('Add Link')
        removeSelectedLink = QPushButton('Remove Selected Link')

        messages.setReadOnly(True)

        links.setHorizontalHeaderLabels(['Url', 'Status'])
        links.horizontalHeader().setResizeMode(QHeaderView.Stretch)
        links.horizontalHeader().setResizeMode(1, QHeaderView.Fixed)

        # set the events

        url.returnPressed.connect(self.select_stream_from_entry)
        quality.returnPressed.connect(self.select_stream_from_entry)
        links.itemDoubleClicked.connect(self.select_stream_from_link)
        clearMessages.clicked.connect(self.clear_messages)
        checkIfOnline.clicked.connect(self.check_if_online)
        addSelectedLink.clicked.connect(self.add_selected_link)
        removeSelectedLink.clicked.connect(self.remove_selected_link)

        #set shortcut
        checkIfOnline.setShortcut(QKeySequence(Qt.Key_F5))

        # set the layouts

        mainLayout = QGridLayout()

        # first row
        mainLayout.addWidget(urlLabel, 0, 0, 1, 1)  # spans 1 column
        mainLayout.addWidget(qualityLabel, 0, 1, 1, 1)  # spans 1 column
        mainLayout.addWidget(linksLabel, 0, 2, 1, 3)  # spans 3 columns

        # second row  (links widget occupies 2 rows and 2 columns)
        mainLayout.addWidget(url, 1, 0, 1, 1)  # spans 1 column
        mainLayout.addWidget(quality, 1, 1, 1, 1)  # spans 1 column
        mainLayout.addWidget(links, 1, 2, 2, 3)  # spans 3 columns

        # third row (messages widget occupies 2 columns)
        mainLayout.addWidget(messages, 2, 0, 1, 2)

        # fourth row
        mainLayout.addWidget(messagesLabel, 3, 0)
        mainLayout.addWidget(clearMessages, 3, 1)
        mainLayout.addWidget(checkIfOnline, 3, 2)
        mainLayout.addWidget(addSelectedLink, 3, 3)
        mainLayout.addWidget(removeSelectedLink, 3, 4)

        window = QWidget()

        window.setLayout(mainLayout)
        window.setWindowTitle('Live Streamer')
        window.resize(700, 350)
        window.show()

        self.url_ui = url
        self.quality_ui = quality
        self.messages_ui = messages
        self.links_ui = links
        self.window_ui = window

        self.links = set()

        self.data_file = os.path.join(os.path.expanduser("~"), ".config",
                                      "livestreamer-ui", "data.txt")
        folder = os.path.dirname(self.data_file)
        if not os.path.exists(folder):
            os.makedirs(folder)
コード例 #10
0
ファイル: xlfview.py プロジェクト: ajiwo/xiboside
class VideoMediaView(MediaView):
    def __init__(self, media, parent):
        super(VideoMediaView, self).__init__(media, parent)
        self._widget = QWidget(parent)
        self._process = QProcess(self._widget)
        self._process.setObjectName('%s-process' % self.objectName())
        self._std_out = []
        self._errors = []
        self._stopping = False
        self._mute = False
        if 'mute' in self._options:
            self._mute = bool(int(self._options['mute']))

        self._widget.setGeometry(media['_geometry'])
        self.connect(self._process, SIGNAL("error()"), self._process_error)
        self.connect(self._process, SIGNAL("finished()"), self.stop)
        self.connect(self._process, SIGNAL("readyReadStandardOutput()"), self.__grep_std_out)
        self.set_default_widget_prop()

        self._stop_timer = QTimer(self)
        self._stop_timer.setSingleShot(True)
        self._stop_timer.setInterval(1000)
        self._stop_timer.timeout.connect(self._force_stop)

    @Slot()
    def _force_stop(self):
        os.kill(self._process.pid(), signal.SIGTERM)
        self._stopping = False
        if not self.is_started():
            self.started_signal.emit()
        super(VideoMediaView, self).stop()

    @Slot(object)
    def _process_error(self, err):
        self._errors.append(err)
        self.stop()

    @Slot()
    def play(self):
        self._finished = 0
        path = "%s/%s" % (self._save_dir, self._options['uri'])
        self._widget.show()
        args = [
            '-slave', '-identify', '-input',
            'nodefault-bindings:conf=/dev/null',
            '-wid', str(int(self._widget.winId())),
            path
        ]
        if self._mute:
            args += ['-ao', 'null']

        self._process.start('mplayer', args)
        self._stop_timer.start()

    @Slot()
    def stop(self, delete_widget=False):
        if self._stopping or self.is_finished():
            return False
        self._stop_timer.start()
        self._stopping = True
        if self._process.state() == QProcess.ProcessState.Running:
            self._process.write("quit\n")
            self._process.waitForFinished(50)
            self._process.close()

        super(VideoMediaView, self).stop(delete_widget)
        self._stopping = False
        self._stop_timer.stop()
        return True

    @Slot()
    def __grep_std_out(self):
        lines = self._process.readAllStandardOutput().split("\n")
        for line in lines:
            if not line.isEmpty():
                if line.startsWith("Starting playback"):
                    self._widget.raise_()
                    self._play_timer.start()
                    self.started_signal.emit()
                    self._stop_timer.stop()
                else:
                    part = line.split("=")
                    if 'ID_LENGTH' == part[0]:
                        if float(self._duration) > 0:  # user set the video duration manually.
                            self._play_timer.setInterval(int(1000 * float(self._duration)))
                        else:  # use duration found by mplayer.
                            self._play_timer.setInterval(int(1000 * float(part[1])))
コード例 #11
0
ファイル: shoot.py プロジェクト: gitter-badger/SHTR.proto
    save_credentials(sender)
    auth_server.stop_server()


def redirect_to_permission_page():
    QDesktopServices.openUrl(get_permission_url())
    quickstart(auth_server)

def shoot():
    if( not isTokenCollected()):
        redirect_to_permission_page()

    #taking the screenshot
    filename = date.strftime('%Y-%m-%d_%H-%M-%S.jpg')
    p = QPixmap.grabWindow(QApplication.desktop().winId())
    p.save(filename, 'jpg')
    upload_file_to_drive(filename)

def upload_file_to_drive(fname):
    service = get_drive_service()
    insert_file(service, fname, 'SHTR SHOT', None, 'image/jpg', fname)

widget.layout().addWidget(QPushButton('Setup Google Drive', clicked=shoot))
dispatcher.connect(receive_verification_code)

widget.show()


#enter Qt App main loop
app.exec_()
sys.exit()
コード例 #12
0
class Airport_project_UI(QWidget):

    airports = ['KRK', 'LA', 'LIS']

    elitism_possibly_values = ['true', 'false']

    max_flights_list = ['1', '2', '3', '4', '5']

    def __init__(self):
        QWidget.__init__(self)
        self.params = {}

        # self.setMinimumSize(600, 250)
        #self.setWindowTitle("Medody Optymalizacji - Projekt")
        # self.setIcon()

        self.start_airport_label = QLabel("Start airport:", self)
        self.start_airport_label.move(5, 10)
        self.start_airport = QLineEdit(self)
        self.start_airport.setText('1')
        #self.start_airport.addItems(self.airports)
        self.start_airport.setMinimumHeight(20)
        self.start_airport.setMaximumHeight(20)
        self.start_airport.setMinimumWidth(60)
        self.start_airport.setMaximumWidth(60)
        self.start_airport.move(150, 5)

        #TODO function to convert names of airport to indexes

        self.destination_airport_label = QLabel("Destination airport:", self)
        self.destination_airport_label.move(5, 40)
        self.destination_airport = QLineEdit(self)
        self.destination_airport.setText('2')
        # self.destination_airport.addItems(self.airports)
        self.destination_airport.setMinimumHeight(20)
        self.destination_airport.setMaximumHeight(20)
        self.destination_airport.setMaximumWidth(60)
        self.destination_airport.setMinimumWidth(60)
        self.destination_airport.move(150, 35)

        self.max_flights_label = QLabel("max number of flights:", self)
        self.max_flights_label.move(5, 70)
        self.max_flights = QLineEdit(self)
        self.max_flights.setText("3")
        #self.max_flights.addItems(self.max_flights_list)
        self.max_flights.setMaximumHeight(20)
        self.max_flights.setMinimumHeight(20)
        self.max_flights.setMaximumWidth(60)
        self.max_flights.setMinimumWidth(60)
        #self.max_flights.setMinimumWidth(60)
        self.max_flights.move(150, 65)

        self.cost_weight_label = QLabel("max cost weights:", self)
        self.cost_weight_label.move(5, 100)
        self.cost_weight = QLineEdit(self)
        self.cost_weight.setText("4")
        self.cost_weight.setMinimumWidth(60)
        self.cost_weight.setMaximumWidth(60)
        self.cost_weight.setMinimumHeight(20)
        self.cost_weight.setMaximumHeight(20)
        self.cost_weight.move(150, 95)

        self.time_weight_label = QLabel("time weight:", self)
        self.time_weight_label.move(5, 130)
        self.time_weight = QLineEdit(self)
        self.time_weight.setText("5")
        self.time_weight.setMinimumWidth(60)
        self.time_weight.setMaximumWidth(60)
        self.time_weight.setMinimumHeight(20)
        self.time_weight.setMaximumHeight(20)
        self.time_weight.move(150, 125)

        self.pop_size_label = QLabel("pop size:", self)
        self.pop_size_label.move(5, 160)  # +30

        self.pop_size = QLineEdit(self)
        self.pop_size.setText("6")
        self.pop_size.setMinimumWidth(60)
        self.pop_size.setMaximumWidth(60)
        self.pop_size.setMinimumHeight(20)
        self.pop_size.setMaximumHeight(20)
        self.pop_size.move(150, 155)  # +30

        self.generation_label = QLabel("generations:", self)
        self.generation_label.move(5, 190)  # +30

        self.generation = QLineEdit(self)
        self.generation.setText("7")
        self.generation.setMinimumWidth(60)
        self.generation.setMaximumWidth(60)
        self.generation.setMinimumHeight(20)
        self.generation.setMaximumHeight(20)
        self.generation.move(150, 185)  # +30

        self.mutation_rate_label = QLabel("mutation rate:", self)
        self.mutation_rate_label.move(5, 210)  # +30

        self.mutation_rate = QLineEdit(self)
        self.mutation_rate.setText("8")
        self.mutation_rate.setMinimumWidth(60)
        self.mutation_rate.setMaximumWidth(60)
        self.mutation_rate.setMinimumHeight(20)
        self.mutation_rate.setMaximumHeight(20)
        self.mutation_rate.move(150, 215)  # +30

        self.tournament_size_label = QLabel("tournament size:", self)
        self.tournament_size_label.move(5, 240)  # +30

        self.tournament_size = QLineEdit(self)
        self.tournament_size.setText("9")
        self.tournament_size.setMinimumWidth(60)
        self.tournament_size.setMaximumWidth(60)
        self.tournament_size.setMinimumHeight(20)
        self.tournament_size.setMaximumHeight(20)
        self.tournament_size.move(150, 245)  # +30

        self.elitism_label = QLabel("elitism:", self)
        self.elitism_label.move(5, 270)  # +30

        self.elitism = QComboBox(self)
        self.elitism.addItems(self.elitism_possibly_values)
        self.elitism.setMinimumWidth(60)
        self.elitism.setMaximumWidth(60)
        self.elitism.setMinimumHeight(20)
        self.elitism.setMaximumHeight(20)
        self.elitism.move(150, 275)  # +30

        self.destination_min_label = QLabel("dest min:", self)
        self.destination_min_label.move(5, 300)  # +30

        self.dest_min = QLineEdit(self)
        self.dest_min.setText("4")
        self.dest_min.setMinimumWidth(60)
        self.dest_min.setMaximumWidth(60)
        self.dest_min.setMinimumHeight(20)
        self.dest_min.setMaximumHeight(20)
        self.dest_min.move(150, 305)  # +30

        self.destination_max_label = QLabel("dest max:", self)
        self.destination_max_label.move(5, 330)  # +30

        self.dest_max = QLineEdit(self)
        self.dest_max.setText("10")
        self.dest_max.setMinimumWidth(60)
        self.dest_max.setMaximumWidth(60)
        self.dest_max.setMinimumHeight(20)
        self.dest_max.setMaximumHeight(20)
        self.dest_max.move(150, 335)  # +30

        self.generate_graph_button = QPushButton("Generate graph!", self)
        self.generate_graph_button.setMinimumWidth(170)
        self.generate_graph_button.move(25, 365)

        self.start_evolution_button = QPushButton("Start evolution!", self)
        self.start_evolution_button.setMinimumWidth(170)
        self.start_evolution_button.move(25, 395)

        self.start_evolution_button.clicked.connect(self.start_evolution)
        self.generate_graph_button.clicked.connect(self.generate_graph)
        #self.get_list_of_possibly_airports() #TODO to have full list of airports in QComboBox

    def generate_graph(self):
        self.params = {
            'graph': None,
            'start_idx': int(self.start_airport.text()),
            'end_idx': int(self.destination_airport.text()),
            'max_flights': int(self.max_flights.text()),
            'cost_weight': int(self.cost_weight.text()),
            'time_weight': int(self.time_weight.text()),
            'pop_size': int(self.pop_size.text()),
            'generations': int(self.generation.text()),
            'mutation_rate': float(self.mutation_rate.text()),
            'tournament_size': int(self.tournament_size.text()),
            'elitism': bool(self.elitism.currentText()),
            'dest_min': int(self.dest_min.text()),
            'dest_max': int(self.dest_max.text()),
            'max_flights': 4,
        }
        data = DataGenerator()
        DataGenerator.DESTINATIONS_MIN = self.params['dest_min']
        DataGenerator.DESTINATIONS_MAX = self.params['dest_max']

        # if input_graph_file is not None:
        #     data.load_saved_graph(input_graph_file)
        #
        # else:
        #TODO ilosc lotnisk
        data.load_new_data(10)
        data.create_graph()

        # if graph_save_file is not None:
        #     data.save_graph(graph_save_file)

        testsuite_airports = data.get_airports()
        testsuite_graph = data.get_graph()

        self.graph = GraphManager(self.params['max_flights'])
        self.graph.set_graph(testsuite_graph, testsuite_airports)

        airports_parser = Testsuite_airports_parser(testsuite_airports)

    def start_evolution(self):
        import pprint
        self.params = {
            'graph': self.graph,
            'start_idx': int(self.start_airport.text()),
            'end_idx': int(self.destination_airport.text()),
            'max_flights': int(self.max_flights.text()),
            'cost_weight': int(self.cost_weight.text()),
            'time_weight': int(self.time_weight.text()),
            'pop_size': int(self.pop_size.text()),
            'generations': int(self.generation.text()),
            'mutation_rate': float(self.mutation_rate.text()),
            'tournament_size': int(self.tournament_size.text()),
            'elitism': bool(self.elitism.currentText()),
            'dest_min': int(self.dest_min.text()),
            'dest_max': int(self.dest_max.text()),
        }
        # pprint.pprint(params)
        self.output_of_algorithm = sys.__stdout__
        GA.run_with_params(self.params)
        self.newwindow()

    def newwindow(self):
        import pprint
        print("##############")
        pprint.pprint(self.output_of_algorithm)
        print("##############")
        self.wid = QWidget()
        self.wid.resize(250, 150)
        self.wid.setWindowTitle('NewWindow')
        self.result = QTextEdit(self.wid)
        self.result.setText(str(self.output_of_algorithm))
        #self.start_airport.addItems(self.airports)
        self.result.setMinimumHeight(200)
        self.result.setMaximumHeight(200)
        self.result.setMinimumWidth(600)
        self.start_airport.setMaximumWidth(600)
        # self.start_airport.move(150, 5)
        self.output_of_algorithm = None
        self.wid.show()
コード例 #13
0
ファイル: xlfview.py プロジェクト: yashodhank/xiboside
class VideoMediaView(MediaView):
    def __init__(self, media, parent):
        super(VideoMediaView, self).__init__(media, parent)
        self._widget = QWidget(parent)
        self._process = QProcess(self._widget)
        self._process.setObjectName('%s-process' % self.objectName())
        self._std_out = []
        self._errors = []
        self._stopping = False
        self._mute = False
        if 'mute' in self._options:
            self._mute = bool(int(self._options['mute']))

        self._widget.setGeometry(media['_geometry'])
        self.connect(self._process, SIGNAL("error()"), self._process_error)
        self.connect(self._process, SIGNAL("finished()"), self.stop)
        self.connect(self._process, SIGNAL("readyReadStandardOutput()"),
                     self.__grep_std_out)
        self.set_default_widget_prop()

        self._stop_timer = QTimer(self)
        self._stop_timer.setSingleShot(True)
        self._stop_timer.setInterval(1000)
        self._stop_timer.timeout.connect(self._force_stop)

    @Slot()
    def _force_stop(self):
        os.kill(self._process.pid(), signal.SIGTERM)
        self._stopping = False
        if not self.is_started():
            self.started_signal.emit()
        super(VideoMediaView, self).stop()

    @Slot(object)
    def _process_error(self, err):
        self._errors.append(err)
        self.stop()

    @Slot()
    def play(self):
        self._finished = 0
        path = "%s/%s" % (self._save_dir, self._options['uri'])
        self._widget.show()
        args = [
            '-slave', '-identify', '-input',
            'nodefault-bindings:conf=/dev/null', '-wid',
            str(int(self._widget.winId())), path
        ]
        if self._mute:
            args += ['-ao', 'null']

        self._process.start('mplayer', args)
        self._stop_timer.start()

    @Slot()
    def stop(self, delete_widget=False):
        if self._stopping or self.is_finished():
            return False
        self._stop_timer.start()
        self._stopping = True
        if self._process.state() == QProcess.ProcessState.Running:
            self._process.write("quit\n")
            self._process.waitForFinished(50)
            self._process.close()

        super(VideoMediaView, self).stop(delete_widget)
        self._stopping = False
        self._stop_timer.stop()
        return True

    @Slot()
    def __grep_std_out(self):
        lines = self._process.readAllStandardOutput().split("\n")
        for line in lines:
            if not line.isEmpty():
                if line.startsWith("Starting playback"):
                    self._widget.raise_()
                    self._play_timer.start()
                    self.started_signal.emit()
                    self._stop_timer.stop()
                else:
                    part = line.split("=")
                    if 'ID_LENGTH' == part[0]:
                        if float(
                                self._duration
                        ) > 0:  # user set the video duration manually.
                            self._play_timer.setInterval(
                                int(1000 * float(self._duration)))
                        else:  # use duration found by mplayer.
                            self._play_timer.setInterval(
                                int(1000 * float(part[1])))
コード例 #14
0
 def show(self):
     QWidget.show(self)
     self.called = True
コード例 #15
0
class MainWindow(QMainWindow):
    start_acq = Signal(str)
    start_rec = Signal(str)
    collect_frame = Signal(object)
    collect_threshed = Signal(object)

    def __init__(self, parent=None):
        ''' sets up the whole main window '''

        #standard init
        super(MainWindow, self).__init__(parent)

        #set the window title
        self.setWindowTitle('Open Ephys Control GUI')

        self.window_height = 700
        self.window_width = 1100

        self.screen2 = QDesktopWidget().screenGeometry(0)
        self.move(
            self.screen2.left() +
            (self.screen2.width() - self.window_width) / 2.,
            self.screen2.top() +
            (self.screen2.height() - self.window_height) / 2.)

        self.get_info()
        self.noinfo = True

        while self.noinfo:
            loop = QEventLoop()
            QTimer.singleShot(500., loop.quit)
            loop.exec_()

        subprocess.Popen('start %s' % open_ephys_path, shell=True)

        self.collect_frame.connect(self.update_frame)
        self.collect_threshed.connect(self.update_threshed)
        self.acquiring = False
        self.recording = False

        self.video_height = self.window_height * .52
        self.video_width = self.window_width * .48

        self.resize(self.window_width, self.window_height)

        #create QTextEdit window 'terminal' for receiving stdout and stderr
        self.terminal = QTextEdit(self)
        #set the geometry
        self.terminal.setGeometry(
            QRect(self.window_width * .02,
                  self.window_height * .15 + self.video_height,
                  self.video_width * .96, 150))

        #make widgets
        self.setup_video_frames()
        self.setup_thresh_buttons()

        self.overlay = True

        #create thread and worker for video processing
        self.videoThread = QThread(self)
        self.videoThread.start()
        self.videoproc_worker = VideoWorker(self)
        self.videoproc_worker.moveToThread(self.videoThread)

        self.vt_file = None
        """""" """""" """""" """""" """""" """""" """""" """
        set up menus
        """ """""" """""" """""" """""" """""" """""" """"""

        #create a QMenuBar and set geometry
        self.menubar = QMenuBar(self)
        self.menubar.setGeometry(
            QRect(0, 0, self.window_width * .5, self.window_height * .03))
        #set the QMenuBar as menu bar for main window
        self.setMenuBar(self.menubar)

        #create a QStatusBar
        statusbar = QStatusBar(self)
        #set it as status bar for main window
        self.setStatusBar(statusbar)

        #create icon toolbar with default image
        iconToolBar = self.addToolBar("iconBar.png")

        #create a QAction for the acquire button
        self.action_Acq = QAction(self)
        #make it checkable
        self.action_Acq.setCheckable(True)
        #grab an icon for the button
        acq_icon = self.style().standardIcon(QStyle.SP_MediaPlay)
        #set the icon for the action
        self.action_Acq.setIcon(acq_icon)
        #when the button is pressed, call the Acquire function
        self.action_Acq.triggered.connect(self.Acquire)

        #create a QAction for the record button
        self.action_Record = QAction(self)
        #make it checkable
        self.action_Record.setCheckable(True)
        #grab an icon for the button
        record_icon = self.style().standardIcon(QStyle.SP_DialogYesButton)
        #set the icon for the action
        self.action_Record.setIcon(record_icon)
        #when the button is pressed, call advanced_settings function
        self.action_Record.triggered.connect(self.Record)

        #create QAction for stop button
        action_Stop = QAction(self)
        #grab close icon
        stop_icon = self.style().standardIcon(QStyle.SP_MediaStop)
        #set icon for action
        action_Stop.setIcon(stop_icon)
        #when button pressed, close window
        action_Stop.triggered.connect(self.Stop)

        #show tips for each action in the status bar
        self.action_Acq.setStatusTip("Start acquiring")
        self.action_Record.setStatusTip("Start recording")
        action_Stop.setStatusTip("Stop acquiring/recording")

        #add actions to icon toolbar
        iconToolBar.addAction(self.action_Acq)
        iconToolBar.addAction(self.action_Record)
        iconToolBar.addAction(action_Stop)

        #        self.sort_button = QPushButton('Sort Now',self)
        #        self.sort_button.setGeometry(QRect(self.window_width*.85,0,self.window_width*.15,self.window_height*.05))
        #        self.sort_button.clicked.connect(self.sort_now)

        #show the window if minimized by windows
        self.showMinimized()
        self.showNormal()
        """""" """""" """""" """""" """""" """""" """""" """""" """""" """""" ""
        """""" """""" """""" """""" """""" """""" """""" """""" """""" """""" ""

    #this function acts as a slot to accept 'message' signal
    @Slot(str)
    def print_message(self, message):
        ''' print stdout and stderr to terminal window '''

        #move terminal cursor to end
        self.terminal.moveCursor(QTextCursor.End)
        #write message to terminal
        self.terminal.insertPlainText(message)

    def setup_thresh_buttons(self):
        ''' set up buttons for overlay/clearing thresh view '''

        self.button_frame = QFrame(self)
        self.button_frame.setGeometry(
            QRect(self.window_width * .52,
                  self.window_height * .13 + self.video_height,
                  self.video_width * .98, 50))
        button_layout = QHBoxLayout()
        self.button_frame.setLayout(button_layout)
        self.clear_button = QPushButton('Clear')
        self.overlay_button = QPushButton('Overlay')
        button_layout.addWidget(self.clear_button)
        button_layout.addWidget(self.overlay_button)

        self.clear_button.setEnabled(False)
        self.clear_button.clicked.connect(self.clear_threshed)
        self.overlay_button.setEnabled(False)
        self.overlay_button.clicked.connect(self.overlay_threshed)

    def setup_video_frames(self):
        ''' set up spots for playing video frames '''

        filler_frame = np.zeros((360, 540, 3))
        filler_frame = qimage2ndarray.array2qimage(filler_frame)

        self.raw_frame = QFrame(self)
        self.raw_label = QLabel()
        self.raw_label.setText('raw')
        self.raw_frame.setGeometry(
            QRect(self.window_width * .01, self.window_height * .15,
                  self.video_width, self.video_height))
        self.raw_frame
        raw_layout = QVBoxLayout()
        self.raw_frame.setLayout(raw_layout)
        raw_layout.addWidget(self.raw_label)

        self.threshed_frame = QFrame(self)
        self.threshed_label = QLabel()
        self.threshed_label.setText('Threshed')
        self.threshed_frame.setGeometry(
            QRect(self.window_width * .51, self.window_height * .15,
                  self.video_width, self.video_height))
        threshed_layout = QVBoxLayout()
        self.threshed_frame.setLayout(threshed_layout)
        threshed_layout.addWidget(self.threshed_label)

        self.label_frame = QFrame(self)
        self.label_frame.setGeometry(
            QRect(self.window_width * .01, self.window_height * .11,
                  self.video_width * 2, 50))
        self.label_rawlabel = QLabel()
        self.label_rawlabel.setText('Raw Video')
        self.label_threshedlabel = QLabel()
        self.label_threshedlabel.setText('Threshold View')
        label_layout = QHBoxLayout()
        self.label_frame.setLayout(label_layout)
        label_layout.addWidget(self.label_rawlabel)
        label_layout.addWidget(self.label_threshedlabel)

        self.raw_label.setPixmap(QPixmap.fromImage(filler_frame))
        self.threshed_label.setPixmap(QPixmap.fromImage(filler_frame))

    def Acquire(self):

        if self.action_Acq.isChecked():

            self.vidbuffer = []

            if self.recording:

                while 1:
                    try:
                        self.sock.send('StopRecord')
                        self.sock.recv()
                    except:
                        continue
                    break

                self.recording = False

            else:
                #create and start a thread to transport a worker to later
                self.workerThread = QThread(self)
                self.workerThread.start()
                #create a worker object based on Worker class and move it to our
                #worker thread
                self.worker = Worker(self)
                self.worker.moveToThread(self.workerThread)

                try:
                    self.start_acq.disconnect()
                except:
                    pass

                while 1:
                    try:
                        self.sock.send('StartAcquisition')
                        self.sock.recv()
                    except:
                        continue
                    break

                self.acquiring = True
                self.start_acq.connect(self.worker.acquire)
                self.start_acq.emit('start!')

            self.action_Acq.setEnabled(False)
            self.action_Record.setChecked(False)
            self.action_Record.setEnabled(True)

            record_icon = self.style().standardIcon(QStyle.SP_DialogYesButton)
            #set the icon for the action
            self.action_Record.setIcon(record_icon)

    def Record(self):

        if self.action_Record.isChecked():

            if not self.acquiring:
                self.workerThread = QThread(self)
                self.workerThread.start()

                self.worker = Worker(self)
                self.worker.moveToThread(self.workerThread)

                try:
                    self.start_rec.disconnect()
                except:
                    pass

                while 1:
                    try:
                        self.sock.send('StartAcquisition')
                        self.sock.recv()
                    except:
                        continue
                    break

                while 1:
                    try:
                        self.sock.send('StartRecord')
                        self.sock.recv()
                    except:
                        continue
                    break

                self.vidbuffer = []
                self.start_rec.connect(self.worker.acquire)
                self.recording = True
                self.start_rec.emit('start!')

            else:

                while 1:
                    try:
                        self.sock.send('StartRecord')
                        self.sock.recv()
                    except:
                        continue
                    break

                self.vidbuffer = []
                self.recording = True

            record_icon = self.style().standardIcon(QStyle.SP_DialogNoButton)
            #set the icon for the action
            self.action_Record.setIcon(record_icon)
            self.action_Record.setEnabled(False)

            self.action_Acq.setChecked(False)
            self.action_Acq.setEnabled(True)

    def Stop(self):

        self.acquiring = False
        self.recording = False

        while 1:
            try:
                self.sock.send('isRecording')
                rec = self.sock.recv()
            except:
                continue
            break

        if rec == '1':
            while 1:
                try:
                    self.sock.send('StopRecord')
                    self.sock.recv()
                except:
                    continue
                break

            self.action_Record.setEnabled(True)
            self.action_Record.setChecked(False)

        while 1:
            try:
                self.sock.send('isAcquiring')
                acq = self.sock.recv_string()
            except:
                continue
            break

        if acq == '1':
            while 1:
                try:
                    self.sock.send('StopAcquisition')
                    self.sock.recv()
                except:
                    continue
                break

        self.action_Acq.setEnabled(True)
        self.action_Acq.setChecked(False)

        try:
            #open a csv file for saving tracking data
            with open(self.vt_file, 'a') as csvfile:
                #create a writer
                vidwriter = csv.writer(csvfile, dialect='excel-tab')
                #check if it's an empty file
                for row in self.vidbuffer:
                    vidwriter.writerow(row)

        except:
            pass

        record_icon = self.style().standardIcon(QStyle.SP_DialogYesButton)
        #set the icon for the action
        self.action_Record.setIcon(record_icon)

    def update_frame(self, image):
        self.raw_label.setPixmap(QPixmap.fromImage(image))

    def update_threshed(self, threshed_image):
        self.threshed_label.setPixmap(QPixmap.fromImage(threshed_image))

    def clear_threshed(self):
        self.green_frame = np.zeros_like(self.green_frame)
        self.red_frame = np.zeros_like(self.red_frame)

    def overlay_threshed(self):
        if self.overlay:
            self.overlay = False
        elif not self.overlay:
            self.overlay = True


#    def sort_now(self):
#
#        if self.recdir is not None:
#            os.chdir('./kilosort_control')
#            #create and show the main window
#            self.sort_frame = kilosort_control.sort_gui.MainWindow()
#            self.sort_frame.show()
#
#            #set up stream for stdout and stderr based on outputStream class
#            self.outputStream = kilosort_control.sort_gui.outputStream()
#            #when outputStream sends messages, connect to appropriate function for
#            #writing to terminal window
#            self.outputStream.message.connect(self.sort_frame.print_message)
#
#            #connect stdout and stderr to outputStream
#            sys.stdout = self.outputStream
#            sys.stderr = self.outputStream
#
#            self.sort_frame.run_now(self.recdir)
#
#            self.close()

    def get_info(self):

        self.info_window = QWidget()
        self.info_window.resize(400, 350)
        #set title
        self.info_window.setWindowTitle('Session Info')
        #give layout
        info_layout = QVBoxLayout(self.info_window)

        with open('info_fields.pickle', 'rb') as f:
            default_fields = pickle.load(f)
            f.close()

        #set label for pic_resolution setting
        experimenter_label = QLabel('Experimenter:')
        #make a QLineEdit box for displaying/editing settings
        experimenter = QComboBox(self.info_window)
        experimenter.setEditable(True)
        experimenter.addItems(default_fields['experimenter'])
        #add label and box to current window
        info_layout.addWidget(experimenter_label)
        info_layout.addWidget(experimenter)

        #set label for pic_resolution setting
        whose_animal_label = QLabel('Whose animal?')
        #make a QLineEdit box for displaying/editing settings
        whose_animal = QComboBox(self.info_window)
        whose_animal.setEditable(True)
        whose_animal.addItems(default_fields['whose_animal'])
        #add label and box to current window
        info_layout.addWidget(whose_animal_label)
        info_layout.addWidget(whose_animal)

        animal_number_label = QLabel('Animal number:')
        animal_number = QComboBox(self.info_window)
        animal_number.setEditable(True)
        animal_number.addItems(default_fields['animal_number'])
        info_layout.addWidget(animal_number_label)
        info_layout.addWidget(animal_number)

        session_number_label = QLabel('Session number:')
        session_number = QTextEdit(self.info_window)
        session_number.setText('1')
        info_layout.addWidget(session_number_label)
        info_layout.addWidget(session_number)

        session_type_label = QLabel('Session type:')
        session_type = QComboBox(self.info_window)
        session_type.setEditable(True)
        session_type.addItems(default_fields['session_type'])
        info_layout.addWidget(session_type_label)
        info_layout.addWidget(session_type)

        def save_info(self):

            info_fields = {}
            info_fields['experimenter'] = [
                experimenter.itemText(i) for i in range(experimenter.count())
            ]
            info_fields['whose_animal'] = [
                whose_animal.itemText(i) for i in range(whose_animal.count())
            ]
            info_fields['animal_number'] = [
                animal_number.itemText(i) for i in range(animal_number.count())
            ]
            info_fields['session_type'] = [
                session_type.itemText(i) for i in range(session_type.count())
            ]

            with open('info_fields.pickle', 'wb') as f:
                pickle.dump(info_fields, f, protocol=2)
                f.close()

            current_experimenter = str(experimenter.currentText())
            current_whose_animal = str(whose_animal.currentText())
            current_animal_number = str(animal_number.currentText())
            current_session_number = str(session_number.toPlainText())
            current_session_type = str(session_type.currentText())

            recdir = data_save_dir + current_whose_animal + '/' + current_animal_number

            if not os.path.exists(recdir):
                os.makedirs(recdir)

            self.experiment_info = '###### Experiment Info ######\r\n'
            self.experiment_info += 'Experimenter: %s\r\n' % current_experimenter
            self.experiment_info += 'Whose animal? %s\r\n' % current_whose_animal
            self.experiment_info += 'Animal number: %s\r\n' % current_animal_number
            self.experiment_info += 'Session number: %s\r\n' % current_session_number
            self.experiment_info += 'Session type: %s\r\n' % current_session_type

            self.experiment_info = self.experiment_info.encode()

            config_file = config_path + '/' + current_animal_number + '.xml'

            if not os.path.exists(config_file):
                shutil.copy(default_config, config_file)

            tree = et.parse(config_file)
            root = tree.getroot()
            for child in root:
                if child.tag == 'CONTROLPANEL':
                    child.attrib['recordPath'] = recdir.replace('/', '\\')
            tree.write(config_file)
            tree.write(default_config)

            self.info_window.close()
            self.noinfo = False

        ready_button = QPushButton('Ready!')
        ready_button.clicked.connect(lambda: save_info(self))
        info_layout.addWidget(ready_button)

        self.info_window.show()
コード例 #16
0
class WebMediaView(MediaView):
    def __init__(self, media, parent):
        super(WebMediaView, self).__init__(media, parent)
        self.widget = QWidget(parent)
        self.process = QProcess(self.widget)
        self.process.setObjectName('%s-process' % self.objectName())
        self.std_out = []
        self.errors = []
        self.stopping = False
        self.mute = False
        self.widget.setGeometry(media['geometry'])
        self.connect(self.process, SIGNAL('error()'), self.process_error)
        self.connect(self.process, SIGNAL('finished()'), self.process_finished)
        self.connect(self.process, SIGNAL('started()'), self.process_started)
        self.set_default_widget_prop()
        self.stop_timer = QTimer(self)
        self.stop_timer.setSingleShot(True)
        self.stop_timer.setInterval(1000)
        self.stop_timer.timeout.connect(self.process_timeout)
        self.rect = self.widget.geometry()

    @Slot()
    def process_timeout(self):
        os.kill(self.process.pid(), signal.SIGTERM)
        self.stopping = False
        if not self.is_started():
            self.started_signal.emit()
        super(WebMediaView, self).stop()

    @Slot(object)
    def process_error(self, err):
        print '---- process error ----'
        self.errors.append(err)
        self.stop()

    @Slot()
    def process_finished(self):
        self.stop()

    @Slot()
    def process_started(self):
        self.stop_timer.stop()
        if float(self.duration) > 0:
            self.play_timer.setInterval(int(float(self.duration) * 1000))
            self.play_timer.start()
        self.started_signal.emit()
        pass

    @Slot()
    def play(self):
        self.finished = 0
        self.widget.show()
        self.widget.raise_()

        #---- kong ----
        url = self.options['uri']
        args = [
            #'--kiosk',
            str(self.rect.left()),
            str(self.rect.top()),
            str(self.rect.width()),
            str(self.rect.height()),
            QUrl.fromPercentEncoding(url)
        ]
        #self.process.start('chromium-browser', args)
        self.process.start('./dist/web', args)
        self.stop_timer.start()
        #----

    @Slot()
    def stop(self, delete_widget=False):
        #---- kong ----
        if not self.widget:
            return False
        if self.stopping or self.is_finished():
            return False
        self.stop_timer.start()
        self.stopping = True
        if self.process.state() == QProcess.ProcessState.Running:
            #os.system('pkill chromium')
            os.system('pkill web')
            self.process.waitForFinished()
            self.process.close()
        super(WebMediaView, self).stop(delete_widget)
        self.stopping = False
        self.stop_timer.stop()
        return True
コード例 #17
0
class VideoMediaView(MediaView):
    def __init__(self, media, parent):
        super(VideoMediaView, self).__init__(media, parent)
        self.widget = QWidget(parent)
        self.process = QProcess(self.widget)
        self.process.setObjectName('%s-process' % self.objectName())
        self.std_out = []
        self.errors = []
        self.stopping = False
        self.mute = False
        self.widget.setGeometry(media['geometry'])
        self.connect(self.process, SIGNAL('error()'), self.process_error)
        self.connect(self.process, SIGNAL('finished()'), self.process_finished)
        self.connect(self.process, SIGNAL('started()'), self.process_started)
        self.set_default_widget_prop()
        self.stop_timer = QTimer(self)
        self.stop_timer.setSingleShot(True)
        self.stop_timer.setInterval(1000)
        self.stop_timer.timeout.connect(self.process_timeout)
        #---- kong ---- for RPi
        self.rect = media['geometry']
        self.omxplayer = True
        #----

    @Slot()
    def process_timeout(self):
        os.kill(self.process.pid(), signal.SIGTERM)
        self.stopping = False
        if not self.is_started():
            self.started_signal.emit()
        super(VideoMediaView, self).stop()

    @Slot(object)
    def process_error(self, err):
        print '---- process error ----'
        self.errors.append(err)
        self.stop()

    @Slot()
    def process_finished(self):
        self.stop()

    @Slot()
    def process_started(self):
        self.stop_timer.stop()
        if float(self.duration) > 0:
            self.play_timer.setInterval(int(float(self.duration) * 1000))
            self.play_timer.start()
        self.started_signal.emit()
        pass

    @Slot()
    def play(self):
        self.finished = 0
        self.widget.show()
        self.widget.raise_()
        path = '%s/%s' % (self.save_dir, self.options['uri'])
        #---- kong ----
        if self.omxplayer is True:
            left, top, right, bottom = self.rect.getCoords()
            rect = '%d,%d,%d,%d' % (left, top, right, bottom)
            args = ['--win', rect, '--no-osd', '--layer', self.zindex, path]
            self.process.start('omxplayer.bin', args)
            self.stop_timer.start()
        else:
            args = [
                '-slave', '-identify', '-input',
                'nodefault-bindings:conf=/dev/null', '-wid',
                str(int(self.widget.winId())), path
            ]
            self.process.start('mplayer', args)
            self.stop_timer.start()
        #----

    @Slot()
    def stop(self, delete_widget=False):
        #---- kong ----
        if not self.widget:
            return False
        if self.stopping or self.is_finished():
            return False
        self.stop_timer.start()
        self.stopping = True
        if self.process.state() == QProcess.ProcessState.Running:
            if self.omxplayer is True:
                self.process.write('q')
            else:
                self.process.write('quit\n')
            self.process.waitForFinished()
            self.process.close()
        super(VideoMediaView, self).stop(delete_widget)
        self.stopping = False
        self.stop_timer.stop()
        return True
コード例 #18
0
ファイル: VideoSwitcher.py プロジェクト: staldates/av-control
class VideoSwitcher(QWidget):

    def __init__(self, controller, mainWindow, switcherState, joystickAdapter=None):
        super(VideoSwitcher, self).__init__()
        self.mainWindow = mainWindow
        self.atem = controller['ATEM']
        self.controller = controller
        self.switcherState = switcherState
        self.joystickAdapter = joystickAdapter
        self.setupUi()

    def setupUi(self):
        layout = QGridLayout()

        inputs_grid = QHBoxLayout()
        self.inputs = QButtonGroup()

        def ifDevice(deviceID, func):
            if self.controller.hasDevice(deviceID):
                return func()
            return (None, None, None, None)

        def setCamera(cam, cc):
            if self.joystickAdapter:
                self.joystickAdapter.set_camera(cam)
                self.joystickAdapter.set_on_move(cc.deselectPreset)

        def makeCamera(videoSource, cameraID):
            cam = self.controller[cameraID]
            cc = CameraControl(cam)

            return (
                videoSource,
                cc,
                AdvancedCameraControl(cameraID, cam, self.mainWindow),
                lambda: setCamera(cam, cc)
            )

        def deselectCamera():
            if self.joystickAdapter:
                self.joystickAdapter.set_camera(None)
                self.joystickAdapter.set_on_move(None)

        self.input_buttons_config = [
            ifDevice("Camera 1", lambda: makeCamera(VideoSource.INPUT_1, "Camera 1")),
            ifDevice("Camera 2", lambda: makeCamera(VideoSource.INPUT_2, "Camera 2")),
            ifDevice("Camera 3", lambda: makeCamera(VideoSource.INPUT_3, "Camera 3")),
            (VideoSource.INPUT_4, QLabel(StringConstants.noDevice), None, deselectCamera),
            (VideoSource.INPUT_5, OverlayControl(self.switcherState.dsks[0], self.atem), None, deselectCamera),
            (VideoSource.INPUT_6, QLabel(StringConstants.noDevice), None, deselectCamera)
        ]

        for source, panel, adv_panel, on_select_func in self.input_buttons_config:
            if source:
                btn = InputButton(self.switcherState.inputs[source])
                btn.setProperty("panel", panel)
                btn.setProperty("adv_panel", adv_panel)
                btn.clicked.connect(self.preview)
                btn.clicked.connect(self.displayPanel)
                if on_select_func:
                    btn.clicked.connect(on_select_func)
                btn.longpress.connect(self.displayAdvPanel)
                self.inputs.addButton(btn)
                inputs_grid.addWidget(btn)

        self.extrasBtn = InputButton(None)
        self.inputs.addButton(self.extrasBtn)
        self.extrasBtn.clicked.connect(self.preview)
        self.extrasBtn.clicked.connect(self.displayPanel)
        self.extrasBtn.clicked.connect(deselectCamera)

        # An empty menu means the button will be given a "down arrow" icon
        # without actually showing a menu when pressed.
        self.extrasBtn.setMenu(QMenu())

        self.allInputs = AllInputsPanel(self.switcherState)
        self.extrasBtn.setProperty("panel", self.allInputs)

        self.allInputs.inputSelected.connect(self.setExtraInput)

        inputs_grid.addWidget(self.extrasBtn)

        self.blackBtn = FlashingInputButton(self.switcherState.inputs[VideoSource.BLACK])
        inputs_grid.addWidget(self.blackBtn)
        self.inputs.addButton(self.blackBtn)
        self.blackBtn.clicked.connect(self.preview)
        self.blackBtn.clicked.connect(self.displayPanel)
        self.blackBtn.clicked.connect(deselectCamera)
        self.ftb = FadeToBlackControl(self.switcherState.ftb, self.atem)
        self.blackBtn.setProperty("panel", self.ftb)
        self.blackBtn.flashing = self.switcherState.ftb.active
        self.switcherState.ftb.activeChanged.connect(self.blackBtn.setFlashing)

        layout.addLayout(inputs_grid, 0, 0, 1, 7)

        self.og = OutputsGrid(self.switcherState)

        self.og.take.connect(self.take)
        self.og.cut.connect(self.cut)
        self.og.selected.connect(self.sendToAux)
        self.og.mainToAll.connect(self.sendMainToAllAuxes)
        self.og.all.connect(self.sendToAll)
        self.og.sendMain.connect(self.sendMainToAux)

        self.og.setAuxesEnabled(False)  # since we start off without an input selected

        layout.addWidget(self.og, 1, 5, 1, 2)

        self.blankWidget = QWidget()
        layout.addWidget(self.blankWidget, 1, 0, 1, 5)

        layout.setRowStretch(0, 1)
        layout.setRowStretch(1, 5)

        self.setLayout(layout)

    def setExtraInput(self, inp):
        self.extrasBtn.setInput(inp)
        self.preview()

    @with_atem
    def preview(self):
        checkedButton = self.inputs.checkedButton()
        if checkedButton and checkedButton.input:
            self.og.setAuxesEnabled(True)
            if self.atem:
                self.atem.setPreview(checkedButton.input.source)
        else:
            self.og.setAuxesEnabled(False)

    @with_atem
    def cut(self):
        self.atem.performCut()

    @with_atem
    def take(self):
        self.atem.setNextTransition(TransitionStyle.MIX, bkgd=True, key1=False, key2=False, key3=False, key4=False)
        self.atem.performAutoTake()

    @with_atem
    def sendToAux(self, auxIndex):
        if self.inputs.checkedButton().input:
            self.atem.setAuxSource(auxIndex + 1, self.inputs.checkedButton().input.source)

    @with_atem
    def sendToAll(self):
        if self.inputs.checkedButton().input:
            self.atem.setProgram(self.inputs.checkedButton().input.source)
            for aux in self.switcherState.outputs.keys():
                self.sendToAux(aux)

    @with_atem
    def sendMainToAux(self, auxIndex):
        self.atem.setAuxSource(auxIndex + 1, VideoSource.ME_1_PROGRAM)

    @with_atem
    def sendMainToAllAuxes(self):
        for aux in self.switcherState.outputs.keys():
            self.atem.setAuxSource(aux + 1, VideoSource.ME_1_PROGRAM)

    def displayPanel(self):
        panel = self.inputs.checkedButton().property("panel")
        layout = self.layout()
        existing = layout.itemAtPosition(1, 0)
        if existing:
            widget = existing.widget()
            widget.hide()
            layout.removeWidget(widget)
            if panel:
                # display panel
                layout.addWidget(panel, 1, 0, 1, 5)
                panel.show()
            else:
                # hide panel
                layout.addWidget(self.blankWidget, 1, 0, 1, 5)
                self.blankWidget.show()

    def displayAdvPanel(self):
        panel = self.sender().property("adv_panel")
        if panel:
            self.mainWindow.showScreen(panel)
コード例 #19
0
ファイル: photocurrent_iv.py プロジェクト: wcyjames/stackbot
class PhotocurrentIVMeasurement(Measurement):

    name = "photocurrrent_iv"

    def setup(self):
        self.display_update_period = 0.1  #seconds

        # logged quantities
        self.source_voltage_min = self.add_logged_quantity(
            "source_voltage_min",
            dtype=float,
            initial=-5,
            unit='V',
            vmin=-5,
            vmax=5,
            ro=False)
        self.source_voltage_max = self.add_logged_quantity(
            "source_voltage_max",
            dtype=float,
            initial=+5,
            unit='V',
            vmin=-5,
            vmax=5,
            ro=False)
        self.source_voltage_delta = self.add_logged_quantity(
            "source_voltage_delta",
            dtype=float,
            initial=0.1,
            unit='V',
            vmin=-5,
            vmax=5,
            ro=False)
        self.source_voltage_steps = self.add_logged_quantity(
            "source_voltage_steps",
            dtype=int,
            initial=10,
            vmin=1,
            vmax=1000,
            ro=False)

        self.voltage_range = LQRange(self.source_voltage_min,
                                     self.source_voltage_max,
                                     self.source_voltage_delta,
                                     self.source_voltage_steps)

        try:
            self.source_voltage_min.connect_bidir_to_widget(
                self.gui.ui.photocurrent_iv_vmin_doubleSpinBox)
            self.source_voltage_max.connect_bidir_to_widget(
                self.gui.ui.photocurrent_iv_vmax_doubleSpinBox)
            self.source_voltage_steps.connect_bidir_to_widget(
                self.gui.ui.photocurrent_iv_steps_doubleSpinBox)
            #connect events
            self.gui.ui.photocurrent_iv_start_pushButton.clicked.connect(
                self.start)
        except Exception as err:
            print self.name, "could not connect to custom gui", err

    def setup_figure(self):
        self.ui = QWidget(None)

        self.ui.setLayout(QVBoxLayout())
        self.fig = self.gui.add_figure_mpl("photocurrent_iv", self.ui)

        self.ui.show()

        self.ax = self.fig.add_subplot(111)
        self.plotline, = self.ax.plot([0, 1], [0, 0])
        #self.ax.set_ylim(1e-1,1e5)
        self.ax.set_xlabel("Voltage (V)")
        self.ax.set_ylabel("Current (Amps)")

    def _run(self):

        self.initial_scan_setup_plotting = True

        #Hardware
        self.keithley_hc = self.gui.keithley_sourcemeter_hc
        K1 = self.keithley = self.keithley_hc.keithley

        # h5 data file setup
        self.t0 = time.time()
        self.h5_file = h5_io.h5_base_file(self.gui,
                                          "%i_%s.h5" % (self.t0, self.name))
        self.h5_file.attrs['time_id'] = self.t0
        H = self.h5_meas_group = self.h5_file.create_group(self.name)
        h5_io.h5_save_measurement_settings(self, H)
        h5_io.h5_save_hardware_lq(self.gui, H)

        K1.resetA()
        K1.setAutoranges_A()
        K1.switchV_A_on()
        I, V = K1.measureIV_A(self.source_voltage_steps.val,
                              Vmin=self.source_voltage_min.val,
                              Vmax=self.source_voltage_max.val,
                              KeithleyADCIntTime=1,
                              delay=0)

        K1.switchV_A_off()

        print I
        print V

        self.Iarray = I
        self.Varray = V

        #save some data
        save_dict = {'I': self.Iarray, 'V': self.Varray}
        self.fname = "%i_photocurrent_iv.npz" % time.time()
        np.savez_compressed(self.fname, **save_dict)
        print "photocurrent_iv Saved", self.fname

        #create h5 data arrays
        H['I'] = self.Iarray
        H['V'] = self.Varray

        self.h5_file.close()

    def update_display(self):
        if self.initial_scan_setup_plotting:
            self.fig.clf()
            self.ax = self.fig.add_subplot(111)
            self.plotline, = self.ax.plot([0, 1], [0, 0])
            self.ax.set_xlabel("Voltage (V)")
            self.ax.set_ylabel("Current (Amps)")
            self.ax.axvline(0, color='k')
            self.ax.axhline(0, color='k')
            self.initial_scan_setup_plotting = False
        self.plotline.set_data(self.Varray, self.Iarray)
        self.ax.relim()
        self.ax.autoscale_view(scalex=True, scaley=True)
        self.fig.canvas.draw()
コード例 #20
0
class Ui_MainView(QMainWindow):

    gui_methods_sig = Signal(int, )

    def __init__(self, ):
        super(Ui_MainView, self).__init__()

        self.output_folder = os.getcwd()
        self.usr = ''
        self.psw = ''

        self.save_username_checked = False

        self.right_base_layout_v = QtGui.QVBoxLayout()
        self.msgBox = QtGui.QMessageBox()

        self.validations = validate_inputs.validate_controls(
            self
        )  # instance for input validations  and we are passing self to validate class for model updations

    def gifUI(self, gui_slate):

        self.gui = gui_slate
        self.gif_widget = QWidget()
        self.gif_layout = QVBoxLayout()

        self.movie_screen = QLabel()
        self.movie_screen.setSizePolicy(QtGui.QSizePolicy.Expanding,
                                        QtGui.QSizePolicy.Expanding)
        self.movie_screen.setAlignment(QtCore.Qt.AlignCenter)
        self.gif_layout.addWidget(self.movie_screen)

        ag_file = "GIF-180704_103026.gif"

        self.movie = QtGui.QMovie(ag_file, QtCore.QByteArray(),
                                  self.gif_widget)
        self.movie.setCacheMode(QtGui.QMovie.CacheAll)
        self.movie.setSpeed(75)
        self.movie_screen.setMovie(self.movie)
        #         self.movie_screen.setFixedWidth(500)

        self.gif_widget.setLayout(self.gif_layout)
        self.gui.setCentralWidget(self.gif_widget)
        #         self.gui.addDockWidget(self.gif_widget)
        self.movie.start()
        #         self.movie.setPaused(True)
        self.gif_widget.show()
#         time.sleep(2)
#         self.movie.stop()

    def setupUi(self, gui_slate):

        self.gui = gui_slate
        self.gui.get_option_selected = False
        self.gui.push_option_selected = False
        self.gui.extract_opt_selected = False
        self.gui.compare_opt_selected = False

        #Outer most Main Layout

        self.widget = QWidget()
        self.widget.setMinimumSize(850, 600)

        self.main_layout_h = QHBoxLayout()
        self.main_layout_h.setAlignment(QtCore.Qt.AlignTop)

        self.widget.setLayout(self.main_layout_h)

        self.gui.setCentralWidget(self.widget)

        self.left_base_widget = QWidget()
        #         self.left_base_widget.setMaximumWidth(600)
        #         self.left_base_widget.setMinimumWidth(450)
        #         self.left_base_widget.setMaximumHeight(700)

        self.right_base_widget = QWidget()

        #3 Sub main Layouts

        self.left_base_layout_v = QVBoxLayout()
        #         self.right_base_layout_v = QVBoxLayout()
        self.corner_logo_layout_v = QVBoxLayout()
        self.left_base_layout_v.setAlignment(QtCore.Qt.AlignTop)

        self.right_base_layout_v.setAlignment(QtCore.Qt.AlignTop)

        #Added Widgets and layouts to the outermost layout

        self.main_layout_h.addWidget(self.left_base_widget)
        self.main_layout_h.addWidget(self.right_base_widget)
        self.main_layout_h.addLayout(self.corner_logo_layout_v)

        #         , QtGui.QFont.Normal
        self.grp_heading_font = QtGui.QFont("Verdana", 10)
        self.grp_heading_font.setItalic(True)

        #Radio buttons layout

        self.radio_groupBox = QtGui.QGroupBox()
        self.radio_option_layout_lb_h = QHBoxLayout()

        self.radio_groupBox.setLayout(self.radio_option_layout_lb_h)

        self.radio_groupBox.setMinimumWidth(450)
        self.left_base_layout_v.addWidget(self.radio_groupBox)

        #Credentials layouts

        self.credentials_groupbox = QtGui.QGroupBox("GTAC Credentials")
        self.credentials_groupbox.setFont(self.grp_heading_font)
        self.credentials_layout_lb_v = QVBoxLayout()

        self.username_layout_lb_h = QHBoxLayout()
        self.password_layout_lb_h = QHBoxLayout()
        self.cr_layout_lb_h = QHBoxLayout()
        self.password_layout_lb_h.setAlignment(QtCore.Qt.AlignLeft)
        self.credentials_layout_lb_v.addLayout(self.username_layout_lb_h)
        self.credentials_layout_lb_v.addLayout(self.password_layout_lb_h)
        self.credentials_layout_lb_v.addLayout(self.cr_layout_lb_h)

        self.credentials_groupbox.setLayout(self.credentials_layout_lb_v)
        self.left_base_layout_v.addWidget(self.credentials_groupbox)
        self.credentials_groupbox.setAlignment(QtCore.Qt.AlignLeft)
        self.credentials_groupbox.hide()

        #IP group box layouts

        self.IP_groupBox = QtGui.QGroupBox("IP Inputs")
        self.IP_groupBox.setFont(self.grp_heading_font)
        self.ip_file_layout_lb_v = QVBoxLayout()

        self.ip_file_select_layout_lb_h = QHBoxLayout()
        self.ip_file_select_layout_lb_h.setAlignment(QtCore.Qt.AlignLeft)
        self.ip_file_layout_lb_v.addLayout(self.ip_file_select_layout_lb_h)

        self.IP_groupBox.setMaximumHeight(135)
        self.IP_groupBox.setLayout(self.ip_file_layout_lb_v)
        self.left_base_layout_v.addWidget(self.IP_groupBox)

        self.IP_groupBox.hide()

        # Commands  group box selection

        self.Commands_groupBox = QtGui.QGroupBox("Commands Inputs")
        self.Commands_groupBox.setFont(self.grp_heading_font)
        self.commands_label_layout_lb_v = QVBoxLayout()

        self.default_chkbx_layout_lb_h = QHBoxLayout()
        self.commands_file_layout_lb_h = QHBoxLayout()
        self.commands_file_layout_lb_h.setAlignment(QtCore.Qt.AlignLeft)
        self.commands_custom_box_layout_lb_h = QHBoxLayout()
        self.none_radio_btn_layout_lb_h = QHBoxLayout()

        self.commands_label_layout_lb_v.addLayout(
            self.default_chkbx_layout_lb_h)
        self.commands_label_layout_lb_v.addLayout(
            self.commands_file_layout_lb_h)
        self.commands_label_layout_lb_v.addLayout(
            self.commands_custom_box_layout_lb_h)
        self.commands_label_layout_lb_v.addLayout(
            self.none_radio_btn_layout_lb_h)

        self.Commands_groupBox.setMaximumHeight(225)
        self.Commands_groupBox.setAlignment(QtCore.Qt.AlignLeft)
        self.Commands_groupBox.setLayout(self.commands_label_layout_lb_v)
        self.left_base_layout_v.addWidget(self.Commands_groupBox)

        self.Commands_groupBox.hide()

        # results group box

        self.results_groupBox = QtGui.QGroupBox("Results")
        self.results_groupBox.setFont(self.grp_heading_font)
        self.results_layout_lb_v = QVBoxLayout()

        self.output_layout_lb_h = QHBoxLayout()
        self.output_layout_lb_h.setAlignment(QtCore.Qt.AlignLeft)

        self.results_layout_lb_v.addLayout(self.output_layout_lb_h)

        self.results_groupBox.setLayout(self.results_layout_lb_v)
        self.left_base_layout_v.addWidget(self.results_groupBox)

        self.results_groupBox.hide()

        # Go Button

        self.go_btn_layout_lb_h = QHBoxLayout()
        self.left_base_layout_v.addLayout(self.go_btn_layout_lb_h)

        # Right and Left Widget on individual layouts

        self.left_base_widget.setLayout(self.left_base_layout_v)
        self.right_base_widget.setLayout(self.right_base_layout_v)

        #### just to see right base layout

        self.right_base = QtGui.QTextEdit(self.gui)
        self.right_base.setStyleSheet(
            """QToolTip { background-color: #00bfff; color: black; border: black solid 2px  }"""
        )
        self.right_base.setObjectName("IP_Address")
        self.right_base_layout_v.addWidget(self.right_base)
        #         self.right_base.setMaximumHeight(500)
        self.right_base.hide()

        self.snap_gif = QtGui.QLabel(self.gui)
        self.snap_gif.setText("")
        self.snap_gif.setStyleSheet("background-color: None")
        self.snap_gif.setPixmap(QtGui.QPixmap("Capture.png"))
        self.snap_gif.setObjectName("logo_corner")
        self.right_base_layout_v.addWidget(self.snap_gif)

        ######

        self.gui.setWindowTitle('SPEED +  3.0')
        self.gui.setWindowIcon(QtGui.QIcon(":/logo/Wind_icon.png"))
        self.gui.setAutoFillBackground(True)

        self.corner_logolabel = QtGui.QLabel(self.gui)
        self.corner_logolabel.setText("")
        self.corner_logolabel.setStyleSheet("background-color: None")
        self.corner_logolabel.setPixmap(QtGui.QPixmap(":/logo/ATT-LOGO-2.png"))
        self.corner_logolabel.setObjectName("logo_corner")
        #         self.corner_logo_layout_v.setAlignment(QtCore.Qt.AlignTop)
        self.corner_logo_layout_v.setAlignment(
            int(QtCore.Qt.AlignTop | QtCore.Qt.AlignRight))
        self.corner_logo_layout_v.addWidget(self.corner_logolabel)

        self.msgBox.setWindowIcon(QtGui.QIcon(":/logo/Wind_icon.png"))
        self.msgBox.setFont(QtGui.QFont("Verdana", 8, QtGui.QFont.Normal))
        self.make_menu()
        ## gif at&t logo
        #         self.movie_screen = QLabel()
        #         self.movie_screen.setSizePolicy(QtGui.QSizePolicy.Expanding,QtGui.QSizePolicy.Expanding)
        #         self.movie_screen.setAlignment(QtCore.Qt.AlignCenter)
        #         self.right_base_layout_v.addWidget(self.movie_screen)
        #
        #         ag_file = "C:/Users/rg012f/eclipse-workspace/poojan_try/giphy.gif"
        #         self.movie = QtGui.QMovie(ag_file, QtCore.QByteArray(), None)
        #         self.movie.setCacheMode(QtGui.QMovie.CacheAll)
        #         self.movie.setSpeed(75)
        #         self.movie_screen.setMovie(self.movie)
        #
        #
        #         self.movie.setPaused(True)
        #         self.movie.start()
        #         self.right_base_widget.show()
        #         time.sleep(2)

        ######################### order of the below funtion calls is importnant change them wisely#####################
        self.check_save_username()
        self.create_views()
        self.left_radio_controls()
        self.connect_child_views()

    def make_menu(self):
        self.myMenu = self.gui.menuBar()

        self.file = self.myMenu.addMenu('&File')

        self.file.addAction("&Select Output Folder...",
                            self.select_destination, "Ctrl+O")
        self.file.addAction("&Exit", self.closewindow, "Ctrl+X")

        self.file = self.myMenu.addMenu('&Help')

        self.file.addAction("&About...", self.about_tool, "Ctrl+H")

    def check_save_username(self):
        print("Yo reached save username")
        try:
            f = open('Username.txt', 'r')
            lines = f.readlines()
            if len(lines):
                self.save_username_checked = True
            else:
                self.save_username_checked = False
        except Exception as ex:
            print(ex)

    def select_destination(self, ):

        fld = QtGui.QFileDialog.getExistingDirectory(self.gui,
                                                     'Select Output Folder')
        self.output_folder = str(fld)

    def closewindow(self):
        self.gui.close()

    def about_tool(self):
        abouttool = "Speed + v3.0 \n\nThis tool is useful to fetch, push, extract, compare device configs \n"

        self.msgBox.setText(abouttool)
        self.msgBox.setWindowTitle("About Speed +")
        self.msgBox.show()

    def left_radio_controls(self):

        # ============================    main radio options selection :
        radio_font = QtGui.QFont("Verdana", 10, QtGui.QFont.Normal)

        self.get_radio_option = QtGui.QRadioButton(self.gui)
        self.get_radio_option.setFont(radio_font)
        self.get_radio_option.setText("Get")
        self.radio_option_layout_lb_h.addWidget(self.get_radio_option)

        self.push_radio_option = QtGui.QRadioButton(self.gui)
        self.push_radio_option.setFont(radio_font)
        self.push_radio_option.setText("Push")
        self.radio_option_layout_lb_h.addWidget(self.push_radio_option)

        self.extract_radio_option = QtGui.QRadioButton(self.gui)
        self.extract_radio_option.setFont(radio_font)
        self.extract_radio_option.setText("Extract")
        self.radio_option_layout_lb_h.addWidget(self.extract_radio_option)

        self.compare_radio_option = QtGui.QRadioButton(self.gui)
        self.compare_radio_option.setFont(radio_font)
        self.compare_radio_option.setText("Compare")
        self.radio_option_layout_lb_h.addWidget(self.compare_radio_option)

    def disp_get_options(self):

        self.snap_gif.show()
        self.push_view.hide_push()
        self.excel_view.userOptionextract.hide()
        self.compare_view.main_widget.hide()
        self.get_view.display_get()

    def disp_push_options(self):

        self.snap_gif.show()
        self.get_view.hide_get()
        self.excel_view.userOptionextract.hide()
        self.compare_view.main_widget.hide()
        self.push_view.display_push()
        self.validations.hide_right_common()

    def disp_ext_options(self):

        self.get_view.hide_get()
        self.push_view.hide_push()
        self.compare_view.main_widget.hide()
        self.excel_view.display_excel_portion()
        self.validations.hide_right_common()

    def disp_comp_options(self):

        self.get_view.hide_get()
        self.push_view.hide_push()
        self.excel_view.userOptionextract.hide()
        self.compare_view.display_comapre_portion()
        self.validations.hide_right_common()

    def connect_child_views(self):

        self.get_radio_option.clicked.connect(self.disp_get_options)
        self.push_radio_option.clicked.connect(self.disp_push_options)
        self.extract_radio_option.clicked.connect(self.disp_ext_options)
        self.compare_radio_option.clicked.connect(self.disp_comp_options)

        self.base_left.go_button.clicked.connect(self.connect_validate_option)

    def connect_validate_option(self):

        self.validations.validate_user_inputs(
        )  # passing self to validation class method , other end this self is last_parent

    def create_views(self):

        self.base_left = left_base(
            self
        )  # we are passing main GUI and also local self as 'last_parent' to left base view to update variables

        self.get_view = get_controls(self.gui, self.base_left)
        self.push_view = push_controls(self.gui, self.base_left)
        self.excel_view = extract_excel(self.gui, self.base_left)
        self.compare_view = compare_op_results(self)

    def show_gif_right_base(self, path, layout):
        print("ui parent view show_gif_right_base line 394")
        self.movie_screen = QLabel()
        self.movie_screen.setSizePolicy(QtGui.QSizePolicy.Expanding,
                                        QtGui.QSizePolicy.Expanding)
        self.movie_screen.setAlignment(QtCore.Qt.AlignCenter)
        layout.addWidget(self.movie_screen)

        ag_file = path
        self.movie = QtGui.QMovie(ag_file, QtCore.QByteArray(), None)
        self.movie.setCacheMode(QtGui.QMovie.CacheAll)
        self.movie.setSpeed(75)
        self.movie_screen.setMovie(self.movie)

        #"C:/Users/rg012f/eclipse-workspace/poojan_try/giphy.gif"
        self.movie.setPaused(True)
        self.movie.start()
#         self.right_base_widget.setLayout(layout)
#         self.right_base_widget.show()

    def hide_gif_right_base(self):
        self.movie_screen.hide()
コード例 #21
0
ファイル: MO_project.py プロジェクト: Filios92/ProjektMO
class Airport_project_UI(QWidget):

    airports = [
        'KRK',
        'LA',
        'LIS'
    ]

    elitism_possibly_values = ['true', 'false']

    max_flights_list = ['1', '2', '3', '4', '5']

    def __init__(self):
        QWidget.__init__(self)
        self.params = {}

       # self.setMinimumSize(600, 250)
        #self.setWindowTitle("Medody Optymalizacji - Projekt")
       # self.setIcon()

        self.start_airport_label = QLabel("Start airport:", self)
        self.start_airport_label.move(5, 10)
        self.start_airport = QLineEdit(self)
        self.start_airport.setText('1')
        #self.start_airport.addItems(self.airports)
        self.start_airport.setMinimumHeight(20)
        self.start_airport.setMaximumHeight(20)
        self.start_airport.setMinimumWidth(60)
        self.start_airport.setMaximumWidth(60)
        self.start_airport.move(150, 5)

#TODO function to convert names of airport to indexes

        self.destination_airport_label = QLabel("Destination airport:", self)
        self.destination_airport_label.move(5, 40)
        self.destination_airport = QLineEdit(self)
        self.destination_airport.setText('2')
       # self.destination_airport.addItems(self.airports)
        self.destination_airport.setMinimumHeight(20)
        self.destination_airport.setMaximumHeight(20)
        self.destination_airport.setMaximumWidth(60)
        self.destination_airport.setMinimumWidth(60)
        self.destination_airport.move(150, 35)

        self.max_flights_label = QLabel("max number of flights:", self)
        self.max_flights_label.move(5, 70)
        self.max_flights = QLineEdit(self)
        self.max_flights.setText("3")
        #self.max_flights.addItems(self.max_flights_list)
        self.max_flights.setMaximumHeight(20)
        self.max_flights.setMinimumHeight(20)
        self.max_flights.setMaximumWidth(60)
        self.max_flights.setMinimumWidth(60)
        #self.max_flights.setMinimumWidth(60)
        self.max_flights.move(150, 65)

        self.cost_weight_label = QLabel("max cost weights:", self)
        self.cost_weight_label.move(5, 100)
        self.cost_weight = QLineEdit(self)
        self.cost_weight.setText("4")
        self.cost_weight.setMinimumWidth(60)
        self.cost_weight.setMaximumWidth(60)
        self.cost_weight.setMinimumHeight(20)
        self.cost_weight.setMaximumHeight(20)
        self.cost_weight.move(150, 95)


        self.time_weight_label = QLabel("time weight:", self)
        self.time_weight_label.move(5, 130)
        self.time_weight = QLineEdit(self)
        self.time_weight.setText("5")
        self.time_weight.setMinimumWidth(60)
        self.time_weight.setMaximumWidth(60)
        self.time_weight.setMinimumHeight(20)
        self.time_weight.setMaximumHeight(20)
        self.time_weight.move(150, 125)

        self.pop_size_label = QLabel("pop size:", self)
        self.pop_size_label.move(5, 160)  # +30

        self.pop_size = QLineEdit(self)
        self.pop_size.setText("6")
        self.pop_size.setMinimumWidth(60)
        self.pop_size.setMaximumWidth(60)
        self.pop_size.setMinimumHeight(20)
        self.pop_size.setMaximumHeight(20)
        self.pop_size.move(150, 155) # +30

        self.generation_label = QLabel("generations:", self)
        self.generation_label.move(5, 190)  # +30

        self.generation = QLineEdit(self)
        self.generation.setText("7")
        self.generation.setMinimumWidth(60)
        self.generation.setMaximumWidth(60)
        self.generation.setMinimumHeight(20)
        self.generation.setMaximumHeight(20)
        self.generation.move(150, 185) # +30

        self.mutation_rate_label = QLabel("mutation rate:", self)
        self.mutation_rate_label.move(5, 210)  # +30

        self.mutation_rate = QLineEdit(self)
        self.mutation_rate.setText("8")
        self.mutation_rate.setMinimumWidth(60)
        self.mutation_rate.setMaximumWidth(60)
        self.mutation_rate.setMinimumHeight(20)
        self.mutation_rate.setMaximumHeight(20)
        self.mutation_rate.move(150, 215) # +30


        self.tournament_size_label = QLabel("tournament size:", self)
        self.tournament_size_label.move(5, 240)  # +30

        self.tournament_size = QLineEdit(self)
        self.tournament_size.setText("9")
        self.tournament_size.setMinimumWidth(60)
        self.tournament_size.setMaximumWidth(60)
        self.tournament_size.setMinimumHeight(20)
        self.tournament_size.setMaximumHeight(20)
        self.tournament_size.move(150, 245) # +30

        self.elitism_label = QLabel("elitism:", self)
        self.elitism_label.move(5, 270)  # +30

        self.elitism = QComboBox(self)
        self.elitism.addItems(self.elitism_possibly_values)
        self.elitism.setMinimumWidth(60)
        self.elitism.setMaximumWidth(60)
        self.elitism.setMinimumHeight(20)
        self.elitism.setMaximumHeight(20)
        self.elitism.move(150, 275) # +30

        self.destination_min_label = QLabel("dest min:", self)
        self.destination_min_label.move(5, 300)  # +30

        self.dest_min = QLineEdit(self)
        self.dest_min.setText("4")
        self.dest_min.setMinimumWidth(60)
        self.dest_min.setMaximumWidth(60)
        self.dest_min.setMinimumHeight(20)
        self.dest_min.setMaximumHeight(20)
        self.dest_min.move(150, 305) # +30

        self.destination_max_label = QLabel("dest max:", self)
        self.destination_max_label.move(5, 330)  # +30

        self.dest_max = QLineEdit(self)
        self.dest_max.setText("10")
        self.dest_max.setMinimumWidth(60)
        self.dest_max.setMaximumWidth(60)
        self.dest_max.setMinimumHeight(20)
        self.dest_max.setMaximumHeight(20)
        self.dest_max.move(150, 335) # +30

        self.generate_graph_button = QPushButton("Generate graph!", self)
        self.generate_graph_button.setMinimumWidth(170)
        self.generate_graph_button.move(25, 365)

        self.start_evolution_button = QPushButton("Start evolution!", self)
        self.start_evolution_button.setMinimumWidth(170)
        self.start_evolution_button.move(25, 395)

        self.start_evolution_button.clicked.connect(self.start_evolution)
        self.generate_graph_button.clicked.connect(self.generate_graph)
        #self.get_list_of_possibly_airports() #TODO to have full list of airports in QComboBox

    def generate_graph(self):
        self.params = {
            'graph'           : None,
            'start_idx'       : int(self.start_airport.text()),
            'end_idx'         : int(self.destination_airport.text()),
            'max_flights'     : int(self.max_flights.text()),
            'cost_weight'     : int(self.cost_weight.text()),
            'time_weight'     : int(self.time_weight.text()),
            'pop_size'        : int(self.pop_size.text()),
            'generations'     : int(self.generation.text()),
            'mutation_rate'   : float(self.mutation_rate.text()),
            'tournament_size' : int(self.tournament_size.text()),
            'elitism'         : bool(self.elitism.currentText()),
            'dest_min'        : int(self.dest_min.text()),
            'dest_max'        : int(self.dest_max.text()),
            'max_flights'     : 4,
        }
        data = DataGenerator()
        DataGenerator.DESTINATIONS_MIN = self.params['dest_min']
        DataGenerator.DESTINATIONS_MAX = self.params['dest_max']

        # if input_graph_file is not None:
        #     data.load_saved_graph(input_graph_file)
        #
        # else:
        #TODO ilosc lotnisk
        data.load_new_data(10)
        data.create_graph()

        # if graph_save_file is not None:
        #     data.save_graph(graph_save_file)

        testsuite_airports = data.get_airports()
        testsuite_graph = data.get_graph()

        self.graph = GraphManager(self.params['max_flights'])
        self.graph.set_graph(testsuite_graph, testsuite_airports)

        airports_parser = Testsuite_airports_parser(testsuite_airports)


    def start_evolution(self):
        import pprint
        self.params = {
        'graph'           : self.graph,
        'start_idx'       : int(self.start_airport.text()),
        'end_idx'         : int(self.destination_airport.text()),
        'max_flights'     : int(self.max_flights.text()),
        'cost_weight'     : int(self.cost_weight.text()),
        'time_weight'     : int(self.time_weight.text()),
        'pop_size'        : int(self.pop_size.text()),
        'generations'     : int(self.generation.text()),
        'mutation_rate'   : float(self.mutation_rate.text()),
        'tournament_size' : int(self.tournament_size.text()),
        'elitism'         : bool(self.elitism.currentText()),
        'dest_min'        : int(self.dest_min.text()),
        'dest_max'        : int(self.dest_max.text()),
        }
        # pprint.pprint(params)
        self.output_of_algorithm = sys.__stdout__
        GA.run_with_params(self.params)
        self.newwindow()

    def newwindow(self):
        import pprint
        print("##############")
        pprint.pprint(self.output_of_algorithm)
        print("##############")
        self.wid = QWidget()
        self.wid.resize(250, 150)
        self.wid.setWindowTitle('NewWindow')
        self.result = QTextEdit(self.wid)
        self.result.setText(str(self.output_of_algorithm))
        #self.start_airport.addItems(self.airports)
        self.result.setMinimumHeight(200)
        self.result.setMaximumHeight(200)
        self.result.setMinimumWidth(600)
        self.start_airport.setMaximumWidth(600)
        # self.start_airport.move(150, 5)
        self.output_of_algorithm = None
        self.wid.show()
コード例 #22
0
    print 'import ZipFile'
    import sys
    print 'import sys'
    import urllib2
    print 'import urllib2'
    import time
    print 'all imports done (time last import)'
    raise

    print 'Before anything apart from importing'

    app = QApplication(sys.argv)
    update_dialog = QWidget()
    update_dialog.resize(350, 100)
    update_dialog.setWindowTitle('Updater')
    update_dialog.show()

    update_dialog_lbl = QLabel(update_dialog)
    update_dialog_lbl.setGeometry(10, 40, 340, 25)
    update_dialog_lbl.setOpenExternalLinks(True)
    update_dialog_lbl.setText('Updating! (Screen will hang, it\'s normal.)')

    # sys.exit(app.exec_())

    running = True
    versionNew = 0
    success = False

    updater()
    # this code will stall the rest of the code until the thread says 'running = False'
    # This means that the code past this will run only after the thread said
コード例 #23
0
class BrowserApp(object):
    def __init__(self):
        self.app = QApplication(sys.argv)
        self.window = QWidget()
        self.window.resize(1280, 1024)

        self.main_layout = QHBoxLayout()
        self.window.setLayout(self.main_layout)
        self.window.show()

        self.left_pane = self.create_browser_pane('Left')
        self.main_layout.addWidget(self.left_pane['main'])

        self.right_pane = self.create_browser_pane('Right')
        self.main_layout.addWidget(self.right_pane['main'])

        self.panes = [self.left_pane, self.right_pane]

    def run(self):
        self.window.show()
        self.app.exec_()

    def create_browser_pane(self, title):
        # Create the pane widget
        pane = QWidget()
        layout = QVBoxLayout()
        pane.setLayout(layout)

        # Create a label for the title
        title_bar = QLabel("")
        # title_bar.setFixedHeight(32)
        title_bar.setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Minimum)
        title_bar.show()
        layout.addWidget(title_bar)

        # Create the "address" box
        address_bar = QLineEdit()
        layout.addWidget(address_bar)

        # todo: we could add some tool buttons here..
        toolbar_layout = QHBoxLayout()
        toolbar = QWidget()
        toolbar.setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Minimum)
        toolbar.setLayout(toolbar_layout)
        tool_stop = QPushButton()
        tool_stop.setText('Stop')
        toolbar_layout.addWidget(tool_stop)
        tool_back = QPushButton()
        tool_back.setText('Back')
        toolbar_layout.addWidget(tool_back)
        tool_forward = QPushButton()
        tool_forward.setText('Forward')
        toolbar_layout.addWidget(tool_forward)
        tool_reload = QPushButton()
        tool_reload.setText('Reload')
        toolbar_layout.addWidget(tool_reload)
        layout.addWidget(toolbar)

        # Create the web view
        web_view = QWebView()
        web_view.setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Expanding)
        layout.addWidget(web_view)

        # Create a status bar
        status_bar = QLabel("")
        status_bar.setFixedHeight(32)
        status_bar.show()
        status_bar.setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Minimum)
        layout.addWidget(status_bar)

        # Attach signal handlers
        address_bar.editingFinished.connect(functools.partial(
            self._addrbar_changed, address_bar, web_view))

        web_view.loadStarted.connect(
            lambda: status_bar.setText('Loading...'))
        web_view.loadProgress.connect(
            lambda p: status_bar.setText('Loading ({0}%)...'.format(p)))
        web_view.loadFinished.connect(
            lambda p: status_bar.setText('Ready.'.format(p)))
        web_view.statusBarMessage.connect(status_bar.setText)
        web_view.titleChanged.connect(title_bar.setText)
        web_view.urlChanged.connect(functools.partial(
            self._url_changed, web_view))
        web_view.urlChanged.connect(
            lambda url: address_bar.setText(url.toString()))

        # Connect tool buttons
        tool_stop.clicked.connect(web_view.stop)
        tool_back.clicked.connect(web_view.back)
        tool_forward.clicked.connect(web_view.forward)
        tool_reload.clicked.connect(web_view.reload)

        return {
            'main': pane,
            'layout': layout,
            'title': title_bar,
            'address': address_bar,
            'web_view': web_view,
            'status': status_bar,
        }

    def _addrbar_changed(self, addrbar, webview):
        webview.load(addrbar.text())

    def _url_changed(self, webview, qurl):
        """
        The url in a webview just changed: update URLs in other panes as well!
        """

        print("URL Changed -- updating other panes")
        url = urlparse.urlparse(qurl.toString())

        for pane in self.panes:
            if pane['web_view'] is webview:
                continue

            # Update the pane url with path/query/fragment
            try:
                this_pane_url = urlparse.urlparse(
                    pane['web_view'].url().toString())
            except:
                pass  # todo: mark error
            else:
                u = this_pane_url._replace(
                    path=url.path,
                    query=url.query,
                    fragment=url.fragment)
                new_url = urlparse.urlunparse(u)

                # Check here is to prevent bouncing!
                if pane['web_view'].url().toString() != new_url:
                    pane['web_view'].load(new_url)
コード例 #24
0
ファイル: test_gui.py プロジェクト: socialdevices/manager
from PySide.QtGui import QLabel
from PySide.QtGui import QPushButton
from PySide.QtGui import QWidget
from PySide.QtGui import QVBoxLayout
from PySide.QtGui import QHBoxLayout

def foo(parent):

    vbox = QHBoxLayout()

    vbox.addWidget( QLabel('this is the label of component', parent) )
    vbox.addWidget( QPushButton(parent, 'button') )

    return vbox
 
# Create the application object
app = QApplication(sys.argv)
 
# Create a simple dialog box
mainw = QWidget(sys.argv)
mainw.resize(250,150)
mainw.setWindowTitle('Mainview (plugins)')
mainlayout = QVBoxLayout()
mainlayout.addLayout( foo(mainw) )

mainw.setLayout( mainlayout )
mainw.show()
sys.exit(app.exec_())


コード例 #25
0
from PySide.QtGui import QMainWindow, QWidget, QScrollArea, QPushButton
from PySide.QtGui import QVBoxLayout, QHBoxLayout

mainWindow = QMainWindow()

mainWindow.show()

centralWidget = QWidget()

centralWidget.show()

centralWidgetLayout = QVBoxLayout()
centralWidget.setLayout(centralWidgetLayout)

mainWindow.setCentralWidget(centralWidget)

buttonsWidget = QWidget()
buttonsLayout = QHBoxLayout()
buttonsWidget.setLayout(buttonsLayout)

buttonsWidget.show()

for char in 'abracadabra':
    buttonsLayout.addWidget(QPushButton("Button '{0}'".format(char)))


scrolledButtonsWidget = QScrollArea()
scrolledButtonsWidget.setWidgetResizable(True)
"""
This property holds whether the scroll area should resize the view widget.
コード例 #26
0
        )

restore_button = QPushButton("Restore selected")
restore_button.clicked.connect(restore_clicked)
box.addWidget(restore_button)


autosave_button = QPushButton("Autosave Start")

auto_save = False


def toggle_autosave():
    global auto_save
    if not auto_save:
        timer.start(AUTOSAVE_TIMEOUT)
        auto_save = True
        autosave_button.setText("Autosave Stop")
    else:
        timer.stop()
        auto_save = False
        autosave_button.setText("Autosave Start")

autosave_button.clicked.connect(toggle_autosave)
box.addWidget(autosave_button)

update_save_list()
main_window.show()

sys.exit(app.exec_())
コード例 #27
0
 def show(self):
     QWidget.show(self)
     self.called = True
コード例 #28
0
ファイル: main.py プロジェクト: ckorn/livestreamer-ui
    def __init__( self ):

        url = QLineEdit()
        quality = QLineEdit()
        urlLabel = QLabel( 'Url' )
        qualityLabel = QLabel( 'Quality' )
        messages = QTextEdit()
        messagesLabel = QLabel( 'Messages' )
        links = QTableWidget( 0, 2 )
        linksLabel = QLabel( 'Links' )
        clearMessages = QPushButton( 'Clear Messages' )
        checkIfOnline = QPushButton( 'Check If Online' )
        addSelectedLink = QPushButton( 'Add Link' )
        removeSelectedLink = QPushButton( 'Remove Selected Link' )

        messages.setReadOnly( True )

        links.setHorizontalHeaderLabels( [ 'Url', 'Status' ] )
        links.horizontalHeader().setResizeMode( QHeaderView.Stretch )
        links.horizontalHeader().setResizeMode( 1, QHeaderView.Fixed )

            # set the events

        url.returnPressed.connect( self.select_stream_from_entry )
        quality.returnPressed.connect( self.select_stream_from_entry )
        links.itemDoubleClicked.connect( self.select_stream_from_link )
        clearMessages.clicked.connect( self.clear_messages )
        checkIfOnline.clicked.connect( self.check_if_online )
        addSelectedLink.clicked.connect( self.add_selected_link )
        removeSelectedLink.clicked.connect( self.remove_selected_link )

        #set shortcut
        checkIfOnline.setShortcut(QKeySequence(Qt.Key_F5))

            # set the layouts

        mainLayout = QGridLayout()

            # first row
        mainLayout.addWidget( urlLabel, 0, 0, 1, 1 )    # spans 1 column
        mainLayout.addWidget( qualityLabel, 0, 1, 1, 1 )# spans 1 column
        mainLayout.addWidget( linksLabel, 0, 2, 1, 3 )  # spans 3 columns

            # second row  (links widget occupies 2 rows and 2 columns)
        mainLayout.addWidget( url, 1, 0, 1, 1 )         # spans 1 column
        mainLayout.addWidget( quality, 1, 1, 1, 1 )     # spans 1 column
        mainLayout.addWidget( links, 1, 2, 2, 3 )   # spans 3 columns

            # third row (messages widget occupies 2 columns)
        mainLayout.addWidget( messages, 2, 0, 1, 2 )

            # fourth row
        mainLayout.addWidget( messagesLabel, 3, 0 )
        mainLayout.addWidget( clearMessages, 3, 1 )
        mainLayout.addWidget( checkIfOnline, 3, 2 )
        mainLayout.addWidget( addSelectedLink, 3, 3 )
        mainLayout.addWidget( removeSelectedLink, 3, 4 )


        window = QWidget()

        window.setLayout( mainLayout )
        window.setWindowTitle( 'Live Streamer' )
        window.resize( 700, 350 )
        window.show()

        self.url_ui = url
        self.quality_ui = quality
        self.messages_ui = messages
        self.links_ui = links
        self.window_ui = window

        self.links = set()

        self.data_file = os.path.join(os.path.expanduser("~"), ".config", "livestreamer-ui", "data.txt")
        folder=os.path.dirname(self.data_file)
        if not os.path.exists(folder):
                os.makedirs(folder)
コード例 #29
0
    def __init__(self):

        url = QLineEdit()
        urlLabel = QLabel('Url')
        messages = QTextEdit()
        messagesLabel = QLabel('Messages')
        links = QTableWidget(0, 2)
        linksLabel = QLabel('Links')
        clearMessages = QPushButton('Clear Messages')
        checkIfOnline = QPushButton('Check If Online')
        addSelectedLink = QPushButton('Add Link')
        removeSelectedLink = QPushButton('Remove Selected Link')

        messages.setReadOnly(True)

        links.setHorizontalHeaderLabels(['Url', 'Status'])
        links.horizontalHeader().setResizeMode(QHeaderView.Stretch)
        links.horizontalHeader().setResizeMode(1, QHeaderView.Fixed)

        # set the events

        url.returnPressed.connect(self.select_stream_from_entry)
        links.itemDoubleClicked.connect(self.select_stream_from_link)
        clearMessages.clicked.connect(self.clear_messages)
        checkIfOnline.clicked.connect(self.check_if_online)
        addSelectedLink.clicked.connect(self.add_selected_link)
        removeSelectedLink.clicked.connect(self.remove_selected_link)

        # set the layouts

        mainLayout = QGridLayout()

        # first row
        mainLayout.addWidget(urlLabel, 0, 0, 1, 2)  # spans 2 columns
        mainLayout.addWidget(linksLabel, 0, 2, 1, 3)  # spans 3 columns

        # second row  (links widget occupies 2 rows and 2 columns)
        mainLayout.addWidget(url, 1, 0, 1, 2)  # spans 2 columns
        mainLayout.addWidget(links, 1, 2, 2, 3)  # spans 3 columns

        # third row (messages widget occupies 2 columns)
        mainLayout.addWidget(messages, 2, 0, 1, 2)

        # fourth row
        mainLayout.addWidget(messagesLabel, 3, 0)
        mainLayout.addWidget(clearMessages, 3, 1)
        mainLayout.addWidget(checkIfOnline, 3, 2)
        mainLayout.addWidget(addSelectedLink, 3, 3)
        mainLayout.addWidget(removeSelectedLink, 3, 4)

        window = QWidget()

        window.setLayout(mainLayout)
        window.setWindowTitle('Live Streamer')
        window.resize(700, 350)
        window.show()

        self.url_ui = url
        self.messages_ui = messages
        self.links_ui = links
        self.window_ui = window

        self.links = set()
コード例 #30
0
ファイル: stock_overview.py プロジェクト: wiz21b/koi
    TextLinePrototype('fullname', _('Fullname'), editable=False)
]

filter = PersistentFilter(QueryLineEdit(), 'supply_orders_overview')
service = None


def apply_filter(f):
    if f == '12134':
        objects = service.findByCode(f)
        model.loadObjects(objects)
    else:
        objects = service.findByQueryString(f)
        model.loadObjects(objects)


filter.activated.connect(apply_filter)

model = PrototypedModelView(prototype, None)
list_view = PrototypedQuickView(prototype, None)
detail_view = None

layout = hlayout(SubFrame("Stock items", vlayout(filter, list_view), None),
                 SubFrame("Details", detail_view, None))

w = QWidget()
w.setLayout(l)
w.show()

app.exec_()
コード例 #31
0
        self.setValue(value)
        self.valueChanged.emit(value)


if __name__ == '__main__':
    from PySide.QtGui import QApplication
    from PySide.QtGui import QVBoxLayout
    app = QApplication([])

    sliderWidget = SliderWidget()
    sliderWidget.setName("Test value")
    sliderWidget.setRange([-100, 200])
    sliderWidget.setValue(300)

    label = QLabel()

    def updateLabel(value):
        label.setText(str(sliderWidget.value()))

    sliderWidget.valueChanged.connect(updateLabel)

    layout = QVBoxLayout()
    layout.addWidget(QLabel("Test sliders"))
    layout.addWidget(sliderWidget)
    layout.addWidget(label)

    widget = QWidget()
    widget.setLayout(layout)
    widget.show()
    app.exec_()
コード例 #32
0
ファイル: rivalctl-qt.py プロジェクト: tomko222/rivalctl
cpi_two_label = QLabel("CPI2 (1600):")
layout.addWidget(cpi_two_label, 2, 2)
cpi_two_spin_box = QSpinBox()
cpi_two_spin_box.setRange(50, 6500)
cpi_two_spin_box.setValue(1600)
cpi_two_spin_box.setSingleStep(50)
layout.addWidget(cpi_two_spin_box, 2, 3)

# polling_rate
polling_rate_label = QLabel("Polling rate (1000):")
layout.addWidget(polling_rate_label, 3, 0)
polling_rate_combo_box = QComboBox()
polling_rate_combo_box.addItem("1000")
polling_rate_combo_box.addItem("500")
polling_rate_combo_box.addItem("250")
polling_rate_combo_box.addItem("125")
layout.addWidget(polling_rate_combo_box, 3, 1)

save_push_button = QPushButton("Save settings")
save_push_button.clicked.connect(save_slot)
layout.addWidget(save_push_button, 4, 0)

reset_push_button = QPushButton("Reset to factory defaults")
layout.addWidget(reset_push_button, 4, 1)

central_widget = QWidget()
central_widget.setWindowTitle("Rivalctl-Qt")
central_widget.setLayout(layout)
central_widget.show()

app.exec_()