示例#1
0
    def __init__(self):
        super().__init__()

        self.settings = QSettings('olle-orks.org', 'Bodenpython')

        self.setWindowTitle('Mikrokopter Bodenpython')
        self.communicator = None
        self.list_widget = None
        self.pingpong_widget = None
        self.serialport_selector = None

        saved_geometry = self.settings.value(self.SETTINGS_MAINWINDOW_GEOMETRY)
        if saved_geometry:
            self.restoreGeometry(saved_geometry)

        self.serialport_selector = SerialPortSelector(self.settings)
        self.serialport_selector.accepted.connect(self.serialport_selected)
        self.serialport_selector.rejected.connect(self.close)

        selector_layout = QHBoxLayout()
        selector_layout.addStretch()
        selector_layout.addWidget(self.serialport_selector)
        selector_layout.addStretch()

        central_widget = QWidget()
        central_layout = QVBoxLayout()
        central_layout.addStretch()
        central_layout.addLayout(selector_layout)
        central_layout.addStretch()
        central_widget.setLayout(central_layout)

        self.setCentralWidget(central_widget)

        QTimer.singleShot(0, self.set_window_icon)
示例#2
0
    def __init__(self, parent):
        super(PercentSlider, self).__init__(parent)

        self._slider = QSlider(Qt.Vertical, self)
        self._slider.setMinimum(-100)
        self._slider.setMaximum(100)
        self._slider.setValue(0)
        self._slider.setTickInterval(100)
        self._slider.setTickPosition(QSlider.TicksBothSides)
        self._slider.valueChanged.connect(lambda: self._spinbox.setValue(self._slider.value()))

        self._spinbox = QSpinBox(self)
        self._spinbox.setMinimum(-100)
        self._spinbox.setMaximum(100)
        self._spinbox.setValue(0)
        self._spinbox.valueChanged.connect(lambda: self._slider.setValue(self._spinbox.value()))

        self._zero_button = make_icon_button("hand-stop-o", "Zero setpoint", self, on_clicked=self.zero)

        layout = QVBoxLayout(self)
        sub_layout = QHBoxLayout(self)
        sub_layout.addStretch()
        sub_layout.addWidget(self._slider)
        sub_layout.addStretch()
        layout.addLayout(sub_layout)
        layout.addWidget(self._spinbox)
        layout.addWidget(self._zero_button)
        self.setLayout(layout)

        self.setMinimumHeight(400)
示例#3
0
    def __init__(self, *args):
        super().__init__(BrickletAnalogIn, *args)

        self.ai = self.device

        # the firmware version of a EEPROM Bricklet can (under common circumstances)
        # not change during the lifetime of an EEPROM Bricklet plugin. therefore,
        # it's okay to make final decisions based on it here
        self.has_range = self.firmware_version >= (2, 0, 1)
        self.has_averaging = self.firmware_version >= (2, 0, 3)

        self.cbe_voltage = CallbackEmulator(self.ai.get_voltage,
                                            None,
                                            self.cb_voltage,
                                            self.increase_error_count)

        self.current_voltage = CurveValueWrapper() # float, V

        plots = [('Voltage', Qt.red, self.current_voltage, format_voltage)]
        self.plot_widget = PlotWidget('Voltage [V]', plots, y_resolution=0.001)

        layout = QVBoxLayout(self)
        layout.addWidget(self.plot_widget)

        if self.has_range:
            self.combo_range = QComboBox()
            self.combo_range.addItem('Automatic', BrickletAnalogIn.RANGE_AUTOMATIC)

            if self.has_averaging:
                self.combo_range.addItem('0 - 3.30 V', BrickletAnalogIn.RANGE_UP_TO_3V)

            self.combo_range.addItem('0 - 6.05 V', BrickletAnalogIn.RANGE_UP_TO_6V)
            self.combo_range.addItem('0 - 10.32 V', BrickletAnalogIn.RANGE_UP_TO_10V)
            self.combo_range.addItem('0 - 36.30 V', BrickletAnalogIn.RANGE_UP_TO_36V)
            self.combo_range.addItem('0 - 45.00 V', BrickletAnalogIn.RANGE_UP_TO_45V)
            self.combo_range.currentIndexChanged.connect(self.range_changed)

            hlayout = QHBoxLayout()
            hlayout.addWidget(QLabel('Range:'))
            hlayout.addWidget(self.combo_range)
            hlayout.addStretch()

            if self.has_averaging:
                self.spin_average = QSpinBox()
                self.spin_average.setMinimum(0)
                self.spin_average.setMaximum(255)
                self.spin_average.setSingleStep(1)
                self.spin_average.setValue(50)
                self.spin_average.editingFinished.connect(self.spin_average_finished)

                hlayout.addWidget(QLabel('Average Length:'))
                hlayout.addWidget(self.spin_average)

            line = QFrame()
            line.setObjectName("line")
            line.setFrameShape(QFrame.HLine)
            line.setFrameShadow(QFrame.Sunken)

            layout.addWidget(line)
            layout.addLayout(hlayout)
示例#4
0
    def __init__(self, main_window, items):

        """
        Connects to menu_btn_clicked signal
        and also emits it when button is clicked.
        """

        super().__init__()
        self.hide()

        hbox = QHBoxLayout()
        hbox.setSpacing(0)
        hbox.setContentsMargins(0, 0, 0, 0)
        self.setLayout(hbox)
        hbox.addSpacing(25)

        main_window.communication.user_selected.connect(self._show)
        main_window.communication.menu_btn_clicked.connect(self._item_selected)

        self.buttons = []
        labels = [each['sys'] for each in options.CONTROL_BUTTONS_LABELS]

        for i, text in enumerate(labels):
            btn = QPushButton(_(text))
            self.buttons.append(btn)
            if i == 0:
                btn.setStyleSheet(self.BUTTON_SELECTED_QSS)

            btn.clicked.connect(functools.partial(main_window.communication.menu_btn_clicked.emit, i))
            hbox.addWidget(btn)

        SelectItemMenu(main_window, self, items)
        self.buttons[0].setText(_(main_window.items[0].name))
        self.buttons[0].setFixedWidth(int(main_window.width() / 5))
        hbox.addStretch()
示例#5
0
    def __init__(self, parent=None):
        super(ResultHandler, self).__init__()
        self.setWindowTitle('Dash results')
        self.control_label = QLabel()
        self.rendered_label = QLabel()
        self.diff_label = QLabel()

        self.mask_label = QLabel()
        self.new_mask_label = QLabel()

        self.scrollArea = QScrollArea()
        self.widget = QWidget()

        self.test_name_label = QLabel()
        grid = QGridLayout()
        grid.addWidget(self.test_name_label, 0, 0)
        grid.addWidget(QLabel('Control'), 1, 0)
        grid.addWidget(QLabel('Rendered'), 1, 1)
        grid.addWidget(QLabel('Difference'), 1, 2)
        grid.addWidget(self.control_label, 2, 0)
        grid.addWidget(self.rendered_label, 2, 1)
        grid.addWidget(self.diff_label, 2, 2)
        grid.addWidget(QLabel('Current Mask'), 3, 0)
        grid.addWidget(QLabel('New Mask'), 3, 1)
        grid.addWidget(self.mask_label, 4, 0)
        grid.addWidget(self.new_mask_label, 4, 1)

        self.widget.setLayout(grid)
        self.scrollArea.setWidget(self.widget)
        v_layout = QVBoxLayout()
        v_layout.addWidget(self.scrollArea, 1)

        next_image_button = QPushButton()
        next_image_button.setText('Skip')
        next_image_button.pressed.connect(self.load_next)

        self.overload_spin = QDoubleSpinBox()
        self.overload_spin.setMinimum(1)
        self.overload_spin.setMaximum(255)
        self.overload_spin.setValue(1)
        self.overload_spin.valueChanged.connect(lambda: save_mask_button.setEnabled(False))

        preview_mask_button = QPushButton()
        preview_mask_button.setText('Preview New Mask')
        preview_mask_button.pressed.connect(self.preview_mask)
        preview_mask_button.pressed.connect(lambda: save_mask_button.setEnabled(True))

        save_mask_button = QPushButton()
        save_mask_button.setText('Save New Mask')
        save_mask_button.pressed.connect(self.save_mask)

        button_layout = QHBoxLayout()
        button_layout.addWidget(next_image_button)
        button_layout.addWidget(QLabel('Mask diff multiplier:'))
        button_layout.addWidget(self.overload_spin)
        button_layout.addWidget(preview_mask_button)
        button_layout.addWidget(save_mask_button)
        button_layout.addStretch()
        v_layout.addLayout(button_layout)
        self.setLayout(v_layout)
示例#6
0
def show_info_dialog( caption, parent, initial_text ):
    dialog = QDialog( parent )
    dialog.setWindowTitle( caption )
    # Create OK and Cancel buttons in a horizontal box.
    ok_button = QPushButton("OK")
    ok_button.setDefault(True)
    ok_button.clicked.connect(dialog.accept)
    cancel_button = QPushButton("Cancel")
    cancel_button.setDefault(False)
    cancel_button.clicked.connect(dialog.reject)
    hbox = QHBoxLayout()
    hbox.addWidget(cancel_button,0)
    hbox.addStretch()
    hbox.addWidget(ok_button,0)
    # Lay out a Plain Text Edit above the buttons.
    vbox = QVBoxLayout()
    pt_editor = QPlainTextEdit()
    pt_editor.document().setPlainText( initial_text )
    vbox.addWidget(pt_editor,1)
    vbox.addLayout(hbox,0)
    dialog.setLayout(vbox)
    result = dialog.exec_()
    if result :
        return pt_editor.document().toPlainText()
    else :
        return None
 def createStart(self):
     self.startButton = QPushButton('Start battle')
     layout = QHBoxLayout()
     layout.addStretch(1)
     layout.addWidget(self.startButton)
     layout.addStretch(1)
     return layout
示例#8
0
    def __init__(self, *args):
        super().__init__(BrickletTemperatureV2, *args)

        self.tem = self.device

        self.cbe_temperature = CallbackEmulator(self.tem.get_temperature,
                                                None,
                                                self.cb_temperature,
                                                self.increase_error_count)

        self.current_temperature = CurveValueWrapper() # float, °C

        plots_temperature = [('Temperature', Qt.red, self.current_temperature, '{} °C'.format)]
        self.plot_widget_temperature = PlotWidget('Temperature [°C]', plots_temperature, y_resolution=0.01)

        self.enable_heater = QCheckBox("Enable Heater")
        self.enable_heater.stateChanged.connect(self.enable_heater_changed)

        layout_plot = QHBoxLayout()
        layout_plot.addWidget(self.plot_widget_temperature)

        layout_config = QHBoxLayout()
        layout_config.addStretch()
        layout_config.addWidget(self.enable_heater)
        layout_config.addStretch()

        layout_main = QVBoxLayout(self)
        layout_main.addLayout(layout_plot)
        layout_main.addLayout(layout_config)
示例#9
0
    def __init__(self, parent):
        super(CharacterDialog, self).__init__(parent)
        self.setWindowTitle(_("KeepKey Seed Recovery"))
        self.character_pos = 0
        self.word_pos = 0
        self.loop = QEventLoop()
        self.word_help = QLabel()
        self.char_buttons = []

        vbox = QVBoxLayout(self)
        vbox.addWidget(WWLabel(CHARACTER_RECOVERY))
        hbox = QHBoxLayout()
        hbox.addWidget(self.word_help)
        for i in range(4):
            char_button = CharacterButton('*')
            char_button.setMaximumWidth(36)
            self.char_buttons.append(char_button)
            hbox.addWidget(char_button)
        self.accept_button = CharacterButton(_("Accept Word"))
        self.accept_button.clicked.connect(partial(self.process_key, 32))
        self.rejected.connect(partial(self.loop.exit, 1))
        hbox.addWidget(self.accept_button)
        hbox.addStretch(1)
        vbox.addLayout(hbox)

        self.finished_button = QPushButton(_("Seed Entered"))
        self.cancel_button = QPushButton(_("Cancel"))
        self.finished_button.clicked.connect(partial(self.process_key,
                                                     Qt.Key_Return))
        self.cancel_button.clicked.connect(self.rejected)
        buttons = Buttons(self.finished_button, self.cancel_button)
        vbox.addSpacing(40)
        vbox.addLayout(buttons)
        self.refresh()
        self.show()
示例#10
0
class PreviewWidget(QScrollArea):

    def __init__(self, parent=None):
        super(PreviewWidget, self).__init__(parent)
        self.setWidgetResizable(True)
        self.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOn)
        self.widget = QWidget()
        self.layout = QHBoxLayout()
        self.layout.addStretch(1)
        self.layout.setContentsMargins(0, 0, 0, 0)
        self.widget.setLayout(self.layout)
        self.setWidget(self.widget)

    def removeLast(self):
        item = self.layout.takeAt(0)
        if item:
            item.widget().deleteLater()

    def resizeEvent(self, event):
        self.widget.setFixedHeight(self.viewport().height())
        super(PreviewWidget, self).resizeEvent(event)

    def addPixmap(self, pixmap):
        label = ImageLabel(pixmap, self)
        self.layout.insertWidget(0, label)
示例#11
0
 def __init__(self, title, text, image, contributors, parent=None):
     super(AboutDialog, self).__init__(parent)
     layout = QVBoxLayout()
     titleLayout = QHBoxLayout()
     name_versionLabel = QLabel(title)
     contentsLayout = QHBoxLayout()
     aboutBrowser = QTextBrowser()
     aboutBrowser.append(text)
     aboutBrowser.setOpenExternalLinks(True)
     creditsBrowser = QTextBrowser()
     creditsBrowser.append(contributors)
     creditsBrowser.setOpenExternalLinks(True)
     TabWidget = QTabWidget()
     TabWidget.addTab(aboutBrowser, self.tr('About'))
     TabWidget.addTab(creditsBrowser, self.tr('Contributors'))
     aboutBrowser.moveCursor(QTextCursor.Start)
     creditsBrowser.moveCursor(QTextCursor.Start)
     imageLabel = QLabel()
     imageLabel.setPixmap(QPixmap(image))
     titleLayout.addWidget(imageLabel)
     titleLayout.addWidget(name_versionLabel)
     titleLayout.addStretch()
     contentsLayout.addWidget(TabWidget)
     buttonLayout = QHBoxLayout()
     buttonBox = QDialogButtonBox(QDialogButtonBox.Ok)
     buttonLayout.addWidget(buttonBox)
     layout.addLayout(titleLayout)
     layout.addLayout(contentsLayout)
     layout.addLayout(buttonLayout)
     self.setLayout(layout)
     buttonBox.clicked.connect(self.accept)
     self.setMinimumSize(QSize(380, 400))
     self.setWindowTitle(self.tr('About Onkyo QT'))
示例#12
0
    def initialize(self):
        tab_widget = QTabWidget()
        tab1 = QWidget()
        tab2 = QWidget()

        juggle_button = QPushButton("Juggle")
        juggle_button.clicked.connect(self.start_simulation)

        hbox = QHBoxLayout()
        hbox.addStretch(1)
        hbox.addWidget(juggle_button)

        vbox = QVBoxLayout(tab1)
        vbox.addStretch(1)
        vbox.addLayout(hbox)

        hbox2 = QHBoxLayout(tab2)

        tab_widget.addTab(tab1, "Main")
        tab_widget.addTab(tab2, "Other")

        self.setCentralWidget(tab_widget)

        menubar = self.menuBar()
        file_menu = menubar.addMenu('&File')
        help_menu = menubar.addMenu('&Help')
        about = help_menu.addMenu('&About')
        exit_action = QAction(QIcon('exit.png'), '&Exit', self)
        exit_action.triggered.connect(qApp.quit)
        file_menu.addAction(exit_action)

        self.setGeometry(300, 300, 350, 300)
        self.setWindowTitle('Juggling Simulator')
        self.show()
示例#13
0
    def __init__(self):
        super().__init__()

        # 사용한 위젯들을 생성
        lbl1 = QLabel('This is')          #<---- 1
        lbl2 = QLabel('Layout Example')

        okButton = QPushButton("OK")   
        cancelButton = QPushButton("Cancel")

        hbox = QHBoxLayout()      #<---- 2
        hbox.addStretch(1)        #<---- 3
        hbox.addWidget(okButton)  #<---- 4
        hbox.addWidget(cancelButton)  #<---- 5

        vbox = QVBoxLayout()      #<---- 6
        vbox.addWidget(lbl1)      #<---- 7
        vbox.addWidget(lbl2)      #<---- 8
        vbox.addLayout(hbox)      #<---- 9

        window = QWidget()        #<---- 10
        window.setLayout(vbox)    #<---- 11
        self.setCentralWidget(window)  #<---- 12

        self.setGeometry(300, 300, 300, 150)
        self.setWindowTitle('Layout Example')    
        self.show()
示例#14
0
	def init_ui(self):
		path = os.getcwd()
		url = path + HTM_FILE
		self.webView.setUrl(QtCore.QUrl(url))
		self.webView.page().loadFinished.connect(self.load_finished)  # for test

		self.inputText.setEnabled(False)
		self.inputText.setAcceptRichText(False)
		self.inputText.setToolTip("每行一组经纬度,纬度lat在前\n" + "以空格、逗号或制表符分隔")

		self.runButton.clicked.connect(self.add_points)  # show all points in input text window
		self.clrButton.clicked.connect(self.clr_points)

		buttonBox = QHBoxLayout()  # button box
		buttonBox.addStretch()
		buttonBox.addWidget(self.runButton)
		buttonBox.addWidget(self.clrButton)

		rightBox = QVBoxLayout()  # right box
		rightBox.addWidget(self.sourceType)
		rightBox.addWidget(self.inputText)
		rightBox.addLayout(buttonBox)
		rightBox.addWidget(self.statusBar)

		layout = QHBoxLayout()  # main box
		layout.addWidget(self.webView)
		layout.addLayout(rightBox)

		self.setLayout(layout)
		self.setWindowTitle('经纬度地图显示')
		self.show()
示例#15
0
    def __init__(self, parent, node):
        super(FileServerWidget, self).__init__(parent)
        self.setTitle('File server (uavcan.protocol.file.*)')

        self._node = node
        self._file_server = None

        self._path_widgets = []

        self._start_button = make_icon_button('rocket', 'Launch/stop the file server', self,
                                              checkable=True,
                                              on_clicked=self._on_start_stop)
        self._start_button.setEnabled(False)

        self._tmr = QTimer(self)
        self._tmr.setSingleShot(False)
        self._tmr.timeout.connect(self._update_on_timer)
        self._tmr.start(500)

        self._add_path_button = \
            make_icon_button('plus', 'Add lookup path (lookup paths can be modified while the server is running)',
                             self, on_clicked=self._on_add_path)

        layout = QVBoxLayout(self)

        controls_layout = QHBoxLayout(self)
        controls_layout.addWidget(self._start_button)
        controls_layout.addWidget(self._add_path_button)
        controls_layout.addStretch(1)

        layout.addLayout(controls_layout)
        self.setLayout(layout)
示例#16
0
文件: aide.py 项目: wxgeo/geophar
    def __init__(self, parent):
        QDialog.__init__(self, parent)
        self.setWindowTitle("Configuration systeme")
        self.setPalette(white_palette)

        panel = QWidget(self)

        panelSizer = QVBoxLayout()

        textes = informations_configuration().split("\n")

        for i, texte in enumerate(textes):
            if texte.startswith("+ "):
                textes[i] = '<i>' + texte + '</i>'
        t = QLabel('<br>'.join(textes), panel)
        panelSizer.addWidget(t)


        btnOK = QPushButton("OK", panel)
        btnOK.clicked.connect(self.close)
        btnCopier = QPushButton("Copier", panel)
        btnCopier.clicked.connect(self.copier)

        sizer = QHBoxLayout()
        sizer.addWidget(btnOK)
        sizer.addStretch()
        sizer.addWidget(btnCopier)
        panelSizer.addLayout(sizer)

        panel.setLayout(panelSizer)

        topSizer = QHBoxLayout()
        topSizer.addWidget(panel)

        self.setLayout(topSizer)
 def packInHStretch(self, widgets):
     layout = QHBoxLayout()
     layout.addStretch(1)
     for widget in widgets:
         layout.addWidget(widget)
         layout.addStretch(1)
     return layout
示例#18
0
文件: command.py 项目: hugsy/cemu
    def __init__(self, parent, *args, **kwargs):
        super(CommandWidget, self).__init__()
        self.parent = parent
        sc = self.parent.parent.shortcuts
        layout = QHBoxLayout()
        layout.addStretch(1)

        self.runButton = QPushButton("Run all code")
        self.runButton.clicked.connect(self.parent.runCode)
        self.runButton.setShortcut(sc.shortcut("emulator_run_all"))

        self.stepButton = QPushButton("Next instruction")
        self.stepButton.clicked.connect(self.parent.stepCode)
        self.stepButton.setShortcut(sc.shortcut("emulator_step"))

        self.stopButton = QPushButton("Stop")
        self.stopButton.setShortcut(sc.shortcut("emulator_stop"))
        self.stopButton.clicked.connect( self.parent.stopCode )

        self.checkAsmButton = QPushButton("Check assembly code")
        self.checkAsmButton.setShortcut(sc.shortcut("emulator_check"))
        self.checkAsmButton.clicked.connect(self.parent.checkAsmCode)

        layout.addWidget(self.runButton)
        layout.addWidget(self.stepButton)
        layout.addWidget(self.stopButton)
        layout.addWidget(self.checkAsmButton)

        self.setLayout(layout)
        return
示例#19
0
文件: charview.py 项目: B-Rich/PPQT2
 def _uic(self):
     mainLayout = QVBoxLayout()
     self.setLayout(mainLayout)
     topLayout = QHBoxLayout()
     topLayout.setContentsMargins(0,0,0,0)
     mainLayout.addLayout(topLayout,0)
     # Lay out the refresh button and filter popup
     self.refresh = QPushButton(
         _TR('Button to reload all data in char panel',
             'Refresh')
         )
     topLayout.addWidget(self.refresh,0)
     topLayout.addStretch(1) # push filters to the right
     self.popup = QComboBox()
     # Set choices in popup, must match to the lambdas
     # defined in CharFilter.set_filter()
     self.popup.addItem(
         _TR('char panel: show all characters',
             'All')
     )
     self.popup.addItem(
         _TR('char panel: show non-ascii characters',
             'not 7-bit')
     )
     self.popup.addItem(
         _TR('char panel: show non-latin-1',
             'not Latin-1')
     )
     topLayout.addWidget(self.popup,0)
     # Set up the table view, the actual visible table
     self.view = QTableView()
     self.view.setCornerButtonEnabled(False)
     self.view.setWordWrap(False)
     self.view.setAlternatingRowColors(True)
     mainLayout.addWidget(self.view,1) # give it all the stretch
示例#20
0
    def __init__(self, parent, titre, contenu, fonction_modif):
        QDialog.__init__(self, parent)
        self.setWindowTitle(titre)
        sizer = QVBoxLayout()
        self.parent = parent
        self.fonction_modif = fonction_modif
        self.texte = EditeurPython(self)
#        self.texte.setMinimumSize(300, 10)
        self.texte.setText(contenu)
##        self.texte.SetInsertionPointEnd()
        sizer.addWidget(self.texte)

        boutons = QHBoxLayout()
        self.btn_modif = QPushButton("Modifier - F5")
        boutons.addWidget(self.btn_modif)
        self.btn_esc = QPushButton("Annuler - ESC")
        boutons.addStretch()
        boutons.addWidget(self.btn_esc)
        sizer.addLayout(boutons)
        self.setLayout(sizer)

        self.btn_modif.clicked.connect(self.executer)
        self.btn_esc.clicked.connect(self.close)

        self.setMinimumSize(400, 500)
        self.texte.setFocus()
示例#21
0
 def initUI(self):
     self.resize(800,600)
     self.center()
     self.setWindowTitle('OxySensor')
     
     okButton = QPushButton("OK")
     cancelButton = QPushButton("Cancel")
     
     
     hbox = QHBoxLayout()
     hbox.addStretch(1)
     hbox.addWidget(okButton)
     hbox.addWidget(cancelButton)
     
     vbox = QVBoxLayout()
     #vbox.addStretch(1)
     self.gl_widget = GLWidget()
     vbox.addWidget(self.gl_widget)
     vbox.addLayout(hbox)
     
     mainWidget = QWidget(self)
     mainWidget.setLayout(vbox)
     
     self.setCentralWidget(mainWidget)
     
     
     self.show()
示例#22
0
 def addTypeBar(self,types):
     typebar = QHBoxLayout();
     typebar.addStretch(1)
     for tp in types:
         if isinstance(tp,Type):
             icon = QIcon('types/%s.png' % tp)
         elif isinstance(tp,Orb):
             icon = QIcon('orbs/%s.png' % tp)
         button = QToolButton()
         button.setIcon(icon)
         button.setCheckable(True)
         button.setContentsMargins(0,0,0,0)
         button.setFixedSize(22,22)
         button.setChecked(tp in self.skill.scope)
         def buttonFuncMaker(x):
             def buttonFunc(y):
                 if y:
                     self.skill.scope.update((x,))
                 else:
                     self.skill.scope.difference_update((x,))
                 self.skillsChanged.emit()
             return buttonFunc
         button.toggled[bool].connect(buttonFuncMaker(tp))
         typebar.addWidget(button)
     typebar.addStretch(1)
     typebar.setSpacing(0)
     typebar.setContentsMargins(0,0,0,0)
     typebar.setAlignment(Qt.AlignCenter)
     self.layout.addLayout(typebar)
示例#23
0
    def __init__(self):
        super().__init__()

        self.setWindowTitle('MiniGrid Gym Environment')

        self.imgLabel = QLabel()
        self.imgLabel.setFrameStyle(QFrame.Panel | QFrame.Sunken)

        # Arrange widgets horizontally
        hbox = QHBoxLayout()
        hbox.addStretch(1)
        hbox.addWidget(self.imgLabel)
        hbox.addStretch(1)

        # Create a main widget for the window
        mainWidget = QWidget(self)
        self.setCentralWidget(mainWidget)
        mainWidget.setLayout(hbox)

        # Show the application window
        self.show()
        self.setFocus()

        self.closed = False

        # Callback for keyboard events
        self.keyDownCb = None
示例#24
0
文件: ui.py 项目: dq5070410/FeelUOwn
class PlayerControlPanel(FFrame):
    def __init__(self, app, parent=None):
        super().__init__(parent)
        self._app = app

        self._layout = QHBoxLayout(self)
        self.previous_btn = PlayerControlButton(self._app, '上一首', self)
        self.pp_btn = PlayerControlButton(self._app, '播放', self)
        self.next_btn = PlayerControlButton(self._app, '下一首', self)
        self.progress_slider = ProgressSlider(self._app, self)
        self.volume_slider = VolumeSlider(self._app, self)
        self.progress_label = ProgressLabel(self._app, '00:00/00:00', self)

        self._btn_container = FFrame(self)
        self._slider_container = FFrame(self)

        self._bc_layout = QHBoxLayout(self._btn_container)
        self._sc_layout = QHBoxLayout(self._slider_container)

        self.setObjectName('pc_panel')
        self.set_theme_style()
        self.setup_ui()

    def set_theme_style(self):
        theme = self._app.theme_manager.current_theme
        style_str = '''
            #{0} {{
                background: transparent;
                color: {1};
            }}
        '''.format(self.objectName(),
                   theme.foreground.name(),
                   theme.color0.name())
        self.setStyleSheet(style_str)

    def setup_ui(self):
        self._btn_container.setFixedWidth(140)
        self._slider_container.setMinimumWidth(700)
        self.progress_label.setFixedWidth(90)

        self._layout.setSpacing(0)
        self._layout.setContentsMargins(0, 0, 0, 0)
        self._bc_layout.setSpacing(0)
        self._bc_layout.setContentsMargins(0, 0, 0, 0)

        self._bc_layout.addWidget(self.previous_btn)
        self._bc_layout.addStretch(1)
        self._bc_layout.addWidget(self.pp_btn)
        self._bc_layout.addStretch(1)
        self._bc_layout.addWidget(self.next_btn)

        self._sc_layout.addWidget(self.progress_slider)
        self._sc_layout.addSpacing(2)
        self._sc_layout.addWidget(self.progress_label)
        self._sc_layout.addSpacing(5)
        self._sc_layout.addWidget(self.volume_slider)

        self._layout.addWidget(self._btn_container)
        self._layout.addSpacing(10)
        self._layout.addWidget(self._slider_container)
示例#25
0
    def __initWidgets(self):
        minimalSizePolicy = QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)

        # List of subtitles
        subListDelegate = SubListItemDelegate()
        self._model = QStandardItemModel(0, 3, self)
        self._model.setHorizontalHeaderLabels([_("Begin"), _("End"), _("Subtitle")])
        self._subList = QTableView(self)
        self._subList.setModel(self._model)
        self._subList.setItemDelegateForColumn(0, subListDelegate)
        self._subList.setItemDelegateForColumn(1, subListDelegate)
        self._subList.horizontalHeader().setSectionResizeMode(2, QHeaderView.Stretch)

        self._searchBar = SearchBar(self)
        self._searchBar.hide()

        # Top toolbar
        toolbar = QHBoxLayout()
        toolbar.setAlignment(Qt.AlignLeft)
        #toolbar.addWidget(someWidget....)
        toolbar.addStretch(1)

        # Main layout
        grid = QGridLayout()
        grid.setSpacing(10)
        grid.setContentsMargins(0, 3, 0, 0)
        grid.addLayout(toolbar, 0, 0, 1, 1) # stretch to the right
        grid.addWidget(self._subList, 1, 0)
        grid.addWidget(self._searchBar, 2, 0)
        self.setLayout(grid)
    def __init__(self, parent):
        QDialog.__init__(self, parent)
        layout = QVBoxLayout(self)
        self.setLayout(layout)

        layout.addWidget(QLabel('Enter the field name:', self))
        self._field_name_edit = QLineEdit(self)
        self._field_name_edit.textChanged.connect(self._text_changed)
        layout.addWidget(self._field_name_edit)
        layout.addWidget(QLabel('Type:', self))
        self._type_combo = QComboBox(self)
        self._type_combo.addItems(['int', 'float', 'bool', 'str'])
        layout.addWidget(self._type_combo)

        buttons = QWidget(self)
        buttons_layout = QHBoxLayout()
        buttons.setLayout(buttons_layout)
        buttons_layout.addStretch()
        self._ok_button = QPushButton("Ok")
        self._ok_button.setEnabled(False)
        cancel_button = QPushButton("Cancel")
        self._ok_button.clicked.connect(self.accept)
        cancel_button.clicked.connect(self.reject)
        buttons_layout.addWidget(self._ok_button)
        buttons_layout.addWidget(cancel_button)
        layout.addWidget(buttons)
示例#27
0
    def __init__(self, parent):
        super().__init__(parent)

        self._counts = {}

        self._summary_label = QLabel('', self)
        self._summary_label.linkActivated.connect(self._on_category_link_clicked)

        self._prev_next_label = QLabel('', self)
        self._prev_next_label.linkActivated.connect(self._on_prev_next_link_clicked)

        layout = QHBoxLayout(self)
        layout.setContentsMargins(0, 0, 0, 0)
        layout.addWidget(self._summary_label)
        layout.addStretch()
        layout.addWidget(self._prev_next_label)

        self.setFocusProxy(self._summary_label)

        self._setup_tab_stops(
            self._summary_label,
            self._prev_next_label,
        )

        self._update_summary_label()
        self._update_prev_next_label()
示例#28
0
class BarreOutilsExEqDte(BarreOutils):
    def __init__(self, parent):
        self.parent = parent
        QWidget.__init__(self, parent)
        self._selected_button = None

        self.sizer = QHBoxLayout()

        if self.parent.param('afficher_boutons'):
            self.creer_boutons()

        self.sizer.addStretch()

        self.sizer.addWidget(QLabel("Utilisez cette barre d'outils pour construire les droites (dans le bon ordre).<br>"
                       "<i>Remarque :</i> pour créer une droite, il vous faudra deux points à coordonnées <i>entières</i>."))

        self.sizer.addStretch()
        self.setLayout(self.sizer)
        self.adjustSize()


    def creer_boutons(self):
        self.add("F1", ("Pointeur", "fleche4", "Déplacer ou modifier un objet.", self.curseur)).select()
        self.add("F3", ("Droite", "droite2", "Créer une droite.", self.droite))
        self.add("F4", ("Gommer", "gomme", "Supprimer des objets.", self.gomme))


    def rafraichir(self):
        pass
    def __init__(self, parent, fields):
        QDialog.__init__(self, parent)

        layout = QVBoxLayout(self)

        self._list_elements = QListWidget(self)
        self._fields = dict(fields)
        for field, ftype in fields.items():
            self._list_elements.addItem(field + ' (' + ftype + ')')

        self._list_elements.setSelectionMode(
            QAbstractItemView.ExtendedSelection)

        layout.addWidget(self._list_elements)

        add_remove = AddRemoveButtonBar(self, 'Remove selected field(s)',
                                        self.remove, 'Add field', self.add)
        layout.addWidget(add_remove)

        buttons = QWidget(self)
        buttons_layout = QHBoxLayout()
        buttons.setLayout(buttons_layout)
        buttons_layout.addStretch()
        ok_button = QPushButton("Ok")
        cancel_button = QPushButton("Cancel")
        ok_button.clicked.connect(self.accept)
        cancel_button.clicked.connect(self.reject)
        buttons_layout.addWidget(ok_button)
        buttons_layout.addWidget(cancel_button)
        layout.addWidget(buttons)

        self.setLayout(layout)
示例#30
0
    def __init__(self, panel):
        super(Articulations, self).__init__(panel)
        self.shorthands = QCheckBox(self)
        self.shorthands.setChecked(True)
        self.removemenu = QToolButton(
            self, autoRaise=True, popupMode=QToolButton.InstantPopup, icon=icons.get("edit-clear")
        )

        mainwindow = panel.parent().mainwindow()
        mainwindow.selectionStateChanged.connect(self.removemenu.setEnabled)
        self.removemenu.setEnabled(mainwindow.hasSelection())

        ac = documentactions.DocumentActions.instance(mainwindow).actionCollection
        self.removemenu.addAction(ac.tools_quick_remove_articulations)
        self.removemenu.addAction(ac.tools_quick_remove_ornaments)
        self.removemenu.addAction(ac.tools_quick_remove_instrument_scripts)

        layout = QHBoxLayout()
        layout.addWidget(self.shorthands)
        layout.addWidget(self.removemenu)
        layout.addStretch(1)

        self.layout().addLayout(layout)
        for cls in (ArticulationsGroup, OrnamentsGroup, SignsGroup, OtherGroup):
            self.layout().addWidget(cls(self))
        self.layout().addStretch(1)
        app.translateUI(self)
示例#31
0
class MovieLayout(QWidget):

    def __init__(self, url, movieID, user):
        super().__init__()
        self.controller = MovieController(url)
        self.url = url
        self.user = user
        self.setWindowTitle("Movie Player")
        self.movieID = movieID
        # creating a basic vlc instance
        self.instance = vlc.Instance()
        # creating an empty vlc media player
        self.mediaplayer = self.instance.media_player_new()
        self.isPaused = True
        

#        self.moviebox = QVBoxLayout()
#        self.moviebox.addWidget(self.widget)
#        self.widget.setLayout(self.moviebox)
#        print("here")
        
        self.videoframe = QFrame()
        self.palette = self.videoframe.palette()
        self.palette.setColor (QPalette.Window,
                                QColor(0,0,0))
        self.videoframe.setPalette(self.palette)
        self.videoframe.setAutoFillBackground(True)

        self.positionslider = QSlider(Qt.Horizontal, self)
        self.positionslider.setToolTip("Position")
        self.positionslider.setMaximum(1000)
        self.positionslider.sliderMoved.connect(self.setPosition)

        self.hbuttonbox = QHBoxLayout()
        self.playbutton = QPushButton("Play")
        self.hbuttonbox.addWidget(self.playbutton)


        self.stopbutton = QPushButton("Stop")
        self.hbuttonbox.addWidget(self.stopbutton)
        self.stopbutton.clicked.connect(self.Stop)

        self.hbuttonbox.addStretch(1)
        self.volumeslider = QSlider(Qt.Horizontal, self)
        self.volumeslider.setMaximum(100)
        self.volumeslider.setValue(self.mediaplayer.audio_get_volume())
        self.volumeslider.setToolTip("Volume")
        self.hbuttonbox.addWidget(self.volumeslider)
        self.volumeslider.valueChanged.connect(self.setVolume)

        
        self.vboxlayout = QVBoxLayout()
      
        self.vboxlayout.addWidget(self.videoframe)
        self.vboxlayout.addWidget(self.positionslider)
        self.vboxlayout.addLayout(self.hbuttonbox)

    
        self.comment = QPlainTextEdit()
        

        
        self.comment.setPlaceholderText("Type Comment Here ...")
        self.comment.setFixedHeight(50)
        self.commentbox = QVBoxLayout()
        
        self.commentSubmit = QPushButton("Comment")
        self.commentSubmit.clicked.connect(lambda: self.submitComment())
        self.commentbox.addWidget(self.comment)
        self.commentbox.addWidget(self.commentSubmit)
        
        self.commentSection = QLabel("Comments:\n")
        self.commentSection.setFixedHeight(10)
        self.commentbox.addWidget(self.commentSection)
        self.commentSection_comments = QTextEdit("No Comments Yet")
        self.commentSection_comments.setStyleSheet("QTextEdit {color:black;font-size:13px;font-family: \"Times New Roman\", Times, serif;background-color:transparent;border-style: none}")
        self.commentSection_comments.setReadOnly(True)
        self.commentSection_comments.setFixedHeight(50)
        
        self.commentbox.addWidget(self.commentSection_comments)
        self.vboxlayout.addLayout(self.commentbox)
        
        
        self.setLayout(self.vboxlayout)
        self.playbutton.clicked.connect(lambda: self.PlayPause())
        self.stopbutton.clicked.connect(lambda: self.Stop())

        self.resize(640,480)
       
        self.timer = QTimer(self)
        self.timer.setInterval(500)
        self.timer.timeout.connect(self.updateUI)   
        
        
        
        self.loaded = False
        self.video = pafy.new(self.url) 
        
        self.best = self.video.getbest() 
            
        self.media = self.instance.media_new(self.best.url)
        
        self.mediaplayer.set_media(self.media)
        
        if sys.platform.startswith('linux'): # for Linux using the X Server
            self.mediaplayer.set_xwindow(self.videoframe.winId())
        elif sys.platform == "win32": # for Windows
            self.mediaplayer.set_hwnd(self.videoframe.winId())
        elif sys.platform == "darwin": # for MacOS
            self.mediaplayer.set_nsobject(int(self.videoframe.winId()))
            
        
        self.LoadComments()

    
   
    def submitComment(self):
        if(self.comment.toPlainText() != ""):
            result = self.controller.submitComment(self.movieID, self.comment.toPlainText(), self.user.username)
            if(result == 1):
                self.commentSection_comments.setPlainText(self.user.username + ": " + self.comment.toPlainText() + "\n" + self.commentSection_comments.toPlainText())
    
    
    def LoadComments(self):
        comments = self.controller.getComments(self.movieID)
        comment = ""
        for i in comments:
            comment += i[1] + ": " + i[0] + "\n"
        self.commentSection_comments.setPlainText(comment)
 
    #Plays and pauses the movie, same button changes status from play to pause
    def PlayPause(self):
        print("Play Pause")
        if(self.loaded == False):     
            self.loaded = True     

        if self.mediaplayer.is_playing():
            
            self.mediaplayer.pause()
            self.playbutton.setText("Play")
            self.isPaused = True
        else:
            
            self.mediaplayer.play()
            self.playbutton.setText("Pause")
            self.timer.start()
            self.isPaused = False

    #stops the movie, unloads it, pressing this requires loading the movie again
    def Stop(self):
        self.mediaplayer.stop()
        self.playbutton.setText("Play")

    #Opens the movie from youtube and sets it in the appropriate layout item to be showcased
    #TODO: add and use param (string youtube_url) 
    def OpenFile(self, filename=None):
      
        self.video = pafy.new(self.url) 
        self.best = self.video.getbest()
        self.media = self.instance.media_new(self.best.url)
        self.mediaplayer.set_media(self.media)
        
        if sys.platform.startswith('linux'): # for Linux using the X Server
                self.mediaplayer.set_xwindow(self.videoframe.winId())
        elif sys.platform == "win32": # for Windows
                self.mediaplayer.set_hwnd(self.videoframe.winId())
        elif sys.platform == "darwin": # for MacOS
                self.mediaplayer.set_nsobject(int(self.videoframe.winId()))
    
        
    #Changes the volume of the media player
    def setVolume(self, Volume):
        #Set the volume 
        self.mediaplayer.audio_set_volume(Volume)

    #Sets the position of the video slider, responsible for going to different times in the movie
    def setPosition(self, position):        
        # setting the position to where the slider was dragged
        self.mediaplayer.set_position(position / 1000.0)
        # the vlc MediaPlayer needs a float value between 0 and 1, Qt
        # uses integer variables, so you need a factor; the higher the
        # factor, the more precise are the results
        # (1000 should be enough)

    #function used by timer to keep the movie's time slider indicator in the right position
    def updateUI(self):
        # setting the slider to the desired position     
        self.positionslider.setValue(self.mediaplayer.get_position() * 1000)
示例#32
0
    def __init__(self, parent=None):
        """ 
        """
        print("Skeet")

        super(FITSBrowse, self).__init__(parent)
        self.setAttribute(QtCore.Qt.WA_DeleteOnClose)
        self.setWindowTitle("FITSBrowse")

        self.current_directory = CurrentDirectory(
            "/data/lemi-archive-2016-04/20160427")
        self.model = FitsFileTableModel(self.current_directory)
        self.d_model = DirectoryListModel(self.current_directory)
        self.main_widget = QWidget(self)

        self.dir_text = "Current Directory: {0}".format(
            self.current_directory.cur_dir_path)
        self.cur_dir_label = QLabel(self.dir_text, self)

        self.listLabel = QLabel("&Directories")

        self.list_view = QListView()
        self.listLabel.setBuddy(self.list_view)
        self.list_view.setModel(self.d_model)
        self.list_view.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOn)

        self.list_view.setMinimumWidth(self.list_view.sizeHintForColumn(0))
        self.list_view.setMaximumWidth(self.list_view.sizeHintForColumn(0))

        self.list_view_sm = self.list_view.selectionModel()
        self.list_view.doubleClicked.connect(self.change_directory)

        self.table_view = QTableView()
        self.table_view.setModel(self.model)
        self.table_view.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOn)
        self.table_view_sm = self.table_view.selectionModel()
        self.table_view.doubleClicked.connect(self.display_image)

        list_vbox = QVBoxLayout()
        list_vbox.addWidget(self.listLabel)
        list_vbox.addWidget(self.list_view)
        self.list_widget = QWidget()
        self.list_widget.setLayout(list_vbox)

        #self.list_view.size

        main_layout = QHBoxLayout()
        main_layout.addWidget(self.list_widget)
        main_layout.addWidget(self.table_view)

        button_layout = QHBoxLayout()
        quit_button = QPushButton('Quit', self)
        quit_button.setToolTip('This button quits FITSBrowse')
        quit_button.clicked.connect(QApplication.instance().quit)
        button_layout.addStretch()
        button_layout.addWidget(quit_button)

        sep_line = QFrame()
        sep_line.setFrameShape(QFrame.HLine)

        super_layout = QVBoxLayout(self.main_widget)
        super_layout.addWidget(self.cur_dir_label)
        super_layout.addWidget(sep_line)
        super_layout.addLayout(main_layout)
        super_layout.addLayout(button_layout)

        self.setCentralWidget(self.main_widget)
        QtCore.QTimer.singleShot(0, self.initialLoad)
        x = self.table_view.frameSize()
        x = x.width()
        self.table_view.setMinimumWidth(x)
        self.main_widget.setMinimumHeight(500)
示例#33
0
    def _set_up_ui(self):
        window_size_x = 640
        window_size_y = 480

        vbox = QVBoxLayout()

        self.book_id = QLabel("ID: " + str(self.copy.CopyID))
        top = QHBoxLayout()
        top.addStretch(1)
        top.addWidget(self.book_id)
        vbox.addLayout(top)

        self.fields = dict()
        dic = {'storage': str, 'checked_out': bool}
        for i in dic:
            if dic[i] == bool:
                continue
            line_item = QLabel(str(getattr(self.copy, i)))
            self.fields[i] = line_item
            line_label = QLabel(str(i) + ':')
            line_label.setFixedWidth(100)
            hbox = QHBoxLayout()
            hbox.addWidget(line_label)
            hbox.addWidget(line_item)
            vbox.addLayout(hbox)

        self.table = QTableWidget()
        self._set_up_table(self.table)
        vbox.addWidget(self.table)

        vbox.addStretch()

        edit_button = QPushButton("Copy edit")
        edit_button.setFixedWidth(90)
        edit_button.setFixedHeight(25)
        edit_button.clicked.connect(self.edit)

        book_button = QPushButton("Check out")
        book_button.setFixedWidth(90)
        book_button.setFixedHeight(25)
        book_button.clicked.connect(self.check_out)

        return_button = QPushButton("Return copy")
        return_button.setFixedWidth(90)
        return_button.setFixedHeight(25)
        return_button.clicked.connect(self.return_book)

        delete_button = QPushButton("Delete")
        delete_button.setFixedWidth(90)
        delete_button.setFixedHeight(25)
        delete_button.clicked.connect(self.delete_book)

        add_button_layout = QHBoxLayout()
        add_button_layout.addStretch()
        add_button_layout.addWidget(delete_button)
        add_button_layout.addWidget(edit_button)
        add_button_layout.addWidget(return_button)
        add_button_layout.addWidget(book_button)
        vbox.addLayout(add_button_layout)

        self.setLayout(vbox)
        self.resize(window_size_x, window_size_y)
        self.setWindowTitle("Copy info")
示例#34
0
class QWPopupTableCheck(QWidget):
    """
    """
    def __init__(self, **kwargs):
        parent = kwargs.get('parent', None)
        QWidget.__init__(self, parent)

        self.kwargs = kwargs
        self.list2d_out = []

        win_title = kwargs.get('win_title', None)
        if win_title is not None: self.setWindowTitle(win_title)

        #self.wtab = QWTableOfCheckBoxes(**kwargs)
        self.wtab = CGWPartitionTable(**kwargs)
        #self.make_gui_checkbox()

        self.do_ctrl = kwargs.get('do_ctrl', True)
        self.do_frame = kwargs.get('do_frame', True)

        #self.but_update = QPushButton('&Update')
        #self.but_cancel = QPushButton('&Cancel')
        self.but_apply = QPushButton('&Apply')

        #self.but_update.clicked.connect(self.on_but_update)
        #self.but_cancel.clicked.connect(self.onCancel)
        self.but_apply.clicked.connect(self.onApply)

        self.hbox = QHBoxLayout()
        #self.hbox.addWidget(self.but_update)
        #self.hbox.addStretch(1)
        #self.hbox.addWidget(self.but_cancel)
        self.hbox.addStretch(1)
        self.hbox.addWidget(self.but_apply)

        self.vbox = QVBoxLayout()
        self.vbox.addWidget(self.wtab)
        self.vbox.addLayout(self.hbox)
        self.setLayout(self.vbox)

        self.setIcons()
        self.set_style()

#-----------------------------

    def set_style(self):
        #if not self.do_frame:
        #   self.setWindowFlags(self.windowFlags() | Qt.FramelessWindowHint)
        styleGray = "background-color: rgb(230, 240, 230); color: rgb(0, 0, 0);"  # Gray
        #styleTest = "background-color: rgb(100, 240, 200); color: rgb(0, 0, 0);"
        styleDefault = ""
        self.setStyleSheet(styleDefault)

        self.layout().setContentsMargins(0, 0, 0, 0)

        self.setMinimumWidth(100)
        #self.but_update.setFixedWidth(70)
        #self.but_cancel.setFixedWidth(70)
        self.but_apply.setFixedWidth(70)

        #self.but_update.setStyleSheet(styleGray)
        #self.but_update.setFocusPolicy(Qt.NoFocus)
        #self.but_cancel.setFocusPolicy(Qt.NoFocus)
        #self.but_cancel.setStyleSheet(styleGray)
        self.but_apply.setStyleSheet(styleGray)
        self.but_apply.setEnabled(self.do_ctrl)
        self.but_apply.setFlat(not self.do_ctrl)

        self.setSizePolicy(QSizePolicy.MinimumExpanding,
                           QSizePolicy.MinimumExpanding)

        self.wtab.setFixedHeight(self.wtab.height() + 2)
        self.setFixedWidth(max(self.wtab.width(), 285) + 2)

        #self.but_update.setVisible(False)
        #self.but_cancel.setVisible(False)

        #self.setWindowFlags(Qt.Window | Qt.FramelessWindowHint)
        #self.setWindowFlags(Qt.Window | Qt.CustomizeWindowHint)

    def setIcons(self):
        try:
            from psdaq.control_gui.QWIcons import icon
            icon.set_icons()
            #self.but_cancel.setIcon(icon.icon_button_cancel)
            self.but_apply.setIcon(icon.icon_button_ok)
        except:
            pass

    #def on_but_update(self):
    def update_partition_table(self):
        logger.debug('update_partition_table')
        _, list2d = get_platform(
        )  # [[[True,''], 'test/19670/daq-tst-dev02', 'testClient2b'], ...]
        logger.debug('list2d\n', list2d)

        self.kwargs['tableio'] = list2d
        wtab = CGWPartitionTable(**self.kwargs)
        self.vbox.replaceWidget(self.wtab, wtab)
        #self.vbox.removeWidget(self.hbox)
        #self.vbox.addLayout(self.hbox)
        self.wtab.close()
        del self.wtab
        self.wtab = wtab
        self.set_style()

    #def onCancel(self):
    #    logger.debug('onCancel')
    #    self.reject()

    def onApply(self):
        logger.debug('onApply')
        self.list2d_out = self.wtab.fill_output_object()
        #self.accept()

        dict_platf, list2d = get_platform(
        )  # [[[True,''], 'test/19670/daq-tst-dev02', 'testClient2b'], ...]
        set_platform(dict_platf, self.list2d_out)

        ## 2019-03-13 caf: If Select->Apply is successful, an Allocate transition should be triggered.
        ## 2020-07-29 caf: The Allocate transition will update the active detectors file, if necessary.

        list2d_active = list_active_procs(self.list2d_out)

        if len(list2d_active) == 0:
            logger.warning('NO PROCESS SELECTED!')
        else:
            daq_control().setState('allocated')

    def table_out(self):
        return self.list2d_out
示例#35
0
class ZhuangGeiFX(QDialog):
    def __init__(self, data, chess, job, race, equip):
        super().__init__()
        self.data = data
        self.chess = chess
        self.job = job
        self.race = race
        self.equip = equip
        self.initshow()

    def initshow(self):
        self.setMinimumWidth(504)
        self.setObjectName('ZhuangbeiFX')
        self.spTitle = QLabel('装备分析')
        self.spTitle.setObjectName('Title')
        self.spDoc = QLabel(self.data['equipment_info'].replace(
            '&amp;nbsp;', ''))
        self.spDoc.setObjectName('Doc')
        self.spDoc.setWordWrap(True)
        self.vbox = QVBoxLayout()
        self.vbox.addWidget(self.spTitle)
        self.vbox.addWidget(self.spDoc)
        #装备推荐框架
        self.zbTJFrame = QFrame()
        self.zbTJVbox = QVBoxLayout()

        #遍历站位数据,看有没有装备,有装备的就加入zbTJHbox
        self.zbtj_YLH = []
        self.xjzb_Vbox = []
        #初始化羁绊和职业容器
        job_list = []
        race_list = []

        txData = None
        for item in self.data['hero_location']:
            # 将羁绊和职业数据存进容器
            try:
                chessData = chessId_get_data(self.chess, item['hero_id'])
                if chessData == None:
                    continue

            except:
                continue
            try:
                for job_item in chessData['jobIds'].split(','):
                    job_list.append(job_item)
            except:
                pass
            try:
                for race_item in chessData['raceIds'].split(','):
                    race_list.append(race_item)
            except:
                pass
            zwpath = Path_chess + chessData['name']
            if item['equipment_id'] != '':
                #英雄头像
                self.zbtj_YLH.append(QHBoxLayout())
                self.zbTJVbox.addLayout(self.zbtj_YLH[-1])
                if chessData["price"] == '1':
                    color = '#989898'
                elif chessData["price"] == '2':
                    color = '#58B137'
                elif chessData["price"] == '3':
                    color = '#3678C8'
                elif chessData["price"] == '4':
                    color = '#C81FC8'
                else:
                    color = '#FDBC03'
                tp_yx = QLabel()
                # 让图像适应标签
                tp_yx.setScaledContents(True)
                tp_yx.setPixmap(QPixmap(zwpath))
                tp_yx.setMaximumSize(50, 50)
                tp_yx.setMinimumSize(50, 50)
                tp_yx.setObjectName('tp_yx')
                tp_yx.setStyleSheet(
                    '''#tp_yx{border: 1px solid %s;border-radius: 10px;  }
                                                               ''' % color)

                tp_yx.setToolTip(tanChudataForm(chessData, self.job,
                                                self.race))
                self.zbtj_YLH[-1].addWidget(tp_yx)
                jtbt = QLabel('>')
                jtbt.setObjectName('Title')
                self.zbtj_YLH[-1].addWidget(jtbt)

                for equi in item['equipment_id'].split(','):

                    djzb = equipId_get_data(self.equip, equi)
                    # 将羁绊和职业数据存进容器
                    try:

                        if djzb['jobId'] != '0' and djzb['jobId'] != None:
                            job_list.append(djzb['jobId'])
                    except:
                        pass
                    try:

                        if djzb['raceId'] != '0' and djzb['raceId'] != None:
                            race_list.append(djzb['raceId'])
                    except:
                        pass

                    zbpath = Path_equip + djzb['imagePath'].split('/')[-1]
                    #大件装备

                    tp_djzb = QLabel()
                    # 让图像适应标签
                    tp_djzb.setScaledContents(True)
                    tp_djzb.setPixmap(QPixmap(zbpath))
                    tp_djzb.setMaximumSize(40, 40)
                    tp_djzb.setMinimumSize(40, 40)
                    tp_djzb.setToolTip(tanChu_EquipData(self.equip, djzb))
                    self.zbtj_YLH[-1].addWidget(tp_djzb)
                    #取小装备的id
                    self.xjzb_Vbox.append(QVBoxLayout())
                    self.xjzb_Vbox[-1].addStretch()
                    self.zbtj_YLH[-1].addLayout(self.xjzb_Vbox[-1])
                    for itemXJ in djzb['formula'].split(','):
                        xjzb = equipId_get_data(self.equip, itemXJ)
                        xjzbpath = Path_equip + xjzb['imagePath'].split(
                            '/')[-1]
                        #print('小装备', zbpath)
                        tp_xjzb = QLabel()
                        # 让图像适应标签
                        tp_xjzb.setScaledContents(True)
                        tp_xjzb.setPixmap(QPixmap(xjzbpath))
                        tp_xjzb.setMaximumSize(20, 20)
                        tp_xjzb.setMinimumSize(20, 20)
                        self.xjzb_Vbox[-1].addWidget(tp_xjzb)
                    #一个弹簧..用来控制位置的
                    self.xjzb_Vbox[-1].addStretch()

                self.zbtj_YLH[-1].addStretch()
            """ # 天选羁绊和职业存入
            if 'isChosenHero' in item:

                if item['isChosenHero'] != None:
                    txData = item['isChosenHero']
                    # 天选羁绊id
                    sss = ''
                    for key in txData.keys():
                        sss = key
                    if sss == 'race':
                        race_list.append(txData['race'])
                    else:
                        job_list.append(txData['job'])
                else:
                    pass"""

        #职业分析组件---------------------------------------------
        self.from_job = QFrame()
        self.from_jobHBox = QHBoxLayout()
        #统计总职业数,并且将底图和图标获取
        jb_ss = {}.fromkeys(job_list).keys()
        for ss in jb_ss:
            num = job_list.count(ss)

            if txData != None:
                if sss == 'job' and txData['job'] == ss:
                    test_job = job_get_background_sf(self.job, ss, num, True)
                else:
                    test_job = job_get_background_sf(self.job, ss, num, False)
            else:
                test_job = job_get_background_sf(self.job, ss, num, False)
            if test_job != None:
                #将每一个小组件渲染
                tp_hbox = QHBoxLayout()
                #羁绊背景
                tp_jb_bj = QLabel()
                tp_jb_bj.setScaledContents(True)
                tp_jb_bj.setPixmap(QPixmap(test_job[0]))
                tp_jb_bj.setMaximumSize(30, 34)
                tp_jb_bj.setMinimumSize(30, 34)
                tp_jb_bj.setToolTip(
                    f'''<b style='color:#FFFFFF;'>{test_job[2]['introduce']}<br>{str(test_job[2]['level']).replace('{', '').replace('}', '').replace(',', '<br>')}</b>'''
                )

                #tp_jb_bj上方显示图标
                tp_jb = QLabel(tp_jb_bj)
                tp_jb.move(5, 7)
                tp_jb.setScaledContents(True)
                tp_jb.setPixmap(QPixmap(test_job[1]))
                tp_jb.setMaximumSize(20, 20)
                tp_jb.setMinimumSize(20, 20)
                #羁绊名 文字
                tp_text = QLabel(tp_jb_bj)
                tp_text.setObjectName('JB')
                tp_text.setText(f"{num} " + test_job[2]['name'])

                #将数据加入到每一列的布局中
                tp_hbox.addWidget(tp_jb_bj)
                tp_hbox.addWidget(tp_text)
                self.from_jobHBox.addLayout(tp_hbox)

        self.from_jobHBox.addStretch()

        # 羁绊分析组件---------------------------------------------
        self.from_race = QFrame()
        self.from_raceHBox = QHBoxLayout()
        # 统计总羁绊数,并且将底图和图标获取
        race_ss = {}.fromkeys(race_list).keys()
        for ss in race_ss:
            num = race_list.count(ss)

            if txData != None:
                if sss == 'race' and txData['race'] == ss:
                    test_race = race_get_background_sf(self.race, ss, num,
                                                       True)
                else:
                    test_race = race_get_background_sf(self.race, ss, num,
                                                       False)
            else:
                test_race = race_get_background_sf(self.race, ss, num, False)
            if test_race != None:
                # 将每一个小组件渲染

                tp_hbox = QHBoxLayout()
                # 羁绊背景
                tp_jb_bj = QLabel()
                tp_jb_bj.setScaledContents(True)
                tp_jb_bj.setPixmap(QPixmap(test_race[0]))
                tp_jb_bj.setMaximumSize(30, 34)
                tp_jb_bj.setMinimumSize(30, 34)
                tp_jb_bj.setToolTip(
                    f'''<b style='color:#FFFFFF;'>{test_race[2]['introduce']}<br>{str(test_race[2]['level']).replace('{', '').replace('}', '').replace(',', '<br>')}</b>'''
                )

                # tp_jb_bj上方显示图标
                tp_jb = QLabel(tp_jb_bj)
                tp_jb.move(5, 7)
                tp_jb.setScaledContents(True)
                tp_jb.setPixmap(QPixmap(test_race[1]))
                tp_jb.setMaximumSize(20, 20)
                tp_jb.setMinimumSize(20, 20)
                # 羁绊名 文字
                tp_text = QLabel(tp_jb_bj)
                tp_text.setObjectName('JB')
                tp_text.setText(f"{num} " + test_race[2]['name'])

                # 将数据加入到每一列的布局中
                tp_hbox.addWidget(tp_jb_bj)
                tp_hbox.addWidget(tp_text)
                self.from_raceHBox.addLayout(tp_hbox)
        self.from_raceHBox.addStretch()

        self.zbTJFrame.setLayout(self.zbTJVbox)
        self.from_job.setLayout(self.from_jobHBox)
        self.from_race.setLayout(self.from_raceHBox)
        self.vbox.addWidget(self.zbTJFrame)
        self.vbox.addWidget(self.from_job)
        self.vbox.addWidget(self.from_race)

        self.vbox.setSpacing(2)
        self.setLayout(self.vbox)
        self.setStyleSheet('''
        #ZhuangbeiFX{
        border: 1px solid rgb(185, 185, 185);  
        
    	background-color: rgb(22,26,32);
    	border-right-style:none;
        border-top-style:none;
        }
        #Title{
	    color: #FFFFFF;
	    background: rgba(22,26,32, 200);   
	    font: 75 12pt "微软雅黑";}
	    
	    #Doc{
	    color: #7E807D;
	    border-left-style: 1px solid rgb(185, 185, 185);  
	    background: rgba(22,26,32, 200) ;  
	    font: 75 10pt "微软雅黑";}
	    #JB{
	    color: #FFFFFF;
	    background: rgba(22,26,32, 200);   
	    font: 75 10pt "微软雅黑";}
	    QToolTip{
            border: 2px solid qconicalgradient(cx:0, cy:0, angle:135, stop:0 rgba(255, 255, 0, 69), stop:0.375 rgba(255, 255, 0, 69), stop:0.423533 rgba(251, 255, 0, 145), stop:0.45 rgba(247, 255, 0, 208), stop:0.477581 rgba(255, 244, 71, 130), stop:0.518717 rgba(255, 218, 71, 130), stop:0.55 rgba(255, 255, 0, 255), stop:0.57754 rgba(255, 203, 0, 130), stop:0.625 rgba(255, 255, 0, 69), stop:1 rgba(255, 255, 0, 69));   
	        background-color: rgb(22,26,32);
	        ridge:ridge;
	        padding: 4px;
	        border-radius:10px;
        }
        ''')
示例#36
0
class QtStartWindow(QWidget):
	def __init__(self,master, firmware):
		super(QtStartWindow,self).__init__()
		self.master = master
		#self.master.HVpowersupply.TurnOn()
		#self.master.LVpowersupply.TurnOn()
		self.firmware = firmware
		self.firmwareName = firmware.getBoardName()
		self.connection = self.master.connection
		self.mainLayout = QGridLayout()
		self.setLayout(self.mainLayout)
		self.runFlag = False

		self.setLoginUI()
		self.createHead()
		self.createMain()
		self.createApp()
		self.occupied()

	def setLoginUI(self):
		self.setGeometry(400, 400, 400, 400)  
		self.setWindowTitle('Start a new test')  
		#QApplication.setStyle(QStyleFactory.create('macintosh'))
		#QApplication.setPalette(QApplication.style().standardPalette())
		#QApplication.setPalette(QApplication.palette())
		self.show()

	def createHead(self):
		self.TestBox = QGroupBox()
		testlayout  = QGridLayout()
		TestLabel = QLabel("Test:")
		self.TestCombo = QComboBox()
		self.TestList = getAllTests(self.master.connection)
		self.TestCombo.addItems(self.TestList)
		TestLabel.setBuddy(self.TestCombo)

		testlayout.addWidget(TestLabel,0,0,1,1)
		testlayout.addWidget(self.TestCombo,0,1,1,1)
		self.TestBox.setLayout(testlayout)

		self.firmware.removeAllModule()
		self.BeBoardWidget = BeBoardBox(self.firmware)   #FLAG
		self.BeBoardWidget.changed.connect(self.destroyMain)
		self.BeBoardWidget.changed.connect(self.createMain)

		self.mainLayout.addWidget(self.TestBox,0,0)
		self.mainLayout.addWidget(self.BeBoardWidget,1,0)

	
	def createMain(self):
		self.firmwareCheckBox = QGroupBox()
		firmwarePar  = QGridLayout()
		BoxSize = {
			"SingleSCC" : 1,
			"DualSCC"	: 2,
			"QuadSCC"	: 4
		}
        ## To be finished
		self.ModuleList = []
		for  i, module  in enumerate(self.BeBoardWidget.ModuleList):
			ModuleSummaryBox = SummaryBox(module)
			self.ModuleList.append(ModuleSummaryBox)
			firmwarePar.addWidget(ModuleSummaryBox, math.floor(i/2), math.ceil( i%2 /2), 1, 1)

		self.firmwareCheckBox.setLayout(firmwarePar)

		self.mainLayout.addWidget(self.firmwareCheckBox,2,0)
		
	def destroyMain(self):
		self.firmwareCheckBox.deleteLater()
		self.mainLayout.removeWidget(self.firmwareCheckBox)

	def createApp(self):
		self.AppOption = QGroupBox()
		self.StartLayout = QHBoxLayout()

		self.CancelButton = QPushButton("&Cancel")
		self.CancelButton.clicked.connect(self.release)
		self.CancelButton.clicked.connect(self.closeWindow)

		self.ResetButton = QPushButton("&Reset")
		self.ResetButton.clicked.connect(self.destroyMain)
		self.ResetButton.clicked.connect(self.createMain)

		self.NextButton = QPushButton("&Next")
		self.NextButton.setDefault(True)
		#self.NextButton.setDisabled(True)
		self.NextButton.clicked.connect(self.openRunWindow)

		self.StartLayout.addStretch(1)
		self.StartLayout.addWidget(self.CancelButton)
		self.StartLayout.addWidget(self.ResetButton)
		self.StartLayout.addWidget(self.NextButton)
		self.AppOption.setLayout(self.StartLayout)

		self.mainLayout.addWidget(self.AppOption,3,0)

	def closeWindow(self):
		self.close()

	def occupied(self):
		self.master.ProcessingTest = True

	def release(self):
		self.master.ProcessingTest = False
		self.master.NewTestButton.setDisabled(False)
		self.master.LogoutButton.setDisabled(False)
		self.master.ExitButton.setDisabled(False)

	def setTestList(self):
		self.TestCombo.setDisabled(True)
		currentModule = self.ModuleIDEdit.text()
		localTests = getLocalTests(currentModule)
		if localTests == []:
			self.TestCombo.clear()
			self.TestCombo.addItems(firstTimeList) 
		else:
			self.TestCombo.clear()
			self.TestCombo.addItems(self.TestList)
		self.TestCombo.setDisabled(False)

	def checkFwPar(self):
		GlobalCheck = True
		for item in self.ModuleList:
			GlobalCheck = GlobalCheck and item.getResult()
		return GlobalCheck

	def setupBeBoard(self):
		# Setup the BeBoard
		pass


	def openRunWindow(self):
		for module in self.BeBoardWidget.getModules():
			if module.getID() == "":
				QMessageBox.information(None,"Error","No valid modlue ID!", QMessageBox.Ok)
				return

		if self.checkFwPar() == False:
			QMessageBox().information(None, "Error", "Front-End parameter check failed", QMessageBox.Ok)
			return

		self.firmwareDescription = self.BeBoardWidget.getFirmwareDescription()
		#self.info = [self.firmware.getModuleByIndex(0).getModuleID(), str(self.TestCombo.currentText())]
		self.info = [self.firmware.getModuleByIndex(0).getOpticalGroupID(), str(self.TestCombo.currentText())]
		self.runFlag = True
		self.master.RunNewTest = QtRunWindow(self.master, self.info, self.firmwareDescription)
		self.close()

	def closeEvent(self, event):
		if self.runFlag == True:
			event.accept()
		
		else:
			reply = QMessageBox.question(self, 'Window Close', 'Are you sure you want to quit the test?',
				QMessageBox.Yes | QMessageBox.No, QMessageBox.No)

			if reply == QMessageBox.Yes:
				event.accept()
				self.release()
				#self.master.powersupply.TurnOff()
				print('Window closed')
			else:
				event.ignore()
示例#37
0
def start_window(app: QApplication, window: SimpleGui) -> None:
    """this function create main menu applications"""
    def show_system_status() -> None:
        """This function create dialog window System Status"""
        msgBox = QMessageBox()
        status = SystemStatus.get_status()
        text = "\n".join([elem + ": " + status[elem] for elem in status])
        msgBox.setWindowTitle("Текущий статус системы")
        msgBox.setText(text)
        msgBox.setStandardButtons(QMessageBox.Ok)
        msgBox.exec_()

    def show_changelog() -> None:
        """This function create dialog window Current Changelog"""
        msgBox = QMessageBox()
        msgBox.setWindowTitle("Актуальный список изменений")
        text = "\n".join(
            [elem[0] + ': ' + elem[1] for elem in CHANGELOG[::-1]])
        msgBox.setText(text)
        msgBox.setStandardButtons(QMessageBox.Ok)
        msgBox.exec_()

    def on_off_web_server() -> None:
        """This function on-off web server"""
        if status_server():
            stop_server()
        else:
            start_server()
        msgBox = QMessageBox()
        msgBox.setWindowTitle("Изменение статуса веб-сервера")
        text = "Произведено изменение статуса веб-сервера"
        msgBox.setText(text)
        msgBox.setStandardButtons(QMessageBox.Ok)
        msgBox.exec_()

    def new_stat_window() -> None:
        """Repaint window to Statistic Table"""
        stat_window(window, vbox)

    def new_bugz_window() -> None:
        bugzilla(window, vbox)

    def new_workers_window() -> None:
        workers(window, vbox)

    print("Переход на главное окно")
    window.new_window_title("База ремонтов компании Малахит")

    status_button = QPushButton("Статус системы")
    status_button.clicked.connect(show_system_status)

    changelog_button = QPushButton("Список изменений")
    changelog_button.clicked.connect(show_changelog)

    on_off_server_button = QPushButton("Включить/выключить веб-сервер")
    on_off_server_button.clicked.connect(on_off_web_server)

    stat_button = QPushButton("Статистика работ")
    stat_button.clicked.connect(new_stat_window)

    bugz_button = QPushButton("Баг-трекер")
    bugz_button.clicked.connect(new_bugz_window)

    workers_button = QPushButton("сотрудники")
    workers_button.clicked.connect(new_workers_window)

    hbox = QHBoxLayout()
    hbox.addStretch(1)
    hbox.addWidget(changelog_button)
    hbox.addWidget(status_button)

    hbox1 = QHBoxLayout()
    hbox1.addStretch(1)
    hbox1.addWidget(on_off_server_button)
    hbox1.addWidget(stat_button)

    hbox2 = QHBoxLayout()
    hbox2.addStretch(1)
    hbox2.addWidget(bugz_button)
    hbox2.addWidget(workers_button)

    vbox = QVBoxLayout()
    vbox.addStretch(1)
    vbox.addLayout(hbox2)
    vbox.addLayout(hbox1)
    vbox.addLayout(hbox)

    window.setLayout(vbox)

    sys.exit(app.exec_())
示例#38
0
class Player(QMainWindow):
    """A simple Media Player using VLC and Qt
    """
    def __init__(self, master=None):
        QMainWindow.__init__(self, master)
        self.setWindowTitle("Media Player")

        # creating a basic vlc instance
        self.instance = vlc.Instance()
        # creating an empty vlc media player
        self.mediaplayer = self.instance.media_player_new()

        self.createUI()
        self.isPaused = False

    def createUI(self):
        """Set up the user interface, signals & slots
        """
        self.widget = QWidget(self)
        self.setCentralWidget(self.widget)

        # In this widget, the video will be drawn
        if sys.platform == "darwin":  # for MacOS
            from PyQt5.QtWidgets import QMacCocoaViewContainer
            self.videoframe = QMacCocoaViewContainer(0)
        else:
            self.videoframe = QFrame()
        self.palette = self.videoframe.palette()
        self.palette.setColor(QPalette.Window, QColor(0, 0, 0))
        self.videoframe.setPalette(self.palette)
        self.videoframe.setAutoFillBackground(True)

        self.positionslider = QSlider(Qt.Horizontal, self)
        self.positionslider.setToolTip("Position")
        self.positionslider.setMaximum(1000)
        self.positionslider.sliderMoved.connect(self.setPosition)

        self.hbuttonbox = QHBoxLayout()
        self.playbutton = QPushButton("Play")
        self.hbuttonbox.addWidget(self.playbutton)
        self.playbutton.clicked.connect(self.PlayPause)

        self.stopbutton = QPushButton("Stop")
        self.hbuttonbox.addWidget(self.stopbutton)
        self.stopbutton.clicked.connect(self.Stop)

        self.hbuttonbox.addStretch(1)
        self.volumeslider = QSlider(Qt.Horizontal, self)
        self.volumeslider.setMaximum(100)
        self.volumeslider.setValue(self.mediaplayer.audio_get_volume())
        self.volumeslider.setToolTip("Volume")
        self.hbuttonbox.addWidget(self.volumeslider)
        self.volumeslider.valueChanged.connect(self.setVolume)

        self.vboxlayout = QVBoxLayout()
        self.vboxlayout.addWidget(self.videoframe)
        self.vboxlayout.addWidget(self.positionslider)
        self.vboxlayout.addLayout(self.hbuttonbox)

        self.widget.setLayout(self.vboxlayout)

        open = QAction("&Open", self)
        open.triggered.connect(self.OpenFile)
        exit = QAction("&Exit", self)
        exit.triggered.connect(sys.exit)
        menubar = self.menuBar()
        filemenu = menubar.addMenu("&File")
        filemenu.addAction(open)
        filemenu.addSeparator()
        filemenu.addAction(exit)

        self.timer = QTimer(self)
        self.timer.setInterval(200)
        self.timer.timeout.connect(self.updateUI)

    def PlayPause(self):
        """Toggle play/pause status
        """
        if self.mediaplayer.is_playing():
            self.mediaplayer.pause()
            self.playbutton.setText("Play")
            self.isPaused = True
        else:
            if self.mediaplayer.play() == -1:
                self.OpenFile()
                return
            self.mediaplayer.play()
            self.playbutton.setText("Pause")
            self.timer.start()
            self.isPaused = False

    def Stop(self):
        """Stop player
        """
        self.mediaplayer.stop()
        self.playbutton.setText("Play")

    def OpenFile(self, filename=None):
        """Open a media file in a MediaPlayer
        """
        #OPEN VIDEO FROM COMP
        """if filename is None:
            filename = QFileDialog.getOpenFileName(self, "Open File", os.path.expanduser('~'))[0]
        if not filename:
            return """
        #Open SPECIFIED VIDEO
        filename = "H:\\Projects\\object detection using SSD\\sample\\horses_in_desert.mp4"

        # create the media

        self.media = self.instance.media_new(filename)
        # put the media in the media player
        self.mediaplayer.set_media(self.media)

        # parse the metadata of the file
        self.media.parse()
        # set the title of the track as window title
        self.setWindowTitle(self.media.get_meta(0))

        # the media player has to be 'connected' to the QFrame
        # (otherwise a video would be displayed in it's own window)
        # this is platform specific!
        # you have to give the id of the QFrame (or similar object) to
        # vlc, different platforms have different functions for this
        if sys.platform.startswith('linux'):  # for Linux using the X Server
            self.mediaplayer.set_xwindow(self.videoframe.winId())
        elif sys.platform == "win32":  # for Windows
            self.mediaplayer.set_hwnd(self.videoframe.winId())
        elif sys.platform == "darwin":  # for MacOS
            self.mediaplayer.set_nsobject(int(self.videoframe.winId()))
        self.PlayPause()

    def setVolume(self, Volume):
        """Set the volume
        """
        self.mediaplayer.audio_set_volume(Volume)

    def setPosition(self, position):
        """Set the position
        """
        # setting the position to where the slider was dragged
        self.mediaplayer.set_position(position / 1000.0)
        # the vlc MediaPlayer needs a float value between 0 and 1, Qt
        # uses integer variables, so you need a factor; the higher the
        # factor, the more precise are the results
        # (1000 should be enough)

    def updateUI(self):
        """updates the user interface"""
        # setting the slider to the desired position
        self.positionslider.setValue(self.mediaplayer.get_position() * 1000)

        if not self.mediaplayer.is_playing():
            # no need to call this function if nothing is played
            self.timer.stop()
            if not self.isPaused:
                # after the video finished, the play button stills shows
                # "Pause", not the desired behavior of a media player
                # this will fix it
                self.Stop()
class mainWindow(QWidget):
    def __init__(self, parent=None):
        super(mainWindow, self).__init__(parent)
        self.setWindowTitle("GUI admin tool")
        self.setWindowIcon(QIcon('/home/abdelmoumen/test.png'))
        self.UI()

        titleBarHeight = self.style().pixelMetric(QStyle.PM_TitleBarHeight,
                                                  QStyleOptionTitleBar(), self)
        geometry = app.desktop().availableGeometry()
        geometry.setHeight(geometry.height() - (titleBarHeight * 2))

        self.setGeometry(geometry)

    #@QtCore.pyqtSlot()
    #def on_pushButtonClose_clicked(self):
    #    QApplication.instance().quit()

    def UI(self):
        self.layouts()
        self.widgets()

    def layouts(self):
        menuLayout = QVBoxLayout()
        menuLayout.setContentsMargins(0, 0, 0, 0)
        about = QPushButton("|  About")
        about.clicked.connect(lambda: aboutClicked(self))
        about.setFixedHeight(30)
        about.setFixedWidth(80)
        about.setStyleSheet("color: #303a46 ; border: 0px solid #303a46")
        menuLayout.addWidget(about)

        self.mainLayout = QVBoxLayout()
        self.topLayout = QHBoxLayout()
        self.bottomLayout = QHBoxLayout()

        self.bottomLeftLayout = QHBoxLayout()
        self.bottomRightLayout = QVBoxLayout()
        #self.bottomRightLayout.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
        '''
        logo = QLabel(self)
        pixmap = QPixmap('icons/admin.png')
        pixmap = pixmap.scaled(50, 50)
        logo.setPixmap(pixmap)
        '''
        #self.topLayout.addWidget(logo)

        refresh = QPushButton("🔁")
        refresh.clicked.connect(self.getContentTrigger)
        refresh.setStyleSheet(
            "color: #95a5a6; background-color: #303a46 ; border: 0px solid #303a46"
        )
        refresh.setFixedHeight(30)
        refresh.setFixedWidth(30)
        b = QHBoxLayout()
        b.addWidget(refresh)
        b.setContentsMargins(0, 0, 13, 0)

        logotext = QLabel("GUI Admin Tool")
        logotext.setStyleSheet("color: #303a46;font: bold 25px;")
        logotext.setContentsMargins(15, 0, 0, 0)
        self.topLayout.addWidget(logotext)
        #self.topLayout.addStretch()
        self.topLayout.addLayout(menuLayout)
        self.topLayout.addStretch()
        self.topLayout.addLayout(b)

        self.bottomLayout.addLayout(self.bottomLeftLayout)
        self.bottomLayout.addLayout(self.bottomRightLayout)
        self.bottomLayout.addStretch()

        self.mainLayout.addLayout(self.topLayout)
        self.mainLayout.addLayout(self.bottomLayout)

        self.setLayout(self.mainLayout)

    def widgets(self):
        self.dockWidget = QDockWidget(self)
        self.listWidget = QListWidget(self)
        self.listWidget.setSelectionMode(QAbstractItemView.SingleSelection)
        self.listWidget.setStyleSheet(
            "color: #303a46; selection-background-color: #303a46 ; selection-color: #95a5a6 ;border: 0px solid #95a5a6"
        )

        self.dockWidget.setFixedWidth(180)

        self.item0 = QtWidgets.QListWidgetItem("   ️💻  Dashboard")
        self.item0.setSizeHint(QtCore.QSize(50, 50))
        self.listWidget.addItem(self.item0)

        self.item1 = QtWidgets.QListWidgetItem("   ️🌐  System Information")
        self.item1.setSizeHint(QtCore.QSize(50, 50))
        self.listWidget.addItem(self.item1)

        self.item2 = QtWidgets.QListWidgetItem("  🚹 ‍ Users Statistics")
        self.item2.setSizeHint(QtCore.QSize(50, 50))

        self.listWidget.addItem(self.item2)
        self.item3 = QtWidgets.QListWidgetItem("  📚  Backup")
        self.item3.setSizeHint(QtCore.QSize(50, 50))
        self.listWidget.addItem(self.item3)

        self.item4 = QtWidgets.QListWidgetItem("  📶  Networking")
        self.item4.setSizeHint(QtCore.QSize(50, 50))
        self.listWidget.addItem(self.item4)

        self.item5 = QtWidgets.QListWidgetItem("  🏢  Firewall")
        self.item5.setSizeHint(QtCore.QSize(50, 50))
        self.listWidget.addItem(self.item5)

        self.item6 = QtWidgets.QListWidgetItem("  ⚙  Services")
        self.item6.setSizeHint(QtCore.QSize(50, 50))
        self.listWidget.addItem(self.item6)

        self.item7 = QtWidgets.QListWidgetItem("  ⌨  Terminal")
        self.item7.setSizeHint(QtCore.QSize(50, 50))
        self.listWidget.addItem(self.item7)

        self.listWidget.itemSelectionChanged.connect(self.getContentTrigger)

        self.dockWidget.setWidget(self.listWidget)
        self.dockWidget.setFloating(False)

        self.bottomLeftLayout.addWidget(self.dockWidget)
        self.listWidget.setCurrentItem(self.item0)

    def getContentTrigger(self):
        si = self.listWidget.selectedItems()[0]
        if si == self.item0:
            self.clearLayout(self.bottomRightLayout)
            mainDashboard.getContentDashboard(self)
        elif si == self.item1:
            self.clearLayout(self.bottomRightLayout)
            mainsystem.getContentSystem(self)
        elif si == self.item2:
            self.clearLayout(self.bottomRightLayout)
            mainusers.getContentUsers(self)
        elif si == self.item3:
            self.clearLayout(self.bottomRightLayout)
            mainbackup.getContentBackup(self)
        elif si == self.item4:
            self.clearLayout(self.bottomRightLayout)
            mainnetworking.getContentNetwork(self)
        elif si == self.item5:
            self.clearLayout(self.bottomRightLayout)
            mainFirewall.getContentFirewall(self)
        elif si == self.item6:
            self.clearLayout(self.bottomRightLayout)
            mainServices.getContentServices(self)
        elif si == self.item7:
            self.clearLayout(self.bottomRightLayout)
            mainterminal.main(self)
        else:
            QMessageBox.warning(
                self, "warning",
                "no section selected, please selecet a section")

    def clearLayout(self, layout):
        try:
            del self.memoryC
        except Exception:
            pass
        try:
            del self.cpuC
        except Exception:
            pass
        try:
            del self.cpusC
        except Exception:
            pass
        try:
            del self.usg
        except Exception:
            pass
        try:
            del self.read
        except Exception:
            pass
        try:
            del self.write
        except Exception:
            pass
        try:
            del self.all
        except Exception:
            pass
        try:
            del self.all2
        except Exception:
            pass
        try:
            del self.lastbadlogins
        except Exception:
            pass
        try:
            del self.lastlogins
        except Exception:
            pass
        try:
            del self.netSent
        except Exception:
            pass
        try:
            del self.netRec
        except Exception:
            pass
        try:
            del self.sw
        except Exception:
            pass

        try:
            del self.tableIncBackup
        except Exception:
            pass
        try:
            del self.tableFullBackup
        except Exception:
            pass
        try:
            del self.tableFw
        except Exception:
            pass
        try:
            del self.dic
        except Exception:
            pass
        try:
            del self.tableNet
        except Exception:
            pass
        try:
            del self.dic
        except Exception:
            pass
        try:
            del self.dic2
        except Exception:
            pass
        try:
            del self.dic3
        except Exception:
            pass
        try:
            del self.dic4
        except Exception:
            pass
        try:
            del self.dic5
        except Exception:
            pass
        try:
            del self.dic6
        except Exception:
            pass
        try:
            del self.tableServices
        except Exception:
            pass
        try:
            del self.form
        except Exception:
            pass
        try:
            del self.tableUsers
        except Exception:
            pass
        try:
            del self.listLoggedOn
        except Exception:
            pass

        while layout.count():
            child = layout.takeAt(0)
            if child.widget() is not None:
                child.widget().deleteLater()
            elif child.layout() is not None:
                self.clearLayout(child.layout())
示例#40
0
class SnapshotKeywordSelectorWidget(QComboBox):
    """
    Widget for defining keywords (labels). Existing keywords are read from
    the common_settings data structure and are suggested to the user in
    drop down menu. Keywords that are selected are returned as list.
    """
    keywords_changed = QtCore.pyqtSignal()

    def __init__(self, common_settings, defaults_only=False, parent=None):
        QComboBox.__init__(self, parent)

        self.defaults_only = defaults_only
        self.common_settings = common_settings

        # data holders
        self.selectedKeywords = list()
        self.keywordWidgets = dict()

        # Main layout
        # [selected widgets][input][drop down arrow (part of QComboBox)]
        self.layout = QHBoxLayout()
        self.setLayout(self.layout)
        self.layout.setContentsMargins(5, 0, 35, 0)
        self.layout.setSpacing(2)

        if not defaults_only:
            self.setEditable(True)
            # Extra styling
            self.lineEdit().setStyleSheet("background-color: white")

            self.input = SnapshotKeywordSelectorInput(self.input_handler, self)
            self.layout.addWidget(self.input)
        else:
            self.layout.addStretch()

        self.setCurrentIndex(0)
        self.currentIndexChanged[str].connect(self.add_to_selected)

        self.update_suggested_keywords()

    def get_keywords(self):
        # Return list of currently selected keywords
        return self.selectedKeywords

    def input_handler(self, event):
        # Is called in self.input widget, every time when important events
        # happen (key events, focus events). self.input just passes the
        # events to this method, where are handled.
        if event.type() == QtCore.QEvent.FocusOut:
            self.focus_out(event)
        else:
            self.key_press_event(event)

    def focus_out(self, event):
        # When focused out of the input (clicking away, tab pressed, ...)
        # current string in the input is added to the selected keywords
        self.add_to_selected(self.input.text())

    def key_press_event(self, event):
        # Handles keyboard events in following way:
        #     if: space, enter or tab, then add current string to the selected
        #     if backspace, then delete last character, or last keyword
        if event.key() in [
                Qt.Key_Tab, Qt.Key_Enter, Qt.Key_Return, Qt.Key_Space
        ]:
            if self.input.text().endswith(" "):
                key_to_add = self.input.text().split(" ")[-2]
            else:
                key_to_add = self.input.text()
            self.add_to_selected(key_to_add)

        elif event.key() == Qt.Key_Backspace and len(self.selectedKeywords):
            self.remove_keyword(self.selectedKeywords[-1])

    def focusInEvent(self, event):
        # Focus should always be on the self.input
        if not self.defaults_only:
            self.input.setFocus()

    def add_to_selected(self, keyword, force=False):
        # When called, keyword is added to list of selected keywords and
        # new graphical representation is added left to the input field
        self.setCurrentIndex(0)
        if not self.defaults_only:
            self.input.setText("")

        default_labels = self.common_settings["default_labels"]
        keyword = keyword.strip()

        # Skip if already selected or not in predefined labels if defaults_only (force=True overrides defaults_only)
        if keyword and (keyword not in self.selectedKeywords) and (
                not self.defaults_only or force
                or self.defaults_only and keyword in default_labels):
            key_widget = SnapshotKeywordWidget(keyword, self)
            key_widget.delete.connect(self.remove_keyword)
            self.keywordWidgets[keyword] = key_widget
            self.selectedKeywords.append(keyword)
            self.layout.insertWidget(
                len(self.selectedKeywords) - 1, key_widget)
            self.keywords_changed.emit()
            self.setItemText(0, "")

    def remove_keyword(self, keyword):
        # Remove keyword from list of selected and delete graphical element
        keyword = keyword.strip()
        if keyword in self.selectedKeywords:
            self.selectedKeywords.remove(keyword)
            key_widget = self.keywordWidgets.get(keyword)
            self.layout.removeWidget(key_widget)
            key_widget.deleteLater()
            self.keywords_changed.emit()
            if not self.selectedKeywords:
                self.setItemText(0, "Select labels ...")

    def setPlaceholderText(self, text):
        # Placeholder tefirst_itemxt is always in the input field
        if not self.defaults_only:
            self.input.setPlaceholderText(text)

    def update_suggested_keywords(self):
        # Method to be called when global list of existing labels (keywords)
        # is changed and widget must be updated.
        self.clear()
        labels = self.common_settings['default_labels'][:]
        if not self.defaults_only:
            labels += [
                l for l in self.common_settings['existing_labels']
                if l not in labels
            ]
            self.addItem("")
        else:
            self.addItem("Select labels ...")

        labels.sort()
        self.addItems(labels)

    def clear_keywords(self):
        keywords_to_remove = copy.copy(self.get_keywords())
        for keyword in keywords_to_remove:
            self.remove_keyword(keyword)
示例#41
0
    def __init__(self, *args):
        super().__init__(BrickletThermocouple, *args)

        self.thermo = self.device

        self.qtcb_error_state.connect(self.cb_error_state)
        self.thermo.register_callback(self.thermo.CALLBACK_ERROR_STATE,
                                      self.qtcb_error_state.emit)

        self.cbe_temperature = CallbackEmulator(self,
                                                self.thermo.get_temperature,
                                                None, self.cb_temperature,
                                                self.increase_error_count)

        self.current_temperature = CurveValueWrapper()  # float, °C

        self.error_label = QLabel('Current Errors: None')
        self.error_label.setAlignment(Qt.AlignVCenter | Qt.AlignRight)

        plots = [('Temperature', Qt.red, self.current_temperature,
                  '{:.2f} °C'.format)]
        self.plot_widget = PlotWidget('Temperature [°C]',
                                      plots,
                                      extra_key_widgets=[self.error_label],
                                      y_resolution=0.01)

        self.averaging_label = QLabel('Averaging:')
        self.averaging_combo = QComboBox()
        self.averaging_combo.addItem('1', BrickletThermocouple.AVERAGING_1)
        self.averaging_combo.addItem('2', BrickletThermocouple.AVERAGING_2)
        self.averaging_combo.addItem('4', BrickletThermocouple.AVERAGING_4)
        self.averaging_combo.addItem('8', BrickletThermocouple.AVERAGING_8)
        self.averaging_combo.addItem('16', BrickletThermocouple.AVERAGING_16)

        self.type_label = QLabel('Thermocouple Type:')
        self.type_combo = QComboBox()
        self.type_combo.addItem('B', BrickletThermocouple.TYPE_B)
        self.type_combo.addItem('E', BrickletThermocouple.TYPE_E)
        self.type_combo.addItem('J', BrickletThermocouple.TYPE_J)
        self.type_combo.addItem('K', BrickletThermocouple.TYPE_K)
        self.type_combo.addItem('N', BrickletThermocouple.TYPE_N)
        self.type_combo.addItem('R', BrickletThermocouple.TYPE_R)
        self.type_combo.addItem('S', BrickletThermocouple.TYPE_S)
        self.type_combo.addItem('T', BrickletThermocouple.TYPE_T)
        self.type_combo.addItem('Gain 8', BrickletThermocouple.TYPE_G8)
        self.type_combo.addItem('Gain 32', BrickletThermocouple.TYPE_G32)

        self.filter_label = QLabel('Noise Rejection Filter:')
        self.filter_combo = QComboBox()
        self.filter_combo.addItem('50 Hz',
                                  BrickletThermocouple.FILTER_OPTION_50HZ)
        self.filter_combo.addItem('60 Hz',
                                  BrickletThermocouple.FILTER_OPTION_60HZ)

        hlayout = QHBoxLayout()
        hlayout.addWidget(self.averaging_label)
        hlayout.addWidget(self.averaging_combo)
        hlayout.addStretch()
        hlayout.addWidget(self.type_label)
        hlayout.addWidget(self.type_combo)
        hlayout.addStretch()
        hlayout.addWidget(self.filter_label)
        hlayout.addWidget(self.filter_combo)

        line = QFrame()
        line.setObjectName("line")
        line.setFrameShape(QFrame.HLine)
        line.setFrameShadow(QFrame.Sunken)

        layout = QVBoxLayout(self)
        layout.addWidget(self.plot_widget)
        layout.addWidget(line)
        layout.addLayout(hlayout)

        self.averaging_combo.currentIndexChanged.connect(
            self.configuration_changed)
        self.type_combo.currentIndexChanged.connect(self.configuration_changed)
        self.filter_combo.currentIndexChanged.connect(
            self.configuration_changed)
示例#42
0
    def Layout(self):
        i = 0
        layout = QGridLayout()
        label1 = QLabel("Layer:")
        label3 = QLabel("Depth End (km,last one must be 800):")
        label4 = QLabel("Model Type:")
        layout.addWidget(label1, i, 0, 1, 1)
        layout.addWidget(label3, i, 1, 1, 1)
        layout.addWidget(label4, i, 2, 1, 2)

        i += 1
        label1 = QLabel("Layer1:")
        self.Depth1 = QLineEdit("")
        self.BTN_Mantle_cambo1 = QComboBox()
        self.BTN_Mantle_cambo1.addItem("Select a Model")
        self.BTN_Mantle_cambo1.addItem("Basalt(Xu et al. 2008)")
        self.BTN_Mantle_cambo1.addItem("Harzburgite (Xu et al. 2008)")
        self.BTN_Mantle_cambo1.addItem("Pyrolite (Xu et al. 2008)")
        self.BTN_Mantle_cambo1.addItem('Piclogite (Weidner, 1986) ')
        self.BTN_Mantle_cambo1.addItem(
            "90%molHarzburgite + 10%molBasalt (Xu et al. 2008) ")
        self.BTN_Mantle_cambo1.addItem(
            "80%molHarzburgite + 20%molBasalt (Xu et al. 2008) ")
        self.BTN_Mantle_cambo1.addItem(
            "70%molHarzburgite + 30%molBasalt (Xu et al. 2008) ")
        self.BTN_Mantle_cambo1.addItem(
            "60%molHarzburgite + 40%molBasalt (Xu et al. 2008) ")
        self.BTN_Mantle_cambo1.addItem(
            "50%molHarzburgite + 50%molBasalt (Xu et al. 2008) ")
        self.BTN_Mantle_cambo1.addItem(
            "40%molHarzburgite + 60%molBasalt (Xu et al. 2008) ")
        self.BTN_Mantle_cambo1.addItem(
            "30%molHarzburgite + 70%molBasalt (Xu et al. 2008) ")
        self.BTN_Mantle_cambo1.addItem(
            "20%molHarzburgite + 80%molBasalt (Xu et al. 2008) ")
        self.BTN_Mantle_cambo1.addItem(
            "10%molHarzburgite + 90%molBasalt (Xu et al. 2008) ")
        self.BTN_Mantle_cambo1.addItem('Pyrolite1 (McDonough and Sun, 1995) ')
        self.BTN_Mantle_cambo1.addItem('Pyrolite2 (Jagoutz et al., 1979) ')
        self.BTN_Mantle_cambo1.addItem('Pyrolite3 (Green et al., 1979) ')
        self.BTN_Mantle_cambo1.addItem(
            'Pyrolite4 (Taylor and McLennan, 1985) ')
        self.BTN_Mantle_cambo1.addItem('Pyrolite5 (Ringwood, 1962*) ')
        layout.addWidget(label1, i, 0, 1, 1)
        layout.addWidget(self.Depth1, i, 1, 1, 1)
        layout.addWidget(self.BTN_Mantle_cambo1, i, 2, 1, 2)

        i += 1
        label1 = QLabel("Layer2:")
        self.Depth2 = QLineEdit("")
        self.BTN_Mantle_cambo2 = QComboBox()
        self.BTN_Mantle_cambo2.addItem("Select a Model")
        self.BTN_Mantle_cambo2.addItem("Basalt(Xu et al. 2008)")
        self.BTN_Mantle_cambo2.addItem("Harzburgite (Xu et al. 2008)")
        self.BTN_Mantle_cambo2.addItem("Pyrolite (Xu et al. 2008)")
        self.BTN_Mantle_cambo2.addItem('Piclogite (Weidner, 1986) ')
        self.BTN_Mantle_cambo2.addItem(
            "90%molHarzburgite + 10%molBasalt (Xu et al. 2008) ")
        self.BTN_Mantle_cambo2.addItem(
            "80%molHarzburgite + 20%molBasalt (Xu et al. 2008) ")
        self.BTN_Mantle_cambo2.addItem(
            "70%molHarzburgite + 30%molBasalt (Xu et al. 2008) ")
        self.BTN_Mantle_cambo2.addItem(
            "60%molHarzburgite + 40%molBasalt (Xu et al. 2008) ")
        self.BTN_Mantle_cambo2.addItem(
            "50%molHarzburgite + 50%molBasalt (Xu et al. 2008) ")
        self.BTN_Mantle_cambo2.addItem(
            "40%molHarzburgite + 60%molBasalt (Xu et al. 2008) ")
        self.BTN_Mantle_cambo2.addItem(
            "30%molHarzburgite + 70%molBasalt (Xu et al. 2008) ")
        self.BTN_Mantle_cambo2.addItem(
            "20%molHarzburgite + 80%molBasalt (Xu et al. 2008) ")
        self.BTN_Mantle_cambo2.addItem(
            "10%molHarzburgite + 90%molBasalt (Xu et al. 2008) ")
        self.BTN_Mantle_cambo2.addItem('Pyrolite1 (McDonough and Sun, 1995) ')
        self.BTN_Mantle_cambo2.addItem('Pyrolite2 (Jagoutz et al., 1979) ')
        self.BTN_Mantle_cambo2.addItem('Pyrolite3 (Green et al., 1979) ')
        self.BTN_Mantle_cambo2.addItem(
            'Pyrolite4 (Taylor and McLennan, 1985) ')
        self.BTN_Mantle_cambo2.addItem('Pyrolite5 (Ringwood, 1962*) ')
        layout.addWidget(label1, i, 0, 1, 1)
        layout.addWidget(self.Depth2, i, 1, 1, 1)
        layout.addWidget(self.BTN_Mantle_cambo2, i, 2, 1, 2)

        i += 1
        label1 = QLabel("Layer3:")
        self.Depth3 = QLineEdit("")
        self.BTN_Mantle_cambo3 = QComboBox()
        self.BTN_Mantle_cambo3.addItem("Select a Model")
        self.BTN_Mantle_cambo3.addItem("Basalt(Xu et al. 2008)")
        self.BTN_Mantle_cambo3.addItem("Harzburgite (Xu et al. 2008)")
        self.BTN_Mantle_cambo3.addItem("Pyrolite (Xu et al. 2008)")
        self.BTN_Mantle_cambo3.addItem('Piclogite (Weidner, 1986) ')
        self.BTN_Mantle_cambo3.addItem(
            "90%molHarzburgite + 10%molBasalt (Xu et al. 2008) ")
        self.BTN_Mantle_cambo3.addItem(
            "80%molHarzburgite + 20%molBasalt (Xu et al. 2008) ")
        self.BTN_Mantle_cambo3.addItem(
            "70%molHarzburgite + 30%molBasalt (Xu et al. 2008) ")
        self.BTN_Mantle_cambo3.addItem(
            "60%molHarzburgite + 40%molBasalt (Xu et al. 2008) ")
        self.BTN_Mantle_cambo3.addItem(
            "50%molHarzburgite + 50%molBasalt (Xu et al. 2008) ")
        self.BTN_Mantle_cambo3.addItem(
            "40%molHarzburgite + 60%molBasalt (Xu et al. 2008) ")
        self.BTN_Mantle_cambo3.addItem(
            "30%molHarzburgite + 70%molBasalt (Xu et al. 2008) ")
        self.BTN_Mantle_cambo3.addItem(
            "20%molHarzburgite + 80%molBasalt (Xu et al. 2008) ")
        self.BTN_Mantle_cambo3.addItem(
            "10%molHarzburgite + 90%molBasalt (Xu et al. 2008) ")
        self.BTN_Mantle_cambo3.addItem('Pyrolite1 (McDonough and Sun, 1995) ')
        self.BTN_Mantle_cambo3.addItem('Pyrolite2 (Jagoutz et al., 1979) ')
        self.BTN_Mantle_cambo3.addItem('Pyrolite3 (Green et al., 1979) ')
        self.BTN_Mantle_cambo3.addItem(
            'Pyrolite4 (Taylor and McLennan, 1985) ')
        self.BTN_Mantle_cambo3.addItem('Pyrolite5 (Ringwood, 1962*) ')
        layout.addWidget(label1, i, 0, 1, 1)
        layout.addWidget(self.Depth3, i, 1, 1, 1)
        layout.addWidget(self.BTN_Mantle_cambo3, i, 2, 1, 2)

        i += 1
        label1 = QLabel("Layer4:")
        self.Depth4 = QLineEdit("")
        self.BTN_Mantle_cambo4 = QComboBox()
        self.BTN_Mantle_cambo4.addItem("Select a Model")
        self.BTN_Mantle_cambo4.addItem("Basalt(Xu et al. 2008)")
        self.BTN_Mantle_cambo4.addItem("Harzburgite (Xu et al. 2008)")
        self.BTN_Mantle_cambo4.addItem("Pyrolite (Xu et al. 2008)")
        self.BTN_Mantle_cambo4.addItem('Piclogite (Weidner, 1986) ')
        self.BTN_Mantle_cambo4.addItem(
            "90%molHarzburgite + 10%molBasalt (Xu et al. 2008) ")
        self.BTN_Mantle_cambo4.addItem(
            "80%molHarzburgite + 20%molBasalt (Xu et al. 2008) ")
        self.BTN_Mantle_cambo4.addItem(
            "70%molHarzburgite + 30%molBasalt (Xu et al. 2008) ")
        self.BTN_Mantle_cambo4.addItem(
            "60%molHarzburgite + 40%molBasalt (Xu et al. 2008) ")
        self.BTN_Mantle_cambo4.addItem(
            "50%molHarzburgite + 50%molBasalt (Xu et al. 2008) ")
        self.BTN_Mantle_cambo4.addItem(
            "40%molHarzburgite + 60%molBasalt (Xu et al. 2008) ")
        self.BTN_Mantle_cambo4.addItem(
            "30%molHarzburgite + 70%molBasalt (Xu et al. 2008) ")
        self.BTN_Mantle_cambo4.addItem(
            "20%molHarzburgite + 80%molBasalt (Xu et al. 2008) ")
        self.BTN_Mantle_cambo4.addItem(
            "10%molHarzburgite + 90%molBasalt (Xu et al. 2008) ")
        self.BTN_Mantle_cambo4.addItem('Pyrolite1 (McDonough and Sun, 1995) ')
        self.BTN_Mantle_cambo4.addItem('Pyrolite2 (Jagoutz et al., 1979) ')
        self.BTN_Mantle_cambo4.addItem('Pyrolite3 (Green et al., 1979) ')
        self.BTN_Mantle_cambo4.addItem(
            'Pyrolite4 (Taylor and McLennan, 1985) ')
        self.BTN_Mantle_cambo4.addItem('Pyrolite5 (Ringwood, 1962*) ')
        layout.addWidget(label1, i, 0, 1, 1)
        layout.addWidget(self.Depth4, i, 1, 1, 1)
        layout.addWidget(self.BTN_Mantle_cambo4, i, 2, 1, 2)

        i += 1
        label1 = QLabel("Layer5:")
        self.Depth5 = QLineEdit("")
        self.BTN_Mantle_cambo5 = QComboBox()
        self.BTN_Mantle_cambo5.addItem("Select a Model")
        self.BTN_Mantle_cambo5.addItem("Basalt(Xu et al. 2008)")
        self.BTN_Mantle_cambo5.addItem("Harzburgite (Xu et al. 2008)")
        self.BTN_Mantle_cambo5.addItem("Pyrolite (Xu et al. 2008)")
        self.BTN_Mantle_cambo5.addItem('Piclogite (Weidner, 1986) ')
        self.BTN_Mantle_cambo5.addItem(
            "90%molHarzburgite + 10%molBasalt (Xu et al. 2008) ")
        self.BTN_Mantle_cambo5.addItem(
            "80%molHarzburgite + 20%molBasalt (Xu et al. 2008) ")
        self.BTN_Mantle_cambo5.addItem(
            "70%molHarzburgite + 30%molBasalt (Xu et al. 2008) ")
        self.BTN_Mantle_cambo5.addItem(
            "60%molHarzburgite + 40%molBasalt (Xu et al. 2008) ")
        self.BTN_Mantle_cambo5.addItem(
            "50%molHarzburgite + 50%molBasalt (Xu et al. 2008) ")
        self.BTN_Mantle_cambo5.addItem(
            "40%molHarzburgite + 60%molBasalt (Xu et al. 2008) ")
        self.BTN_Mantle_cambo5.addItem(
            "30%molHarzburgite + 70%molBasalt (Xu et al. 2008) ")
        self.BTN_Mantle_cambo5.addItem(
            "20%molHarzburgite + 80%molBasalt (Xu et al. 2008) ")
        self.BTN_Mantle_cambo5.addItem(
            "10%molHarzburgite + 90%molBasalt (Xu et al. 2008) ")
        self.BTN_Mantle_cambo5.addItem('Pyrolite1 (McDonough and Sun, 1995) ')
        self.BTN_Mantle_cambo5.addItem('Pyrolite2 (Jagoutz et al., 1979) ')
        self.BTN_Mantle_cambo5.addItem('Pyrolite3 (Green et al., 1979) ')
        self.BTN_Mantle_cambo5.addItem(
            'Pyrolite4 (Taylor and McLennan, 1985) ')
        self.BTN_Mantle_cambo5.addItem('Pyrolite5 (Ringwood, 1962*) ')
        layout.addWidget(label1, i, 0, 1, 1)
        layout.addWidget(self.Depth5, i, 1, 1, 1)
        layout.addWidget(self.BTN_Mantle_cambo5, i, 2, 1, 2)

        i += 1
        label1 = QLabel("Layer6:")
        self.Depth6 = QLineEdit("")
        self.BTN_Mantle_cambo6 = QComboBox()
        self.BTN_Mantle_cambo6.addItem("Select a Model")
        self.BTN_Mantle_cambo6.addItem("Basalt(Xu et al. 2008)")
        self.BTN_Mantle_cambo6.addItem("Harzburgite (Xu et al. 2008)")
        self.BTN_Mantle_cambo6.addItem("Pyrolite (Xu et al. 2008)")
        self.BTN_Mantle_cambo6.addItem('Piclogite (Weidner, 1986) ')
        self.BTN_Mantle_cambo6.addItem(
            "90%molHarzburgite + 10%molBasalt (Xu et al. 2008) ")
        self.BTN_Mantle_cambo6.addItem(
            "80%molHarzburgite + 20%molBasalt (Xu et al. 2008) ")
        self.BTN_Mantle_cambo6.addItem(
            "70%molHarzburgite + 30%molBasalt (Xu et al. 2008) ")
        self.BTN_Mantle_cambo6.addItem(
            "60%molHarzburgite + 40%molBasalt (Xu et al. 2008) ")
        self.BTN_Mantle_cambo6.addItem(
            "50%molHarzburgite + 50%molBasalt (Xu et al. 2008) ")
        self.BTN_Mantle_cambo6.addItem(
            "40%molHarzburgite + 60%molBasalt (Xu et al. 2008) ")
        self.BTN_Mantle_cambo6.addItem(
            "30%molHarzburgite + 70%molBasalt (Xu et al. 2008) ")
        self.BTN_Mantle_cambo6.addItem(
            "20%molHarzburgite + 80%molBasalt (Xu et al. 2008) ")
        self.BTN_Mantle_cambo6.addItem(
            "10%molHarzburgite + 90%molBasalt (Xu et al. 2008) ")
        self.BTN_Mantle_cambo6.addItem('Pyrolite1 (McDonough and Sun, 1995) ')
        self.BTN_Mantle_cambo6.addItem('Pyrolite2 (Jagoutz et al., 1979) ')
        self.BTN_Mantle_cambo6.addItem('Pyrolite3 (Green et al., 1979) ')
        self.BTN_Mantle_cambo6.addItem(
            'Pyrolite4 (Taylor and McLennan, 1985) ')
        self.BTN_Mantle_cambo6.addItem('Pyrolite5 (Ringwood, 1962*) ')
        layout.addWidget(label1, i, 0, 1, 1)
        layout.addWidget(self.Depth6, i, 1, 1, 1)
        layout.addWidget(self.BTN_Mantle_cambo6, i, 2, 1, 2)

        self.setLayout(layout)
        self.setWindowTitle("Layers")
        self.resize(100, 50)

        self.okButton = QPushButton("&OK", self)
        self.okButton.clicked.connect(self.OK)
        self.okButton.setAutoDefault(False)
        self.cancelButton = QPushButton("Cancel", self)
        self.cancelButton.clicked.connect(self.Cancel)
        self.cancelButton.setAutoDefault(False)

        i += 1
        buttonLayout = QHBoxLayout()
        buttonLayout.addStretch()
        buttonLayout.addWidget(self.okButton)
        buttonLayout.addWidget(self.cancelButton)
        layout.addLayout(buttonLayout, i, 0, 1, 2)

        self.Lines = [
            self.Depth1, self.Depth2, self.Depth3, self.Depth4, self.Depth5,
            self.Depth6
        ]
        self.Combos = [
            self.BTN_Mantle_cambo1, self.BTN_Mantle_cambo2,
            self.BTN_Mantle_cambo3, self.BTN_Mantle_cambo4,
            self.BTN_Mantle_cambo5, self.BTN_Mantle_cambo6
        ]
示例#43
0
    def __init__(self,persepolis_setting):
        super().__init__()

        self.persepolis_setting = persepolis_setting

        icons = ':/' + str(self.persepolis_setting.value('settings/icons')) + '/'

        self.setWindowIcon(QIcon.fromTheme('persepolis' ,QIcon(':/icon.svg')))
        self.setWindowTitle("Persepolis Download Manager")
#complete_label
        self.verticalLayout_1 = QVBoxLayout()
        self.verticalLayout_1.setContentsMargins(21, 21, 21, 21)

        self.complete_label = QLabel()
        self.verticalLayout_1.addWidget(self.complete_label)
# file_name_label
        self.file_name_label = QLabel()
        self.verticalLayout_1.addWidget(self.file_name_label)
# size_label
        self.size_label = QLabel()
        self.verticalLayout_1.addWidget(self.size_label)

# link
        self.link_label = QLabel()
        self.verticalLayout_1.addWidget(self.link_label)

        self.link_lineEdit = QLineEdit()
        self.verticalLayout_1.addWidget(self.link_lineEdit)
# save_as
        self.save_as_label = QLabel()
        self.verticalLayout_1.addWidget(self.save_as_label)
        self.save_as_lineEdit = QLineEdit()
        self.verticalLayout_1.addWidget(self.save_as_lineEdit)
# open_pushButtun
        button_horizontalLayout = QHBoxLayout()
        button_horizontalLayout.setContentsMargins(10, 10, 10, 10)

        button_horizontalLayout.addStretch(1)
        self.open_pushButtun = QPushButton()
        self.open_pushButtun.setIcon(QIcon(icons + 'file'))
        button_horizontalLayout.addWidget(self.open_pushButtun)

# open_folder_pushButtun
        self.open_folder_pushButtun = QPushButton()
        self.open_folder_pushButtun.setIcon(QIcon(icons + 'folder'))
        button_horizontalLayout.addWidget(self.open_folder_pushButtun)

# ok_pushButton
        self.ok_pushButton = QPushButton()
        self.ok_pushButton.setIcon(QIcon(icons + 'ok'))
        button_horizontalLayout.addWidget(self.ok_pushButton)

        self.verticalLayout_1.addLayout(button_horizontalLayout)
# dont_show_checkBox
        self.dont_show_checkBox = QCheckBox()
        self.verticalLayout_1.addWidget(self.dont_show_checkBox)

        self.setLayout(self.verticalLayout_1)

# labels
        self.open_pushButtun.setText("  Open File  ")
        self.open_folder_pushButtun.setText("Open Download Folder")
        self.ok_pushButton.setText("   OK   ")
        self.dont_show_checkBox.setText("Don't show this message again.")
        self.complete_label.setText("<b>Download Completed!</b>")
        self.save_as_label.setText("<b>Save as</b> : ")
        self.link_label.setText("<b>Link</b> : " ) 
示例#44
0
文件: info.py 项目: prm268/Pythonic
class InfoWindow(QWidget):

    def __init__(self):

        logging.debug('__init__() called InfoWindow')
        super().__init__()

    def show(self):

        logging.debug('edit() called ExecReturn')
        self.infoLayout = QVBoxLayout()

        self.window = ElementEditor(self)
        self.window.setWindowTitle(QC.translate('', 'Info'))

        self.link_row = QWidget()
        self.link_row_layout = QHBoxLayout(self.link_row)
        self.link_row_layout.setAlignment(Qt.AlignLeft)

        self.license_txt_1 = QLabel()
        self.license_txt_1.setText(QC.translate('', 'Pythonic is published under the'))

        self.license_txt_2 = QLabel()
        self.license_txt_2.setText('<a href="https://raw.githubusercontent.com/hANSIc99/Pythonic/master/LICENSE">GNU General Public License v3.0')
        self.license_txt_2.setTextInteractionFlags(Qt.TextBrowserInteraction)
        self.license_txt_2.setOpenExternalLinks(True)

        self.license_txt_3 = QLabel()
        self.license_txt_3.setText(QC.translate('', 'Sources are available on'))

        self.license_txt_4 = QLabel()
        self.license_txt_4.setText('<a href="https://github.com/hANSIc99/Pythonic">GitHub')
        self.license_txt_4.setTextInteractionFlags(Qt.TextBrowserInteraction)
        self.license_txt_4.setOpenExternalLinks(True)

        self.license_line_1 = QWidget()
        self.license_line_layout_1 = QHBoxLayout(self.license_line_1)

        self.license_line_layout_1.addWidget(self.license_txt_1)
        self.license_line_layout_1.addWidget(self.license_txt_2)
        self.license_line_layout_1.addStretch(1)

        self.license_line_2 = QWidget()
        self.license_line_layout_2 = QHBoxLayout(self.license_line_2)

        self.license_line_layout_2.addWidget(self.license_txt_3)
        self.license_line_layout_2.addWidget(self.license_txt_4)
        self.license_line_layout_2.addStretch(1)

        self.link_line = QLabel()
        self.link_line.setText(QC.translate('', 'Pythonic by'))

        self.link = QLabel()
        self.link.setText('<a href="https://krypto-fuchs.de">https://krypto-fuchs.de</a>')
        self.link.setTextFormat(Qt.RichText)
        self.link.setTextInteractionFlags(Qt.TextBrowserInteraction)
        self.link.setOpenExternalLinks(True)

        self.link_row_layout.addWidget(self.link_line)
        self.link_row_layout.addWidget(self.link)

        self.logo = QWidget()
        self.logo_layout = QHBoxLayout(self.logo)
        self.logo_layout.setAlignment(Qt.AlignCenter)
        self.logo_label = QLabel()
        self.logo_label.setPixmap(QPixmap('images/vertical.png').scaledToHeight(200))
        self.logo_layout.addWidget(self.logo_label)

        self.confirm_button = QPushButton(QC.translate('', 'Ok'))

        self.confirm_button.clicked.connect(self.window.closeEvent)

        self.infoLayout.addWidget(self.license_line_1)
        self.infoLayout.addWidget(self.license_line_2)
        self.infoLayout.addWidget(self.logo)
        #self.infoLayout.addWidget(self.link_row)
        self.infoLayout.addStretch(1)
        self.infoLayout.addWidget(self.confirm_button)
        self.window.setLayout(self.infoLayout)
        self.window.show()
示例#45
0
    def showDialog(self, currentCard=None):
        if currentCard:
            self.did = currentCard.did
        elif mw._selectedDeck():
            self.did = mw._selectedDeck()['id']
        else:
            return

        if not self._getCardInfo(self.did):
            showInfo('Please select an Incremental Reading deck.')
            return

        dialog = QDialog(mw)
        layout = QVBoxLayout()
        self.cardListWidget = QListWidget()
        self.cardListWidget.setAlternatingRowColors(True)
        self.cardListWidget.setSelectionMode(
            QAbstractItemView.ExtendedSelection)
        self.cardListWidget.setWordWrap(True)
        self.cardListWidget.itemDoubleClicked.connect(lambda: showBrowser(
            self.cardListWidget.currentItem().data(Qt.UserRole)['nid']))

        self._updateListItems()

        upButton = QPushButton('Up')
        upButton.clicked.connect(self._moveUp)
        downButton = QPushButton('Down')
        downButton.clicked.connect(self._moveDown)
        topButton = QPushButton('Top')
        topButton.clicked.connect(self._moveToTop)
        bottomButton = QPushButton('Bottom')
        bottomButton.clicked.connect(self._moveToBottom)
        randomizeButton = QPushButton('Randomize')
        randomizeButton.clicked.connect(self._randomize)

        controlsLayout = QHBoxLayout()
        controlsLayout.addWidget(topButton)
        controlsLayout.addWidget(upButton)
        controlsLayout.addWidget(downButton)
        controlsLayout.addWidget(bottomButton)
        controlsLayout.addStretch()
        controlsLayout.addWidget(randomizeButton)

        buttonBox = QDialogButtonBox(QDialogButtonBox.Close
                                     | QDialogButtonBox.Save)
        buttonBox.accepted.connect(dialog.accept)
        buttonBox.rejected.connect(dialog.reject)
        buttonBox.setOrientation(Qt.Horizontal)

        layout.addLayout(controlsLayout)
        layout.addWidget(self.cardListWidget)
        layout.addWidget(buttonBox)

        dialog.setLayout(layout)
        dialog.setWindowModality(Qt.WindowModal)
        dialog.resize(500, 500)
        choice = dialog.exec_()

        if choice == 1:
            cids = []
            for i in range(self.cardListWidget.count()):
                card = self.cardListWidget.item(i).data(Qt.UserRole)
                cids.append(card['id'])

            self.reorder(cids)
示例#46
0
    def __init__(self,
                 data,
                 parent=None,
                 title="",
                 show_text=False,
                 description=None):
        WindowModalDialog.__init__(self, parent, title)

        vbox = QVBoxLayout()
        qrw = QRCodeWidget(data)

        if description:
            label = QLabel(description)
            label.setWordWrap(True)
            hbox2 = QHBoxLayout()
            hbox2.addWidget(label)
            vbox.addLayout(hbox2)

        vbox.addWidget(qrw, 1)
        if show_text:
            text = QTextEdit()
            text.setText(data)
            text.setReadOnly(True)
            vbox.addWidget(text)
        hbox = QHBoxLayout()
        hbox.addStretch(1)

        def print_qr():
            main_window = get_parent_main_window(self)
            if main_window:
                filename = main_window.getSaveFileName(
                    _("Select where to save file"), "qrcode.png")
            else:
                filename, __ = QFileDialog.getSaveFileName(
                    self, _("Select where to save file"), "qrcode.png")
            if not filename:
                return
            p = qrw.grab()  # FIXME also grabs neutral colored padding
            p.save(filename, 'png')
            self.show_message(_("QR code saved to file") + " " + filename)

        def copy_to_clipboard():
            p = qrw.grab()
            QApplication.clipboard().setPixmap(p)
            self.show_message(_("QR code copied to clipboard"))

        b = QPushButton(_("Copy"))
        hbox.addWidget(b)
        b.clicked.connect(copy_to_clipboard)

        b = QPushButton(_("Save"))
        hbox.addWidget(b)
        b.clicked.connect(print_qr)

        b = QPushButton(_("Close"))
        hbox.addWidget(b)
        b.clicked.connect(self.accept)
        b.setDefault(True)

        vbox.addLayout(hbox)

        self.setLayout(vbox)
示例#47
0
    def __init__(self, parent=None):
        super(ResultHandler, self).__init__()
        self.setWindowTitle('Dash results')
        self.control_label = QLabel()
        self.rendered_label = QLabel()
        self.diff_label = QLabel()

        self.mask_label = QLabel()
        self.new_mask_label = QLabel()

        self.scrollArea = QScrollArea()
        self.widget = QWidget()

        self.test_name_label = QLabel()
        grid = QGridLayout()
        grid.addWidget(self.test_name_label, 0, 0)
        grid.addWidget(QLabel('Control'), 1, 0)
        grid.addWidget(QLabel('Rendered'), 1, 1)
        grid.addWidget(QLabel('Difference'), 1, 2)
        grid.addWidget(self.control_label, 2, 0)
        grid.addWidget(self.rendered_label, 2, 1)
        grid.addWidget(self.diff_label, 2, 2)
        grid.addWidget(QLabel('Current Mask'), 3, 0)
        grid.addWidget(QLabel('New Mask'), 3, 1)
        grid.addWidget(self.mask_label, 4, 0)
        grid.addWidget(self.new_mask_label, 4, 1)

        self.widget.setLayout(grid)
        self.scrollArea.setWidget(self.widget)
        v_layout = QVBoxLayout()
        v_layout.addWidget(self.scrollArea, 1)

        next_image_button = QPushButton()
        next_image_button.setText('Skip')
        next_image_button.pressed.connect(self.load_next)

        self.overload_spin = QDoubleSpinBox()
        self.overload_spin.setMinimum(1)
        self.overload_spin.setMaximum(255)
        self.overload_spin.setValue(1)
        self.overload_spin.valueChanged.connect(
            lambda: save_mask_button.setEnabled(False))

        preview_mask_button = QPushButton()
        preview_mask_button.setText('Preview New Mask')
        preview_mask_button.pressed.connect(self.preview_mask)
        preview_mask_button.pressed.connect(
            lambda: save_mask_button.setEnabled(True))

        save_mask_button = QPushButton()
        save_mask_button.setText('Save New Mask')
        save_mask_button.pressed.connect(self.save_mask)

        button_layout = QHBoxLayout()
        button_layout.addWidget(next_image_button)
        button_layout.addWidget(QLabel('Mask diff multiplier:'))
        button_layout.addWidget(self.overload_spin)
        button_layout.addWidget(preview_mask_button)
        button_layout.addWidget(save_mask_button)
        button_layout.addStretch()
        v_layout.addLayout(button_layout)
        self.setLayout(v_layout)
示例#48
0
class TitleBar(QWidget):
    def __init__(self, parent):
        super(TitleBar, self).__init__()
        self.parent = parent
        self.db_wrapper = DatabaseWrapper()
        self.layout = QHBoxLayout()
        self.layout.setContentsMargins(0, 0, 0, 0)
        self.title = QLabel("Fitness Tracker")
        try:
            self.username = self.db_wrapper.fetch_local_column("Users", "name")
        except:
            self.username = None
        if self.username == None:
            self.version = QLabel()
        else:
            self.version = QLabel("-" + self.username)

        self.setFixedHeight(25)

        self.gridlayout = QHBoxLayout()
        self.gridlayout.setContentsMargins(0, 0, 0, 0)

        slight_indent = QSpacerItem(4, 0, QSizePolicy.Minimum,
                                    QSizePolicy.Expanding)
        version_space = QSpacerItem(20, 0, QSizePolicy.Minimum,
                                    QSizePolicy.Expanding)

        title_font_size = 14
        title_font = QFont('Ubuntu', title_font_size)
        self.title.setFont(title_font)

        self.version.setFont(title_font)
        self.version.setStyleSheet("color: #A5A5A5;")

        icon_max_size_x = 32
        icon_max_size_y = 24

        self.close_icon = QIcon(icons["close"])
        self.close_button = QPushButton()
        self.close_button.clicked.connect(self.close_click)
        self.close_button.setIcon(self.close_icon)
        self.close_button.setMaximumSize(icon_max_size_x, icon_max_size_y)
        self.close_button.setStyleSheet(
            "QPushButton{ background-color: rgba(237, 17, 17, 0); }"
            "QPushButton:hover{ background-color: rgba(237, 17, 17, 75); }"
            "QPushButton:pressed{ background-color: rgba(255, 0, 0, 100); }")

        self.minimise_icon = QIcon(icons["min"])
        self.minimise_button = QPushButton()
        self.minimise_button.clicked.connect(self.min_click)
        self.minimise_button.setIcon(self.minimise_icon)
        self.minimise_button.setMaximumSize(icon_max_size_x, icon_max_size_y)
        self.minimise_button.setStyleSheet(
            "QPushButton{ background-color: rgba(255, 255, 255, 0); }"
            "QPushButton:hover{ background-color: rgba(255, 255, 255, 70); }"
            "QPushButton:pressed{ background-color: rgba(255, 255, 255, 40); }"
        )

        self.maximize_icon = QIcon(icons["max"])
        self.unmax_icon = QIcon(icons["small"])
        self.maximize_button = QPushButton()
        self.maximize_button.setIcon(self.maximize_icon)
        self.maximize_button.clicked.connect(self.max_click)
        self.maximize_button.setMaximumSize(icon_max_size_x, icon_max_size_y)
        self.maximize_button.setStyleSheet(
            "QPushButton{ background-color: rgba(255, 255, 255, 0); }"
            "QPushButton:hover{ background-color: rgba(255, 255, 255, 70); }"
            "QPushButton:pressed{ background-color: rgba(255, 255, 255, 40); }"
        )

        self.settings_icon = QIcon(icons["settings"])
        self.settings_button = QPushButton()
        self.settings_button.setIcon(self.settings_icon)
        self.settings_button.setMaximumSize(icon_max_size_x, icon_max_size_y)
        self.settings_button.setStyleSheet(
            "QPushButton{ background-color: rgba(255, 255, 255, 0); }"
            "QPushButton:hover{ background-color: rgba(255, 255, 255, 70); }"
            "QPushButton:pressed{ background-color: rgba(255, 255, 255, 40); }"
        )
        self.settings_button.clicked.connect(self.showSettings)

        self.settings_button.setObjectName("SettingsButton")

        self.layout.addItem(slight_indent)
        self.layout.addWidget(self.title)
        self.layout.addItem(version_space)
        self.layout.addWidget(self.version)

        if not self.db_wrapper.connection_exists:
            self.layout.addItem(
                QSpacerItem(20, 0, QSizePolicy.Minimum, QSizePolicy.Expanding))
            connection_label = QLabel(
                "No internet connection. Changes will not be saved!")
            connection_label.setStyleSheet("color: red;")
            connection_label.setFont(title_font)
            self.layout.addWidget(connection_label)

        self.layout.addStretch(-1)

        self.gridlayout.addLayout(self.layout)
        self.gridlayout.addStretch(1)
        self.gridlayout.setSpacing(0)
        self.gridlayout.addWidget(self.settings_button)
        self.gridlayout.addWidget(self.minimise_button)
        self.gridlayout.addWidget(self.maximize_button)
        self.gridlayout.addWidget(self.close_button)
        self.setLayout(self.gridlayout)

        self.start = QPoint(0, 0)
        self.pressing = False
        self.maximized = False

    def mousePressEvent(self, event):
        self.start = self.mapToGlobal(event.pos())
        self.pressing = True

    def mouseMoveEvent(self, event):
        if self.pressing & self.maximized is False:
            self.end = self.mapToGlobal(event.pos())
            self.movement = self.end - self.start
            self.parent.setGeometry(
                self.mapToGlobal(self.movement).x(),
                self.mapToGlobal(self.movement).y(), self.parent.width(),
                self.parent.height())
            self.start = self.end

    def mouseReleaseEvent(self, QMouseEvent):
        self.pressing = False

    def close_click(self):
        self.parent.close()

    def max_click(self):
        if self.maximized:
            self.maximized = False
            self.parent.showNormal()
            self.maximize_button.setIcon(self.maximize_icon)
        else:
            self.maximized = True
            self.maximize_button.setIcon(self.unmax_icon)
            self.parent.showMaximized()

    def min_click(self):
        self.parent.showMinimized()

    def paintEvent(self, event):
        painter = QPainter()
        painter.begin(self)
        painter.setRenderHint(QPainter.Antialiasing)
        painter.fillRect(event.rect(), QBrush(QColor(68, 13, 15, 255)))

    def removeSettingsButton(self):
        self.layout.removeWidget("SettingsButton")

    def showSettings(self):
        global w
        w = SettingsWindow()
        w.show()
示例#49
0
class QWEditText(QWidget) :
    """ Text editor widget woth Load and Save buttons.
    """
    MORE_OPTIONS = ('More','Load','Save')

    def __init__(self, **kwargs) :
        parent      = kwargs.get('parent', None)
        win_title   = kwargs.get('win_title', 'Text Editor')
        self.ifname = kwargs.get('ifname', 'test.txt')
        self.ofname = kwargs.get('ofname', 'test.txt')
        self.textin = kwargs.get('text', 'N/A')

        QWidget.__init__(self, parent)
        if win_title is not None : self.setWindowTitle(win_title)

        self.vbox = QVBoxLayout()
        self.edi_text = QTextEdit(str(self.textin))
        self.vbox.addWidget(self.edi_text)

        self.box_more = QComboBox(self)
        self.box_more.addItems(self.MORE_OPTIONS)
        self.box_more.setCurrentIndex(0)

        self.hbox = QHBoxLayout()
        self.hbox.addWidget(self.box_more)
        self.hbox.addStretch(1)

        self.vbox.addLayout(self.hbox)
        self.setLayout(self.vbox)

        self.box_more.currentIndexChanged[int].connect(self.on_box_more)

        self.set_style()
        #self.set_icons()
        self.set_tool_tips()

#-----------------------------  

    def set_tool_tips(self):
        self.setToolTip('Text editor')
        self.box_more.setToolTip('More options:'\
                                +'\n * Load content from file'\
                                +'\n * Save content in file')

    def set_style(self):
        #self.setFixedWidth(200)
        self.setMinimumWidth(200)
        styleGray = "background-color: rgb(230, 240, 230); color: rgb(0, 0, 0);" # Gray
        styleDefault = ""

        #self.setWindowFlags(Qt.FramelessWindowHint)
        self.layout().setContentsMargins(0,0,0,0)

        self.setStyleSheet(styleDefault)
        self.set_style_msg(styleGray)

 
    def set_style_msg(self, style_bkgd):
        #self.edi_msg.setReadOnly(True)
        #self.edi_msg.setStyleSheet(style_bkgd)
        #self.edi_msg.setFrameStyle(QFrame.NoFrame)
        #self.edi_msg.setSizePolicy(QSizePolicy.MinimumExpanding, QSizePolicy.MinimumExpanding) # Ignored, Fixed, Expanding, Preferred
        #self.edi_msg.updateGeometry()
        #s = self.edi_msg.document().size()
        #print('XXX:document().size()', s.width(), s.height())
        #self.edi_msg.setMinimumSize(200,50)
        #self.edi_msg.setFixedSize(180,50)
        pass

    def set_icons(self):
        try :
          from psdaq.control_gui.QWIcons import icon
          #from psana.graphqt.QWIcons import icon
          icon.set_icons()
          #self.but_cancel.setIcon(icon.icon_button_cancel)
          #self.but_apply .setIcon(icon.icon_button_ok)
        except : pass
 
    #def resizeEvent(self, e):
        #logger.debug('resizeEvent') 

    #def moveEvent(self, e):
        #logger.debug('moveEvent') 

    #def event(self, event):
        #logger.debug('Event happens...: %s' % str(event))

    #def closeEvent(self, event):
    #    logger.debug('closeEvent')

#--------------------

    def get_content(self):
        return str(self.edi_text.toPlainText())

    def set_content(self, text='N/A'):
        self.edi_text.setPlainText(text)

#--------------------

    def select_ifname(self):
        logger.info('select_ifname %s' % self.ifname)
        path, ftype = QFileDialog.getOpenFileName(self,
                        caption   = 'Select the file to load json',
                        directory = self.ifname,
                        filter = 'Text files(*.txt *.text *.dat *.data *.npy)\nAll files (*)'
                        )
        if path == '' :
            logger.info('Loading is cancelled')
            return False
        self.ifname = path
        logger.info('Input file: %s' % path)
        return True

#--------------------
 
    def load_content_from_numpy_file(self, fname):
        logger.debug('TBD: load_content_from_numpy_file %s' % fname)
        import numpy as np
        nda = np.load(fname)              # array([0, 1, 2, 3, 4, 5])
        #lst = nda.tolist()               # [0, 1, 2, 3, 4, 5]
        #lst_str = [str(v)] for v in lst] # ['0', '1', '2', '3', '4', '5']
        #txt = ' '.join(lst)              # '0 1 2 3 4 5'
        txt = np.array2string(nda).lstrip('[').rstrip(']') # '0 1 2 3 4 5'
        return txt

#--------------------
 
    def save_content_in_numpy_file(self, fname):
        logger.warning('save_content_in_numpy_file %s' % fname)
        txt = self.get_content()
        import numpy as np

        #TODO: enter dtype and shape using popup gui, otherwise default

        arr = np.fromstring(txt, sep=' ') # dtype=int
        #arr.astype(int)                   
        #arr.shape = shape
        np.save(fname, arr)

#--------------------
 
    def on_but_load(self):
        logger.debug('on_but_load')
        if self.select_ifname() :
           root, ext = os.path.splitext(self.ifname)
           self.textin = self.load_content_from_numpy_file(self.ifname)\
                         if ext == '.npy' else load_textfile(self.ifname)

           self.set_content(self.textin)

#--------------------
 
    def save_text_in_file(self):
        #logger.info('save_text_in_file %s' % self.ofname)
        txt = self.get_content()
        save_textfile(txt, self.ofname, mode='w', verb=False)

#--------------------
 
    def select_ofname(self):
        logger.info('select_ofname %s' % self.ofname)
        path, ftype = QFileDialog.getSaveFileName(self,
                        caption   = 'Select the file to save',
                        directory = self.ofname,
                        filter    = 'Text files (*.txt *.text *.dat *.data *.npy)\nAll files (*)'
                        )
        if path == '' :
            logger.info('Saving is cancelled')
            return False
        self.ofname = path
        logger.info('Output file: %s' % path)
        return True

#--------------------
 
    def on_but_save(self):
        logger.debug('on_but_save')
        if self.select_ofname() : 
           root, ext = os.path.splitext(self.ofname)
           if ext == '.npy' : self.save_content_in_numpy_file(self.ofname)
           else             : self.save_text_in_file()

#--------------------
 
    def on_box_more(self, ind) :
        opt = self.MORE_OPTIONS[ind]
        logger.info('CGWConfigEditor selected option %s' % opt)
        if   ind==1 : self.on_but_load()
        elif ind==2 : self.on_but_save()
        self.box_more.setCurrentIndex(0)
示例#50
0
class UIOpenPatientWindow(object):
    patient_info_initialized = QtCore.pyqtSignal(object)

    def setup_ui(self, open_patient_window_instance):
        if platform.system() == 'Darwin':
            self.stylesheet_path = "src/res/stylesheet.qss"
        else:
            self.stylesheet_path = "src/res/stylesheet-win-linux.qss"
        stylesheet = open(resource_path(self.stylesheet_path)).read()
        window_icon = QIcon()
        window_icon.addPixmap(
            QPixmap(resource_path("src/res/images/icon.ico")), QIcon.Normal,
            QIcon.Off)
        open_patient_window_instance.setObjectName("OpenPatientWindowInstance")
        open_patient_window_instance.setWindowIcon(window_icon)
        open_patient_window_instance.resize(840, 530)

        # Create a vertical box for containing the other elements and layouts
        self.open_patient_window_instance_vertical_box = QVBoxLayout()
        self.open_patient_window_instance_vertical_box.setObjectName(
            "OpenPatientWindowInstanceVerticalBox")

        # Create a label to prompt the user to enter the path to the directory that contains the DICOM files
        self.open_patient_directory_prompt = QLabel()
        self.open_patient_directory_prompt.setObjectName(
            "OpenPatientDirectoryPrompt")
        self.open_patient_directory_prompt.setAlignment(Qt.AlignLeft)
        self.open_patient_window_instance_vertical_box.addWidget(
            self.open_patient_directory_prompt)

        # Create a horizontal box to hold the input box for the directory and the choose button
        self.open_patient_directory_input_horizontal_box = QHBoxLayout()
        self.open_patient_directory_input_horizontal_box.setObjectName(
            "OpenPatientDirectoryInputHorizontalBox")
        # Create a textbox to contain the path to the directory that contains the DICOM files
        self.open_patient_directory_input_box = UIOpenPatientWindowDragAndDropEvent(
            self)

        self.open_patient_directory_input_box.setObjectName(
            "OpenPatientDirectoryInputBox")
        self.open_patient_directory_input_box.setSizePolicy(
            QSizePolicy(QSizePolicy.MinimumExpanding,
                        QSizePolicy.MinimumExpanding))
        self.open_patient_directory_input_box.returnPressed.connect(
            self.scan_directory_for_patient)
        self.open_patient_directory_input_horizontal_box.addWidget(
            self.open_patient_directory_input_box)

        # Create a choose button to open the file dialog
        self.open_patient_directory_choose_button = QPushButton()
        self.open_patient_directory_choose_button.setObjectName(
            "OpenPatientDirectoryChooseButton")
        self.open_patient_directory_choose_button.setSizePolicy(
            QSizePolicy(QSizePolicy.MinimumExpanding,
                        QSizePolicy.MinimumExpanding))
        self.open_patient_directory_choose_button.resize(
            self.open_patient_directory_choose_button.sizeHint().width(),
            self.open_patient_directory_input_box.height())
        self.open_patient_directory_choose_button.setCursor(
            QtGui.QCursor(QtCore.Qt.PointingHandCursor))
        self.open_patient_directory_input_horizontal_box.addWidget(
            self.open_patient_directory_choose_button)
        self.open_patient_directory_choose_button.clicked.connect(
            self.choose_button_clicked)
        # Create a widget to hold the input fields
        self.open_patient_directory_input_widget = QWidget()
        self.open_patient_directory_input_horizontal_box.setStretch(0, 4)
        self.open_patient_directory_input_widget.setLayout(
            self.open_patient_directory_input_horizontal_box)
        self.open_patient_window_instance_vertical_box.addWidget(
            self.open_patient_directory_input_widget)

        # Create a horizontal box to hold the stop button and direction to the user on where to select the patient
        self.open_patient_appear_prompt_and_stop_horizontal_box = QHBoxLayout()
        self.open_patient_appear_prompt_and_stop_horizontal_box.setObjectName(
            "OpenPatientAppearPromptAndStopHorizontalBox")
        # Create a label to show direction on where the files will appear
        self.open_patient_directory_appear_prompt = QLabel()
        self.open_patient_directory_appear_prompt.setObjectName(
            "OpenPatientDirectoryAppearPrompt")
        self.open_patient_directory_appear_prompt.setAlignment(Qt.AlignLeft)
        self.open_patient_appear_prompt_and_stop_horizontal_box.addWidget(
            self.open_patient_directory_appear_prompt)
        self.open_patient_appear_prompt_and_stop_horizontal_box.addStretch(1)
        # Create a button to stop searching
        self.open_patient_window_stop_button = QPushButton()
        self.open_patient_window_stop_button.setObjectName(
            "OpenPatientWindowStopButton")
        self.open_patient_window_stop_button.setSizePolicy(
            QSizePolicy(QSizePolicy.MinimumExpanding,
                        QSizePolicy.MinimumExpanding))
        self.open_patient_window_stop_button.resize(
            self.open_patient_window_stop_button.sizeHint().width(),
            self.open_patient_window_stop_button.sizeHint().height())
        self.open_patient_window_stop_button.setCursor(
            QtGui.QCursor(QtCore.Qt.PointingHandCursor))
        self.open_patient_window_stop_button.clicked.connect(
            self.stop_button_clicked)
        self.open_patient_window_stop_button.setProperty(
            "QPushButtonClass", "fail-button")
        self.open_patient_window_stop_button.setVisible(
            False)  # Button doesn't show until a search commences
        self.open_patient_appear_prompt_and_stop_horizontal_box.addWidget(
            self.open_patient_window_stop_button)
        # Create a widget to hold the layout
        self.open_patient_appear_prompt_and_stop_widget = QWidget()
        self.open_patient_appear_prompt_and_stop_widget.setLayout(
            self.open_patient_appear_prompt_and_stop_horizontal_box)
        self.open_patient_window_instance_vertical_box.addWidget(
            self.open_patient_appear_prompt_and_stop_widget)

        # Create a tree view list to list out all patients in the directory selected above
        self.open_patient_window_patients_tree = QTreeWidget()
        self.open_patient_window_patients_tree.setObjectName(
            "OpenPatientWindowPatientsTree")
        self.open_patient_window_patients_tree.setSizePolicy(
            QSizePolicy(QSizePolicy.MinimumExpanding,
                        QSizePolicy.MinimumExpanding))
        self.open_patient_window_patients_tree.resize(
            self.open_patient_window_patients_tree.sizeHint().width(),
            self.open_patient_window_patients_tree.sizeHint().height())
        self.open_patient_window_patients_tree.setHeaderHidden(True)
        self.open_patient_window_patients_tree.setHeaderLabels([""])
        self.open_patient_window_instance_vertical_box.addWidget(
            self.open_patient_window_patients_tree)

        # Create a label to show what would happen if they select the patient
        self.open_patient_directory_result_label = QtWidgets.QLabel()
        self.open_patient_directory_result_label.setObjectName(
            "OpenPatientDirectoryResultLabel")
        self.open_patient_directory_result_label.setAlignment(Qt.AlignLeft)
        self.open_patient_window_instance_vertical_box.addWidget(
            self.open_patient_directory_result_label)

        # Create a horizontal box to hold the Cancel and Open button
        self.open_patient_window_patient_open_actions_horizontal_box = QHBoxLayout(
        )
        self.open_patient_window_patient_open_actions_horizontal_box.setObjectName(
            "OpenPatientWindowPatientOpenActionsHorizontalBox")
        self.open_patient_window_patient_open_actions_horizontal_box.addStretch(
            1)
        # Add a button to go back/exit from the application
        self.open_patient_window_exit_button = QPushButton()
        self.open_patient_window_exit_button.setObjectName(
            "OpenPatientWindowExitButton")
        self.open_patient_window_exit_button.setSizePolicy(
            QSizePolicy(QSizePolicy.MinimumExpanding,
                        QSizePolicy.MinimumExpanding))
        self.open_patient_window_exit_button.resize(
            self.open_patient_window_stop_button.sizeHint().width(),
            self.open_patient_window_stop_button.sizeHint().height())
        self.open_patient_window_exit_button.setCursor(
            QtGui.QCursor(QtCore.Qt.PointingHandCursor))
        self.open_patient_window_exit_button.clicked.connect(
            self.exit_button_clicked)
        self.open_patient_window_exit_button.setProperty(
            "QPushButtonClass", "fail-button")
        self.open_patient_window_patient_open_actions_horizontal_box.addWidget(
            self.open_patient_window_exit_button)

        # Add a button to confirm opening of the patient
        self.open_patient_window_confirm_button = QPushButton()
        self.open_patient_window_confirm_button.setObjectName(
            "OpenPatientWindowConfirmButton")
        self.open_patient_window_confirm_button.setSizePolicy(
            QSizePolicy(QSizePolicy.MinimumExpanding,
                        QSizePolicy.MinimumExpanding))
        self.open_patient_window_confirm_button.resize(
            self.open_patient_window_confirm_button.sizeHint().width(),
            self.open_patient_window_confirm_button.sizeHint().height())
        self.open_patient_window_confirm_button.setCursor(
            QtGui.QCursor(QtCore.Qt.PointingHandCursor))
        self.open_patient_window_confirm_button.clicked.connect(
            self.confirm_button_clicked)
        self.open_patient_window_confirm_button.setProperty(
            "QPushButtonClass", "success-button")
        self.open_patient_window_patient_open_actions_horizontal_box.addWidget(
            self.open_patient_window_confirm_button)

        # Create a widget to house all of the actions button for open patient window
        self.open_patient_window_patient_open_actions_widget = QWidget()
        self.open_patient_window_patient_open_actions_widget.setLayout(
            self.open_patient_window_patient_open_actions_horizontal_box)
        self.open_patient_window_instance_vertical_box.addWidget(
            self.open_patient_window_patient_open_actions_widget)

        # Set the vertical box fourth element, the tree view, to stretch out as far as possible
        self.open_patient_window_instance_vertical_box.setStretch(
            3, 4)  # Stretch the treeview out as far as possible
        self.open_patient_window_instance_central_widget = QWidget()
        self.open_patient_window_instance_central_widget.setObjectName(
            "OpenPatientWindowInstanceCentralWidget")
        self.open_patient_window_instance_central_widget.setLayout(
            self.open_patient_window_instance_vertical_box)

        # Create threadpool for multithreading
        self.threadpool = QThreadPool()
        print("Multithreading with maximum %d threads" %
              self.threadpool.maxThreadCount())
        # Create interrupt event for stopping the directory search
        self.interrupt_flag = threading.Event()

        # Bind all texts into the buttons and labels
        self.retranslate_ui(open_patient_window_instance)
        # Set the central widget, ready for display
        open_patient_window_instance.setCentralWidget(
            self.open_patient_window_instance_central_widget)

        # Set the current stylesheet to the instance and connect it back to the caller through slot
        open_patient_window_instance.setStyleSheet(stylesheet)
        QtCore.QMetaObject.connectSlotsByName(open_patient_window_instance)

    def retranslate_ui(self, open_patient_window_instance):
        _translate = QtCore.QCoreApplication.translate
        open_patient_window_instance.setWindowTitle(
            _translate("OpenPatientWindowInstance",
                       "OnkoDICOM - Select Patient"))
        self.open_patient_directory_prompt.setText(
            _translate(
                "OpenPatientWindowInstance",
                "Choose the path of the folder containing DICOM files to load Patient's details:"
            ))
        self.open_patient_directory_input_box.setPlaceholderText(
            _translate(
                "OpenPatientWindowInstance",
                "Enter DICOM Files Path (For example, C:\path\\to\your\DICOM\Files)"
            ))
        self.open_patient_directory_choose_button.setText(
            _translate("OpenPatientWindowInstance", "Choose"))
        self.open_patient_directory_appear_prompt.setText(
            _translate(
                "OpenPatientWindowInstance",
                "Patient File directory shown below once file path chosen. Please select the file(s) you want to open:"
            ))
        self.open_patient_directory_result_label.setText(
            "The selected directory(s) above will be opened in the OnkoDICOM program."
        )
        self.open_patient_window_stop_button.setText(
            _translate("OpenPatientWindowInstance", "Stop Search"))
        self.open_patient_window_exit_button.setText(
            _translate("OpenPatientWindowInstance", "Exit"))
        self.open_patient_window_confirm_button.setText(
            _translate("OpenPatientWindowInstance", "Confirm"))

    def exit_button_clicked(self):
        QCoreApplication.exit(0)

    def scan_directory_for_patient(self):
        self.filepath = self.open_patient_directory_input_box.text()
        # Proceed if a folder was selected
        if self.filepath != "":
            # Update the QTreeWidget to reflect data being loaded
            # First, clear the widget of any existing data
            self.open_patient_window_patients_tree.clear()

            # Next, update the tree widget
            self.open_patient_window_patients_tree.addTopLevelItem(
                QTreeWidgetItem(["Loading selected directory..."]))

            # The choose button is disabled until the thread finishes executing
            self.open_patient_directory_choose_button.setEnabled(False)

            # Reveals the Stop Search button for the duration of the search
            self.open_patient_window_stop_button.setVisible(True)

            # The interrupt flag is then un-set if a previous search has been stopped.
            self.interrupt_flag.clear()

            # Then, create a new thread that will load the selected folder
            worker = Worker(DICOMDirectorySearch.get_dicom_structure,
                            self.filepath,
                            self.interrupt_flag,
                            progress_callback=True)
            worker.signals.result.connect(self.on_search_complete)
            worker.signals.progress.connect(self.search_progress)

            # Execute the thread
            self.threadpool.start(worker)

    def choose_button_clicked(self):
        """
        Executes when the choose button is clicked.
        Gets filepath from the user and loads all files and subdirectories.
        """
        # Get folder path from pop up dialog box
        self.filepath = QtWidgets.QFileDialog.getExistingDirectory(
            None, 'Select patient folder...', '')
        self.open_patient_directory_input_box.setText(self.filepath)
        self.scan_directory_for_patient()

    def stop_button_clicked(self):
        self.interrupt_flag.set()

    def search_progress(self, progress_update):
        """
        Current progress of the file search.
        """
        self.open_patient_window_patients_tree.clear()
        self.open_patient_window_patients_tree.addTopLevelItem(
            QTreeWidgetItem([
                "Loading selected directory... (%s files searched)" %
                progress_update
            ]))

    def on_search_complete(self, dicom_structure):
        """
        Executes once the directory search is complete.
        :param dicom_structure: DICOMStructure object constructed by the directory search.
        """
        self.open_patient_directory_choose_button.setEnabled(True)
        self.open_patient_window_stop_button.setVisible(False)
        self.open_patient_window_patients_tree.clear()

        if dicom_structure is None:  # dicom_structure will be None if function was interrupted.
            return

        for patient_item in dicom_structure.get_tree_items_list():
            self.open_patient_window_patients_tree.addTopLevelItem(
                patient_item)

        if len(dicom_structure.patients) == 0:
            QMessageBox.about(self, "No files found",
                              "Selected directory contains no DICOM files.")

    def confirm_button_clicked(self):
        """
        Begins loading of the selected files.
        """
        selected_files = []
        for item in self.get_checked_leaves():
            selected_files += item.dicom_object.get_files()

        if len(selected_files) > 0:
            self.progress_window = ProgressWindow(
                self,
                QtCore.Qt.WindowTitleHint | QtCore.Qt.WindowCloseButtonHint)
            self.progress_window.signal_loaded.connect(self.on_loaded)
            self.progress_window.signal_error.connect(self.on_loading_error)

            self.progress_window.start_loading(selected_files)
            self.progress_window.exec_()
        else:
            QMessageBox.about(self, "Unable to open selection",
                              "No files selected.")

    def on_loaded(self, results):
        """
        Executes when the progress bar finishes loaded the selected files.
        """
        if results[0] is True:  # Will be NoneType if loading was interrupted.
            self.patient_info_initialized.emit(
                results[1])  # Emits the progress window.

    def on_loading_error(self, error_code):
        """
        Error handling for progress window.
        """
        if error_code == 0:
            QMessageBox.about(
                self.progress_window, "Unable to open selection",
                "Selected files cannot be opened as they are not a DICOM-RT set."
            )
            self.progress_window.close()
        elif error_code == 1:
            QMessageBox.about(
                self.progress_window, "Unable to open selection",
                "Selected files cannot be opened as they contain unsupported DICOM classes."
            )
            self.progress_window.close()

    def get_checked_leaves(self):
        """
        :return: A list of all QTreeWidgetItems in the QTreeWidget that are both leaves and checked.
        """
        checked_items = []

        def recurse(parent_item: QTreeWidgetItem):
            for i in range(parent_item.childCount()):
                child = parent_item.child(i)
                grand_children = child.childCount()
                if grand_children > 0:
                    recurse(child)
                else:
                    if child.checkState(0) == Qt.Checked:
                        checked_items.append(child)

        recurse(self.open_patient_window_patients_tree.invisibleRootItem())
        return checked_items
示例#51
0
    def select_storage(self, path, get_wallet_from_daemon) -> Tuple[str, Optional[WalletStorage]]:

        vbox = QVBoxLayout()
        hbox = QHBoxLayout()
        hbox.addWidget(QLabel(_('Wallet') + ':'))
        name_e = QLineEdit()
        hbox.addWidget(name_e)
        button = QPushButton(_('Choose...'))
        hbox.addWidget(button)
        vbox.addLayout(hbox)

        msg_label = WWLabel('')
        vbox.addWidget(msg_label)
        hbox2 = QHBoxLayout()
        pw_e = PasswordLineEdit('', self)
        pw_e.setFixedWidth(17 * char_width_in_lineedit())
        pw_label = QLabel(_('Password') + ':')
        hbox2.addWidget(pw_label)
        hbox2.addWidget(pw_e)
        hbox2.addStretch()
        vbox.addLayout(hbox2)

        vbox.addSpacing(50)
        vbox_create_new = QVBoxLayout()
        vbox_create_new.addWidget(QLabel(_('Alternatively') + ':'), alignment=Qt.AlignLeft)
        button_create_new = QPushButton(_('Create New Wallet'))
        button_create_new.setMinimumWidth(120)
        vbox_create_new.addWidget(button_create_new, alignment=Qt.AlignLeft)
        widget_create_new = QWidget()
        widget_create_new.setLayout(vbox_create_new)
        vbox_create_new.setContentsMargins(0, 0, 0, 0)
        vbox.addWidget(widget_create_new)

        self.set_layout(vbox, title=_('Electrum wallet'))

        temp_storage = None  # type: Optional[WalletStorage]
        wallet_folder = os.path.dirname(path)

        def on_choose():
            path, __ = QFileDialog.getOpenFileName(self, "Select your wallet file", wallet_folder)
            if path:
                name_e.setText(path)

        def on_filename(filename):
            # FIXME? "filename" might contain ".." (etc) and hence sketchy path traversals are possible
            nonlocal temp_storage
            temp_storage = None
            msg = None
            if filename:
                path = os.path.join(wallet_folder, filename)
                wallet_from_memory = get_wallet_from_daemon(path)
                try:
                    if wallet_from_memory:
                        temp_storage = wallet_from_memory.storage  # type: Optional[WalletStorage]
                    else:
                        temp_storage = WalletStorage(path)
                except (StorageReadWriteError, WalletFileException) as e:
                    msg = _('Cannot read file') + f'\n{repr(e)}'
                except Exception as e:
                    self.logger.exception('')
                    msg = _('Cannot read file') + f'\n{repr(e)}'
            else:
                msg = ""
            self.next_button.setEnabled(temp_storage is not None)
            user_needs_to_enter_password = False
            if temp_storage:
                if not temp_storage.file_exists():
                    msg =_("This file does not exist.") + '\n' \
                          + _("Press 'Next' to create this wallet, or choose another file.")
                elif not wallet_from_memory:
                    if temp_storage.is_encrypted_with_user_pw():
                        msg = _("This file is encrypted with a password.") + '\n' \
                              + _('Enter your password or choose another file.')
                        user_needs_to_enter_password = True
                    elif temp_storage.is_encrypted_with_hw_device():
                        msg = _("This file is encrypted using a hardware device.") + '\n' \
                              + _("Press 'Next' to choose device to decrypt.")
                    else:
                        msg = _("Press 'Next' to open this wallet.")
                else:
                    msg = _("This file is already open in memory.") + "\n" \
                        + _("Press 'Next' to create/focus window.")
            if msg is None:
                msg = _('Cannot read file')
            msg_label.setText(msg)
            widget_create_new.setVisible(bool(temp_storage and temp_storage.file_exists()))
            if user_needs_to_enter_password:
                pw_label.show()
                pw_e.show()
                pw_e.setFocus()
            else:
                pw_label.hide()
                pw_e.hide()

        button.clicked.connect(on_choose)
        button_create_new.clicked.connect(
            partial(
                name_e.setText,
                get_new_wallet_name(wallet_folder)))
        name_e.textChanged.connect(on_filename)
        name_e.setText(os.path.basename(path))

        def run_user_interaction_loop():
            while True:
                if self.loop.exec_() != 2:  # 2 = next
                    raise UserCancelled()
                assert temp_storage
                if temp_storage.file_exists() and not temp_storage.is_encrypted():
                    break
                if not temp_storage.file_exists():
                    break
                wallet_from_memory = get_wallet_from_daemon(temp_storage.path)
                if wallet_from_memory:
                    raise WalletAlreadyOpenInMemory(wallet_from_memory)
                if temp_storage.file_exists() and temp_storage.is_encrypted():
                    if temp_storage.is_encrypted_with_user_pw():
                        password = pw_e.text()
                        try:
                            temp_storage.decrypt(password)
                            break
                        except InvalidPassword as e:
                            self.show_message(title=_('Error'), msg=str(e))
                            continue
                        except BaseException as e:
                            self.logger.exception('')
                            self.show_message(title=_('Error'), msg=repr(e))
                            raise UserCancelled()
                    elif temp_storage.is_encrypted_with_hw_device():
                        try:
                            self.run('choose_hw_device', HWD_SETUP_DECRYPT_WALLET, storage=temp_storage)
                        except InvalidPassword as e:
                            self.show_message(title=_('Error'),
                                              msg=_('Failed to decrypt using this hardware device.') + '\n' +
                                                  _('If you use a passphrase, make sure it is correct.'))
                            self.reset_stack()
                            return self.select_storage(path, get_wallet_from_daemon)
                        except (UserCancelled, GoBack):
                            raise
                        except BaseException as e:
                            self.logger.exception('')
                            self.show_message(title=_('Error'), msg=repr(e))
                            raise UserCancelled()
                        if temp_storage.is_past_initial_decryption():
                            break
                        else:
                            raise UserCancelled()
                    else:
                        raise Exception('Unexpected encryption version')

        try:
            run_user_interaction_loop()
        finally:
            try:
                pw_e.clear()
            except RuntimeError:  # wrapped C/C++ object has been deleted.
                pass              # happens when decrypting with hw device

        return temp_storage.path, (temp_storage if temp_storage.file_exists() else None)
class PlayerControlPanel(QFrame):
    def __init__(self, app, parent=None):
        super().__init__(parent)
        self._app = app

        class IconButton(QPushButton):
            def __init__(self, *args, **kwargs):
                super().__init__(*args, **kwargs)

        self._playback_modes = list(PlaybackMode.__members__.values())
        self._pm_alias_map = {
            PlaybackMode.one_loop: '单曲循环',
            PlaybackMode.sequential: '顺序播放',
            PlaybackMode.loop: '循环播放',
            PlaybackMode.random: '随机播放',
        }

        # initialize sub widgets
        self._layout = QHBoxLayout(self)
        self.previous_btn = IconButton(self)
        self.pp_btn = IconButton(self)
        self.next_btn = IconButton(self)

        #: playback mode switch button
        self.pms_btn = QPushButton(self)
        self.volume_btn = VolumeButton(self)
        self.volume_btn.change_volume_needed.connect(
            lambda volume: setattr(self._app.player, 'volume', volume))
        self.playlist_btn = IconButton(parent=self)
        #: mark song as favorite button
        self.like_btn = QPushButton(self)
        self.mv_btn = QPushButton('MV', self)
        self.download_btn = QPushButton(self)
        self.toggle_video_btn = QPushButton('△', self)

        self.previous_btn.setObjectName('previous_btn')
        self.pp_btn.setObjectName('pp_btn')
        self.next_btn.setObjectName('next_btn')
        self.playlist_btn.setObjectName('playlist_btn')
        self.volume_btn.setObjectName('volume_btn')
        self.pms_btn.setObjectName('pms_btn')
        self.download_btn.setObjectName('download_btn')
        self.like_btn.setObjectName('like_btn')
        self.mv_btn.setObjectName('mv_btn')
        self.toggle_video_btn.setObjectName('toggle_video_btn')

        self.progress_slider = ProgressSlider(self)

        self.pms_btn.setToolTip('修改播放模式')
        self.volume_btn.setToolTip('调整音量')
        self.playlist_btn.setToolTip('显示当前播放列表')
        self.progress_slider.setToolTip('拖动调节进度')

        self.mv_btn.setToolTip('播放 MV')
        self.download_btn.setToolTip('下载歌曲(未实现,欢迎 PR)')
        self.like_btn.setToolTip('收藏歌曲(未实现,欢迎 PR)')
        self.pp_btn.setCheckable(True)
        self.like_btn.setCheckable(True)
        self.download_btn.setCheckable(True)
        self.toggle_video_btn.hide()

        self.song_title_label = QLabel('No song is playing.', parent=self)
        self.song_source_label = QLabel('歌曲来源', parent=self)
        self.song_title_label.setAlignment(Qt.AlignCenter)
        self.duration_label = QLabel('00:00', parent=self)
        self.position_label = QLabel('00:00', parent=self)

        self.song_source_label.setObjectName('song_source_label')

        self.next_btn.clicked.connect(self._app.player.play_next)
        self.previous_btn.clicked.connect(self._app.player.play_previous)
        self.pp_btn.clicked.connect(self._app.player.toggle)
        self.pms_btn.clicked.connect(self._switch_playback_mode)

        player = self._app.player

        player.state_changed.connect(self._on_player_state_changed,
                                     aioqueue=True)
        player.position_changed.connect(self.on_position_changed)
        player.duration_changed.connect(self.on_duration_changed,
                                        aioqueue=True)
        player.playlist.playback_mode_changed.connect(
            self.on_playback_mode_changed, aioqueue=True)
        player.playlist.song_changed.connect(self.on_player_song_changed,
                                             aioqueue=True)
        player.media_changed.connect(self.on_player_media_changed,
                                     aioqueue=True)
        self.progress_slider.resume_player_needed.connect(player.resume)
        self.progress_slider.pause_player_needed.connect(player.pause)
        self.progress_slider.change_position_needed.connect(
            lambda value: setattr(player, 'position', value))

        self._update_pms_btn_text()
        self._setup_ui()

    def _setup_ui(self):
        # set widget layout
        self.song_source_label.setFixedHeight(20)
        self.progress_slider.setFixedHeight(20)  # half of parent height
        self.position_label.setFixedWidth(45)
        self.duration_label.setFixedWidth(45)
        # on macOS, we should set AlignVCenter flag
        self.position_label.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
        self.like_btn.setFixedSize(15, 15)
        self.download_btn.setFixedSize(15, 15)
        self.mv_btn.setFixedHeight(16)

        self.progress_slider.setSizePolicy(QSizePolicy.Expanding,
                                           QSizePolicy.Preferred)
        self._sub_layout = QVBoxLayout()
        self._sub_top_layout = QHBoxLayout()

        # add space to make top layout align with progress slider
        self._sub_top_layout.addSpacing(3)
        self._sub_top_layout.addWidget(self.song_source_label)
        self._sub_top_layout.addSpacing(5)
        self._sub_top_layout.addWidget(self.song_title_label)
        self._sub_top_layout.addStretch(0)
        self._sub_top_layout.addWidget(self.like_btn)
        self._sub_top_layout.addSpacing(8)
        self._sub_top_layout.addWidget(self.mv_btn)
        self._sub_top_layout.addSpacing(8)
        self._sub_top_layout.addWidget(self.download_btn)
        self._sub_top_layout.addSpacing(3)

        self._sub_layout.addSpacing(3)
        self._sub_layout.addLayout(self._sub_top_layout)
        self._sub_layout.addWidget(self.progress_slider)

        self._layout.addSpacing(20)
        self._layout.addWidget(self.previous_btn)
        self._layout.addSpacing(8)
        self._layout.addWidget(self.pp_btn)
        self._layout.addSpacing(8)
        self._layout.addWidget(self.next_btn)
        self._layout.addSpacing(26)
        self._layout.addWidget(self.volume_btn)
        # 18 = 200(left_panel_width) - 4 * 30(btn) - 20 - 8 - 8 -26
        self._layout.addSpacing(18)
        self._layout.addStretch(0)
        self._layout.addWidget(self.position_label)
        self._layout.addSpacing(7)
        self._layout.addLayout(self._sub_layout)
        self._layout.setStretchFactor(self._sub_layout, 1)
        self._layout.addSpacing(7)
        self._layout.addWidget(self.duration_label)
        self._layout.addStretch(0)
        self._layout.addSpacing(18)
        self._layout.addWidget(self.pms_btn)
        self._layout.addSpacing(8)
        self._layout.addWidget(self.playlist_btn)
        self._layout.addSpacing(8)
        self._layout.addWidget(self.toggle_video_btn)
        self._layout.addSpacing(18)
        self._layout.setSpacing(0)
        self._layout.setContentsMargins(0, 0, 0, 0)

    def _switch_playback_mode(self):
        playlist = self._app.player.playlist
        pm_total = len(self._playback_modes)
        pm_idx = self._playback_modes.index(playlist.playback_mode)
        if pm_idx < pm_total - 1:
            pm_idx += 1
        else:
            pm_idx = 0
        playlist.playback_mode = self._playback_modes[pm_idx]

    def on_duration_changed(self, duration):
        duration = duration * 1000
        m, s = parse_ms(duration)
        t = QTime(0, m, s)
        self.progress_slider.set_duration(duration)
        self.duration_label.setText(t.toString('mm:ss'))

    def on_position_changed(self, position):
        if position is None:
            return
        position = position * 1000
        m, s = parse_ms(position)
        t = QTime(0, m, s)
        self.position_label.setText(t.toString('mm:ss'))
        self.progress_slider.update_state(position)

    def on_playback_mode_changed(self, playback_mode):
        self._update_pms_btn_text()

    def _update_pms_btn_text(self):
        playback_mode = self._app.player.playlist.playback_mode
        alias = self._pm_alias_map[playback_mode]
        self.pms_btn.setText(alias)

    def on_player_song_changed(self, song):
        if song is None:
            self.song_source_label.setText('歌曲来源')
            self.song_title_label.setText('No song is playing.')
            return
        source_name_map = {
            p.identifier: p.name
            for p in self._app.library.list()
        }
        font_metrics = QFontMetrics(QApplication.font())
        text = '{} - {}'.format(song.title_display, song.artists_name_display)
        elided_text = font_metrics.elidedText(
            text, Qt.ElideRight,
            self.progress_slider.width() - 100)
        self.song_source_label.setText(source_name_map[song.source])
        self.song_title_label.setText(elided_text)
        loop = asyncio.get_event_loop()
        loop.create_task(self.update_mv_btn_status(song))

    def on_player_media_changed(self, media):
        if media is not None and media.type_ == MediaType.audio:
            metadata = media.metadata
            if metadata.bitrate:
                text = self.song_source_label.text()
                bitrate_text = str(metadata.bitrate) + 'kbps'
                self.song_source_label.setText('{} - {}'.format(
                    text, bitrate_text))

    async def update_mv_btn_status(self, song):
        mv = await async_run(lambda: song.mv)
        if mv:
            self.mv_btn.setToolTip(mv.name)
            self.mv_btn.setEnabled(True)
        else:
            self.mv_btn.setEnabled(False)

    def _on_player_state_changed(self, state):
        self.pp_btn.setChecked(state == State.playing)
示例#53
0
    def request_safe_t_init_settings(self, wizard, method, device):
        vbox = QVBoxLayout()
        next_enabled = True
        label = QLabel(_("Enter a label to name your device:"))
        name = QLineEdit()
        hl = QHBoxLayout()
        hl.addWidget(label)
        hl.addWidget(name)
        hl.addStretch(1)
        vbox.addLayout(hl)

        def clean_text(widget):
            text = widget.toPlainText().strip()
            return ' '.join(text.split())

        if method in [TIM_NEW, TIM_RECOVER]:
            gb = QGroupBox()
            hbox1 = QHBoxLayout()
            gb.setLayout(hbox1)
            vbox.addWidget(gb)
            gb.setTitle(_("Select your seed length:"))
            bg = QButtonGroup()
            for i, count in enumerate([12, 18, 24]):
                rb = QRadioButton(gb)
                rb.setText(_("{:d} words").format(count))
                bg.addButton(rb)
                bg.setId(rb, i)
                hbox1.addWidget(rb)
                rb.setChecked(True)
            cb_pin = QCheckBox(_('Enable PIN protection'))
            cb_pin.setChecked(True)
        else:
            text = QTextEdit()
            text.setMaximumHeight(60)
            if method == TIM_MNEMONIC:
                msg = _("Enter your BIP39 mnemonic:")
            else:
                msg = _("Enter the master private key beginning with xprv:")

                def set_enabled():
                    from electrum_dash.bip32 import is_xprv
                    wizard.next_button.setEnabled(is_xprv(clean_text(text)))

                text.textChanged.connect(set_enabled)
                next_enabled = False

            vbox.addWidget(QLabel(msg))
            vbox.addWidget(text)
            pin = QLineEdit()
            pin.setValidator(QRegExpValidator(QRegExp('[1-9]{0,9}')))
            pin.setMaximumWidth(100)
            hbox_pin = QHBoxLayout()
            hbox_pin.addWidget(QLabel(_("Enter your PIN (digits 1-9):")))
            hbox_pin.addWidget(pin)
            hbox_pin.addStretch(1)

        if method in [TIM_NEW, TIM_RECOVER]:
            vbox.addWidget(WWLabel(RECOMMEND_PIN))
            vbox.addWidget(cb_pin)
        else:
            vbox.addLayout(hbox_pin)

        passphrase_msg = WWLabel(PASSPHRASE_HELP_SHORT)
        passphrase_warning = WWLabel(PASSPHRASE_NOT_PIN)
        passphrase_warning.setStyleSheet("color: red")
        cb_phrase = QCheckBox(_('Enable passphrases'))
        cb_phrase.setChecked(False)
        vbox.addWidget(passphrase_msg)
        vbox.addWidget(passphrase_warning)
        vbox.addWidget(cb_phrase)

        wizard.exec_layout(vbox, next_enabled=next_enabled)

        if method in [TIM_NEW, TIM_RECOVER]:
            item = bg.checkedId()
            pin = cb_pin.isChecked()
        else:
            item = ' '.join(str(clean_text(text)).split())
            pin = str(pin.text())

        return (item, name.text(), pin, cb_phrase.isChecked())
示例#54
0
    def show_settings_dialog(self, window, success):
        if not success:
            window.show_message(_('Server not reachable.'))
            return

        wallet = window.wallet
        d = WindowModalDialog(window, _("TrustedCoin Information"))
        d.setMinimumSize(500, 200)
        vbox = QVBoxLayout(d)
        hbox = QHBoxLayout()

        logo = QLabel()
        logo.setPixmap(QPixmap(icon_path("trustedcoin-status.png")))
        msg = _('This wallet is protected by TrustedCoin\'s two-factor authentication.') + '<br/>'\
              + _("For more information, visit") + " <a href=\"https://api.trustedcoin.com/#/electrum-help\">https://api.trustedcoin.com/#/electrum-help</a>"
        label = QLabel(msg)
        label.setOpenExternalLinks(1)

        hbox.addStretch(10)
        hbox.addWidget(logo)
        hbox.addStretch(10)
        hbox.addWidget(label)
        hbox.addStretch(10)

        vbox.addLayout(hbox)
        vbox.addStretch(10)

        msg = _(
            'TrustedCoin charges a small fee to co-sign transactions. The fee depends on how many prepaid transactions you buy. An extra output is added to your transaction every time you run out of prepaid transactions.'
        ) + '<br/>'
        label = QLabel(msg)
        label.setWordWrap(1)
        vbox.addWidget(label)

        vbox.addStretch(10)
        grid = QGridLayout()
        vbox.addLayout(grid)

        price_per_tx = wallet.price_per_tx
        n_prepay = wallet.num_prepay()
        i = 0
        for k, v in sorted(price_per_tx.items()):
            if k == 1:
                continue
            grid.addWidget(QLabel("Pay every %d transactions:" % k), i, 0)
            grid.addWidget(
                QLabel(
                    window.format_amount(v / k) + ' ' + window.base_unit() +
                    "/tx"), i, 1)
            b = QRadioButton()
            b.setChecked(k == n_prepay)
            b.clicked.connect(lambda b, k=k: self.config.set_key(
                'trustedcoin_prepay', k, True))
            grid.addWidget(b, i, 2)
            i += 1

        n = wallet.billing_info.get('tx_remaining', 0)
        grid.addWidget(
            QLabel(_("Your wallet has {} prepaid transactions.").format(n)), i,
            0)
        vbox.addLayout(Buttons(CloseButton(d)))
        d.exec_()
示例#55
0
    def __init__(self, resultwindow, stencil_field_mapper):
        super().__init__(resultwindow)

        # Data
        self.__stencil_field_mapper = stencil_field_mapper
        self.__draw_success_icons = True
        self.__draw_failure_icons = True

        self.__table_data = None
        self.__current_cell_row = None
        self.__current_cell_col = None
        self.__last_cell_row = None
        self.__last_cell_row = None

        self.__current_invocation_count = 0

        # Widgets
        self.__widget_resultwindow = resultwindow
        self.__widget_table = QTableWidget(self)
        self.__currently_processing_custom_context_menu_request = False

        self.__widget_label_title = QLabel("", parent=self)

        self.__widget_label_invocation_count = QLabel("Invocation count: ",
                                                      parent=self)
        self.__widget_label_invocation_count.setStatusTip(
            "Select the invocation of the stencil")
        self.__widget_combobox_invocation_count = QComboBox(self)
        self.__widget_combobox_invocation_count.currentIndexChanged.connect(
            self.set_invocation_count)

        self.__widget_checkbox_draw_success = QCheckBox(self)
        self.__widget_checkbox_draw_success.setIcon(Icon("success.png"))
        self.__widget_checkbox_draw_success.setChecked(True)
        self.__widget_checkbox_draw_success.stateChanged[int].connect(
            self.set_draw_success)
        self.__widget_checkbox_draw_success.setStatusTip("Show success icons")

        self.__widget_checkbox_draw_failure = QCheckBox(self)
        self.__widget_checkbox_draw_failure.setIcon(Icon("failure-small.png"))
        self.__widget_checkbox_draw_failure.setChecked(True)
        self.__widget_checkbox_draw_failure.stateChanged[int].connect(
            self.set_draw_failure)
        self.__widget_checkbox_draw_failure.setStatusTip("Show failure icons")

        self.__widget_label_result = QLabel("", parent=self)
        self.__widget_label_result_icon = QLabel("", parent=self)

        self.__widget_label_loading = QLabel("", parent=self)

        vbox = QVBoxLayout()

        hbox_top = QHBoxLayout()
        hbox_top.addWidget(self.__widget_label_title)
        hbox_top.addStretch(1)
        hbox_top.addWidget(self.__widget_checkbox_draw_success)
        hbox_top.addWidget(self.__widget_checkbox_draw_failure)
        vbox.addLayout(hbox_top)

        hbox_middle = QHBoxLayout()
        hbox_middle.addWidget(self.__widget_label_invocation_count)
        hbox_middle.addWidget(self.__widget_combobox_invocation_count)
        hbox_middle.addStretch(1)
        vbox.addLayout(hbox_middle)

        vbox.addWidget(self.__widget_table)

        hbox_bottom = QHBoxLayout()
        hbox_bottom.addWidget(self.__widget_label_result)
        hbox_bottom.addWidget(self.__widget_label_result_icon)
        hbox_bottom.addStretch(1)
        hbox_bottom.addWidget(self.__widget_label_loading)

        vbox.addLayout(hbox_bottom)

        self.setLayout(vbox)
示例#56
0
        def initUI(self):
            main_layout = QVBoxLayout()
            # main_layout.setSpacing(5)
            hor1 = QHBoxLayout()

            self.day_box = QLineEdit(os.path.basename(self.data.day_folder))
            hor1.addWidget(self.day_box)

            day_folder = QPushButton('Day')
            day_folder.clicked.connect(self.dayBtnPressed)
            hor1.addWidget(day_folder)

            hor1.addWidget(QLabel('Meas. type'))

            self.meas_type_box = QComboBox()
            self.meas_type_box.addItems(self.data.all_types)
            self.meas_type_box.setCurrentText(self.data.current_type)
            self.meas_type_box.currentTextChanged.connect(self.measTypeChanged)
            hor1.addWidget(self.meas_type_box)

            # hor1.addWidget(QLabel('other params'))
            #
            # other_params_box = QLineEdit(self.data.other_params)
            # other_params_box.editingFinished.connect(self.otherParamsChanged)
            # hor1.addWidget(other_params_box)

            main_layout.addLayout(hor1)

            self.param_table = QTableWidget(2, self.N_params)
            self.param_table.setVerticalHeaderLabels(['param', 'value'])
            self.param_table.setMaximumHeight(80)
            for i, s in enumerate(self.data.other_params.split()):
                if '=' not in s:
                    self.param_table.setItem(0, i, QTableWidgetItem(s))
                else:
                    self.param_table.setItem(0, i,
                                             QTableWidgetItem(s.split('=')[0]))
                    self.param_table.setItem(1, i,
                                             QTableWidgetItem(s.split('=')[1]))
            self.param_table.horizontalHeader().hide()
            # param_table.setItem(0,0,QTableWidgetItem('param'))
            # param_table.setItem(1, 0, QTableWidgetItem('value'))

            main_layout.addWidget(self.param_table)

            hor2 = QHBoxLayout()

            hor2.addWidget(QLabel('Folder'))

            # self.meas_folder_box = QLineEdit(self.data.name)
            # self.updateMeasFolder()
            # self.meas_folder_box.editingFinished.connect(self.measFolderChanged)
            self.meas_folder_box = QLabel(self.data.name)
            self.meas_folder_box.setStyleSheet(
                "QLabel { background-color : white}")
            self.meas_folder_box.setFont(QFont("Arial", 14))
            hor2.addWidget(self.meas_folder_box)
            hor2.addStretch(1)

            new_btn = QPushButton('New')
            new_btn.clicked.connect(self.newBtnPressed)
            hor2.addWidget(new_btn)

            open_btn = QPushButton('Open')
            open_btn.clicked.connect(self.openBtnPressed)
            hor2.addWidget(open_btn)

            main_layout.addLayout(hor2)

            self.setLayout(main_layout)
示例#57
0
    def make_page(self):
        page = QFrame()
        layout = QVBoxLayout()
        page.setLayout(layout)

        line1 = QFrame()
        layout1 = QHBoxLayout()
        line1.setLayout(layout1)
        layout.addWidget(line1)

        line2 = QFrame()
        layout2 = QHBoxLayout()
        line2.setLayout(layout2)
        layout.addWidget(line2)

        line3 = QFrame()
        layout3 = QHBoxLayout()
        line3.setLayout(layout3)
        layout.addWidget(line3)

        self.edit_start = QComboBoxNoWheel()
        self.edit_start.addItem("-")
        self.edit_start.addItem("1")
        self.edit_start.addItem("2")
        self.edit_start.addItem("3")
        self.edit_start.currentIndexChanged.connect(self.onChange)
        layout1.addWidget(self.edit_start)

        self.edit_end = QComboBoxNoWheel()
        self.edit_end.addItem("-")
        self.edit_end.addItem("1")
        self.edit_end.addItem("2")
        self.edit_end.addItem("3")
        self.edit_end.currentIndexChanged.connect(self.onChange)
        layout1.addWidget(self.edit_end)

        layout1.addStretch(1)

        delete = QPushButton('Delete')
        delete.clicked.connect(self.delete_self)
        layout1.addWidget(delete)

        layout2.addWidget(QLabel("<b>Pos:</b> "))

        self.edit_posref = QComboBoxNoWheel()
        self.edit_posref.addItem("Chord %")
        self.edit_posref.addItem("Rel Front")
        self.edit_posref.addItem("Rel Rear")
        self.edit_posref.addItem("Abs Pos")
        self.edit_posref.currentIndexChanged.connect(self.onChange)
        layout2.addWidget(self.edit_posref)

        self.edit_pos = QLineEdit()
        self.edit_pos.setFixedWidth(50)
        self.edit_pos.textChanged.connect(self.onChange)
        layout2.addWidget(self.edit_pos)

        layout2.addWidget(QLabel("<b>At Station:</b> "))
        self.edit_atstation = QLineEdit()
        self.edit_atstation.setFixedWidth(50)
        self.edit_atstation.textChanged.connect(self.onChange)
        layout2.addWidget(self.edit_atstation)

        layout2.addWidget(QLabel("<b>Slope:</b> "))
        self.edit_slope = QLineEdit()
        self.edit_slope.setFixedWidth(50)
        self.edit_slope.textChanged.connect(self.onChange)
        layout2.addWidget(self.edit_slope)

        layout2.addStretch(1)

        layout3.addWidget(QLabel("<b>Edge Stringer W x H:</b> "))

        self.edit_width = QLineEdit()
        self.edit_width.setFixedWidth(50)
        self.edit_width.textChanged.connect(self.onChange)
        layout3.addWidget(self.edit_width)

        self.edit_height = QLineEdit()
        self.edit_height.setFixedWidth(50)
        self.edit_height.textChanged.connect(self.onChange)
        layout3.addWidget(self.edit_height)

        layout3.addWidget(QLabel("<b>Hinge Cutout Angle:</b> "))

        self.edit_angle = QLineEdit()
        self.edit_angle.setFixedWidth(50)
        self.edit_angle.textChanged.connect(self.onChange)
        layout3.addWidget(self.edit_angle)

        layout3.addStretch(1)

        return page
示例#58
0
    def request_trezor_init_settings(self, wizard, method, device_id):
        vbox = QVBoxLayout()
        next_enabled = True

        devmgr = self.device_manager()
        client = devmgr.client_by_id(device_id)
        if not client:
            raise Exception(_("The device was disconnected."))
        model = client.get_trezor_model()
        fw_version = client.client.version
        capabilities = client.client.features.capabilities
        have_shamir = Capability.Shamir in capabilities

        # label
        label = QLabel(_("Enter a label to name your device:"))
        name = QLineEdit()
        hl = QHBoxLayout()
        hl.addWidget(label)
        hl.addWidget(name)
        hl.addStretch(1)
        vbox.addLayout(hl)

        # Backup type
        gb_backuptype = QGroupBox()
        hbox_backuptype = QHBoxLayout()
        gb_backuptype.setLayout(hbox_backuptype)
        vbox.addWidget(gb_backuptype)
        gb_backuptype.setTitle(_('Select backup type:'))
        bg_backuptype = QButtonGroup()

        rb_single = QRadioButton(gb_backuptype)
        rb_single.setText(_('Single seed (BIP39)'))
        bg_backuptype.addButton(rb_single)
        bg_backuptype.setId(rb_single, BackupType.Bip39)
        hbox_backuptype.addWidget(rb_single)
        rb_single.setChecked(True)

        rb_shamir = QRadioButton(gb_backuptype)
        rb_shamir.setText(_('Shamir'))
        bg_backuptype.addButton(rb_shamir)
        bg_backuptype.setId(rb_shamir, BackupType.Slip39_Basic)
        hbox_backuptype.addWidget(rb_shamir)
        rb_shamir.setEnabled(Capability.Shamir in capabilities)
        rb_shamir.setVisible(False)  # visible with "expert settings"

        rb_shamir_groups = QRadioButton(gb_backuptype)
        rb_shamir_groups.setText(_('Super Shamir'))
        bg_backuptype.addButton(rb_shamir_groups)
        bg_backuptype.setId(rb_shamir_groups, BackupType.Slip39_Advanced)
        hbox_backuptype.addWidget(rb_shamir_groups)
        rb_shamir_groups.setEnabled(Capability.ShamirGroups in capabilities)
        rb_shamir_groups.setVisible(False)  # visible with "expert settings"

        # word count
        word_count_buttons = {}

        gb_numwords = QGroupBox()
        hbox1 = QHBoxLayout()
        gb_numwords.setLayout(hbox1)
        vbox.addWidget(gb_numwords)
        gb_numwords.setTitle(_("Select seed/share length:"))
        bg_numwords = QButtonGroup()
        for count in (12, 18, 20, 24, 33):
            rb = QRadioButton(gb_numwords)
            word_count_buttons[count] = rb
            rb.setText(_("{:d} words").format(count))
            bg_numwords.addButton(rb)
            bg_numwords.setId(rb, count)
            hbox1.addWidget(rb)
            rb.setChecked(True)

        def configure_word_counts():
            if model == "1":
                checked_wordcount = 24
            else:
                checked_wordcount = 12

            if method == TIM_RECOVER:
                if have_shamir:
                    valid_word_counts = (12, 18, 20, 24, 33)
                else:
                    valid_word_counts = (12, 18, 24)
            elif rb_single.isChecked():
                valid_word_counts = (12, 18, 24)
                gb_numwords.setTitle(_('Select seed length:'))
            else:
                valid_word_counts = (20, 33)
                checked_wordcount = 20
                gb_numwords.setTitle(_('Select share length:'))

            word_count_buttons[checked_wordcount].setChecked(True)
            for c, btn in word_count_buttons.items():
                btn.setVisible(c in valid_word_counts)

        bg_backuptype.buttonClicked.connect(configure_word_counts)
        configure_word_counts()

        # set up conditional visibility:
        # 1. backup_type is only visible when creating new seed
        gb_backuptype.setVisible(method == TIM_NEW)
        # 2. word_count is not visible when recovering on TT
        if method == TIM_RECOVER and model != "1":
            gb_numwords.setVisible(False)

        # PIN
        cb_pin = QCheckBox(_('Enable PIN protection'))
        cb_pin.setChecked(True)
        vbox.addWidget(WWLabel(RECOMMEND_PIN))
        vbox.addWidget(cb_pin)

        # "expert settings" button
        expert_vbox = QVBoxLayout()
        expert_widget = QWidget()
        expert_widget.setLayout(expert_vbox)
        expert_widget.setVisible(False)
        expert_button = QPushButton(_("Show expert settings"))

        def show_expert_settings():
            expert_button.setVisible(False)
            expert_widget.setVisible(True)
            rb_shamir.setVisible(True)
            rb_shamir_groups.setVisible(True)

        expert_button.clicked.connect(show_expert_settings)
        vbox.addWidget(expert_button)

        # passphrase
        passphrase_msg = WWLabel(PASSPHRASE_HELP_SHORT)
        passphrase_warning = WWLabel(PASSPHRASE_NOT_PIN)
        passphrase_warning.setStyleSheet("color: red")
        cb_phrase = QCheckBox(_('Enable passphrases'))
        cb_phrase.setChecked(False)
        expert_vbox.addWidget(passphrase_msg)
        expert_vbox.addWidget(passphrase_warning)
        expert_vbox.addWidget(cb_phrase)

        # ask for recovery type (random word order OR matrix)
        bg_rectype = None
        if method == TIM_RECOVER and model == '1':
            gb_rectype = QGroupBox()
            hbox_rectype = QHBoxLayout()
            gb_rectype.setLayout(hbox_rectype)
            expert_vbox.addWidget(gb_rectype)
            gb_rectype.setTitle(_("Select recovery type:"))
            bg_rectype = QButtonGroup()

            rb1 = QRadioButton(gb_rectype)
            rb1.setText(_('Scrambled words'))
            bg_rectype.addButton(rb1)
            bg_rectype.setId(rb1, RecoveryDeviceType.ScrambledWords)
            hbox_rectype.addWidget(rb1)
            rb1.setChecked(True)

            rb2 = QRadioButton(gb_rectype)
            rb2.setText(_('Matrix'))
            bg_rectype.addButton(rb2)
            bg_rectype.setId(rb2, RecoveryDeviceType.Matrix)
            hbox_rectype.addWidget(rb2)

        # no backup
        cb_no_backup = None
        if method == TIM_NEW:
            cb_no_backup = QCheckBox(f'''{_('Enable seedless mode')}''')
            cb_no_backup.setChecked(False)
            if (model == '1' and fw_version >= (1, 7, 1)
                    or model == 'T' and fw_version >= (2, 0, 9)):
                cb_no_backup.setToolTip(SEEDLESS_MODE_WARNING)
            else:
                cb_no_backup.setEnabled(False)
                cb_no_backup.setToolTip(_('Firmware version too old.'))
            expert_vbox.addWidget(cb_no_backup)

        vbox.addWidget(expert_widget)
        wizard.exec_layout(vbox, next_enabled=next_enabled)

        return TrezorInitSettings(
            word_count=bg_numwords.checkedId(),
            label=name.text(),
            pin_enabled=cb_pin.isChecked(),
            passphrase_enabled=cb_phrase.isChecked(),
            recovery_type=bg_rectype.checkedId() if bg_rectype else None,
            backup_type=bg_backuptype.checkedId(),
            no_backup=cb_no_backup.isChecked() if cb_no_backup else False,
        )
示例#59
0
 def initRewardsForm(self):
     self.collateralHidden = True
     self.rewardsForm = QGroupBox()
     self.rewardsForm.setTitle("Transfer Rewards")
     layout = QFormLayout()
     layout.setContentsMargins(10, 10, 10, 10)
     layout.setSpacing(13)
     layout.setFieldGrowthPolicy(QFormLayout.AllNonFixedFieldsGrow)
     ##--- ROW 1
     hBox = QHBoxLayout()
     self.mnSelect = QComboBox()
     self.mnSelect.setToolTip("Select Masternode")
     hBox.addWidget(self.mnSelect)
     self.btn_ReloadUTXOs = QPushButton()
     self.btn_ReloadUTXOs.setToolTip("Reload UTXOs")
     refresh_icon = QIcon(os.path.join(self.imgDir, 'icon_refresh.png'))
     self.btn_ReloadUTXOs.setIcon(refresh_icon)
     hBox.addWidget(self.btn_ReloadUTXOs)
     hBox.addStretch(1)
     label = QLabel("Total Address Balance")
     label.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
     hBox.addWidget(label)
     self.addrAvailLine = QLabel()
     self.addrAvailLine.setToolTip("PIVX Address total balance")
     self.addrAvailLine.setText("--")
     hBox.addWidget(self.addrAvailLine)
     self.btn_toggleCollateral = QPushButton("Show Collateral")
     hBox.addWidget(self.btn_toggleCollateral)
     layout.addRow(QLabel("Masternode"), hBox)
     ## --- ROW 2: REWARDS
     self.rewardsList = QVBoxLayout()
     self.rewardsList.statusLabel = QLabel()
     self.rewardsList.statusLabel.setMinimumWidth(116)
     self.resetStatusLabel('<b style="color:red">Reload Rewards</b>')
     self.rewardsList.addWidget(self.rewardsList.statusLabel)
     self.rewardsList.box = QTableWidget()
     self.rewardsList.box.setMinimumHeight(140)
     #self.rewardsList.box.setMaximumHeight(140)
     self.rewardsList.box.setHorizontalScrollBarPolicy(
         Qt.ScrollBarAlwaysOff)
     self.rewardsList.box.setSelectionMode(QAbstractItemView.MultiSelection)
     self.rewardsList.box.setSelectionBehavior(QAbstractItemView.SelectRows)
     self.rewardsList.box.setShowGrid(True)
     self.rewardsList.box.setColumnCount(4)
     self.rewardsList.box.setRowCount(0)
     self.rewardsList.box.horizontalHeader().setSectionResizeMode(
         2, QHeaderView.Stretch)
     self.rewardsList.box.verticalHeader().hide()
     item = QTableWidgetItem()
     item.setText("PIVs")
     item.setTextAlignment(Qt.AlignCenter)
     self.rewardsList.box.setHorizontalHeaderItem(0, item)
     item = QTableWidgetItem()
     item.setText("Confirmations")
     item.setTextAlignment(Qt.AlignCenter)
     self.rewardsList.box.setHorizontalHeaderItem(1, item)
     item = QTableWidgetItem()
     item.setText("TX Hash")
     item.setTextAlignment(Qt.AlignCenter)
     self.rewardsList.box.setHorizontalHeaderItem(2, item)
     item = QTableWidgetItem()
     item.setText("TX Output N")
     item.setTextAlignment(Qt.AlignCenter)
     self.rewardsList.box.setHorizontalHeaderItem(3, item)
     item = QTableWidgetItem()
     self.rewardsList.addWidget(self.rewardsList.box)
     layout.addRow(self.rewardsList)
     ##--- ROW 3
     hBox2 = QHBoxLayout()
     self.btn_selectAllRewards = QPushButton("Select All")
     self.btn_selectAllRewards.setToolTip("Select all available UTXOs")
     hBox2.addWidget(self.btn_selectAllRewards)
     self.btn_deselectAllRewards = QPushButton("Deselect all")
     self.btn_deselectAllRewards.setToolTip("Deselect current selection")
     hBox2.addWidget(self.btn_deselectAllRewards)
     hBox2.addWidget(QLabel("Selected rewards"))
     self.selectedRewardsLine = QLabel()
     self.selectedRewardsLine.setMinimumWidth(200)
     self.selectedRewardsLine.setStyleSheet("color: purple")
     self.selectedRewardsLine.setToolTip("PIVX to move away")
     hBox2.addWidget(self.selectedRewardsLine)
     hBox2.addStretch(1)
     layout.addRow(hBox2)
     ##--- ROW 4
     hBox3 = QHBoxLayout()
     self.destinationLine = QLineEdit()
     self.destinationLine.setToolTip("PIVX address to transfer rewards to")
     hBox3.addWidget(self.destinationLine)
     hBox3.addWidget(QLabel("Fee"))
     self.feeLine = QDoubleSpinBox()
     self.feeLine.setDecimals(8)
     self.feeLine.setPrefix("PIV  ")
     self.feeLine.setToolTip("Insert a small fee amount")
     self.feeLine.setFixedWidth(150)
     self.feeLine.setSingleStep(0.001)
     hBox3.addWidget(self.feeLine)
     self.btn_sendRewards = QPushButton("Send")
     hBox3.addWidget(self.btn_sendRewards)
     layout.addRow(QLabel("Destination Address"), hBox3)
     ##--- ROW 5
     hBox4 = QHBoxLayout()
     hBox4.addStretch(1)
     self.loadingLine = QLabel(
         "<b style='color:red'>Preparing TX.</b> Completed: ")
     self.loadingLinePercent = QProgressBar()
     self.loadingLinePercent.setMaximumWidth(200)
     self.loadingLinePercent.setMaximumHeight(10)
     self.loadingLinePercent.setRange(0, 100)
     hBox4.addWidget(self.loadingLine)
     hBox4.addWidget(self.loadingLinePercent)
     self.loadingLine.hide()
     self.loadingLinePercent.hide()
     layout.addRow(hBox4)
     #--- Set Layout
     self.rewardsForm.setLayout(layout)
     #--- ROW 5
     self.btn_Cancel = QPushButton("Clear/Reload")
    def createPanel(self):
        hboxButton = QHBoxLayout()
        btnSave = QPushButton(self.translate("nauticalChartPanel", "Save"))
        btnExit = QPushButton(self.translate("nauticalChartPanel", "Exit"))
        self.groupButtonConfigure = QButtonGroup()
        self.groupButtonConfigure.addButton(btnSave)
        self.groupButtonConfigure.addButton(btnExit)

        hboxButton.addStretch()
        hboxButton.addWidget(btnSave)
        hboxButton.addWidget(btnExit)

        self.inbound = inboundPanel.InboundPanel(self.treasureChest)
        self.outbound = outboundPanel.OutboundPanel(self.treasureChest)

        tabWidgetConfigurePanel = QTabWidget()
        tabWidgetConfigurePanel.addTab(
            self.inbound.createInboundPanel(),
            self.translate("nauticalChartPanel", "Inbound"))
        tabWidgetConfigurePanel.addTab(
            self.outbound.createOutboundPanel(),
            self.translate("nauticalChartPanel", "Outbound"))

        self.transportTAB = transportTAB.transportTab()
        tabWidgetConfigurePanel.addTab(
            self.transportTAB.createTransportPanel(),
            self.translate("nauticalChartPanel", "Transport Setting"))

        self.dnsTAB = dnsTAB.dnsTab()
        tabWidgetConfigurePanel.addTab(
            self.dnsTAB.createDnsTab(),
            self.translate("nauticalChartPanel", "DNS Server"))

        self.routingTAB = routingTAB.routingTab()
        tabWidgetConfigurePanel.addTab(
            self.routingTAB.createRoutingTab(),
            self.translate("nauticalChartPanel", "Router Setting"))

        self.policyTAB = policyTAB.policyTab(self.treasureChest)
        tabWidgetConfigurePanel.addTab(
            self.policyTAB.createPolicyTab(),
            self.translate("nauticalChartPanel", "Policy"))

        self.logTAB = logTAB.logTab()
        tabWidgetConfigurePanel.addTab(
            self.logTAB.createLogTab(),
            self.translate("nauticalChartPanel", "Log Files"))

        vboxConfigure = QVBoxLayout()
        vboxConfigure.addWidget(tabWidgetConfigurePanel)
        vboxConfigure.addLayout(hboxButton)
        self.ScrollLayout(vboxConfigure)

        if (v2rayshellDebug):
            self.__debugBtn = QPushButton("__debugTest", self)
            self.__debugRefresh = QPushButton("__RefreshTest", self)
            self.__printTags = QPushButton("__PrintTags", self)
            self.__printAllLevels = QPushButton("__PrintAllLevels", self)
            self.__printAllEmails = QPushButton("__PrintAllEmails", self)

            hboxBtn = QHBoxLayout(self)
            hboxBtn.addWidget(self.__debugBtn)
            hboxBtn.addWidget(self.__printTags)
            hboxBtn.addWidget(self.__printAllLevels)
            hboxBtn.addWidget(self.__printAllEmails)
            hboxBtn.addWidget(self.__debugRefresh)
            vboxConfigure.addLayout(hboxBtn)

            self.__debugBtn.clicked.connect(self.__debugTest)
            self.__debugRefresh.clicked.connect(self.__debugRefreshTest)
            self.__printTags.clicked.connect(
                lambda: print(self.treasureChest.getAllTags()))
            self.__printAllLevels.clicked.connect(
                lambda: print(self.treasureChest.getLevels()))
            self.__printAllEmails.clicked.connect(
                lambda: print(self.treasureChest.getEmails()))

            self.editV2rayJSONFile = openV2rayJSONFile.editV2rayJSONFile(
                self.treasureChest)
            tabWidgetConfigurePanel.addTab(
                self.editV2rayJSONFile.createPanel(), "open V2ray File")
            self.settingv2rayshellPanelFromJSONFile(True)

        if (self.filePath):
            openV2rayJSONFile.openV2rayJSONFile(
                self.filePath, self.treasureChest).initboundJSONData()
            self.settingv2rayshellPanelFromJSONFile(openFromJSONFile=True)

        self.createPanelSignals()