Beispiel #1
1
class MainWindow(QMainWindow):
    
#    class EventFilter(QObject):
#        def __init__(self, parent):
#            super().__init__(parent)
#
#        def eventFilter(self, obj, e):
#            #print(obj.metaObject().className())
#
#            if e.type() == QEvent.KeyPress or e.type() == QEvent.ShortcutOverride:
#                key = e.key()
#                mod = e.modifiers()
#
#                print(str(e) + ' ' + str(e.type()) )
#
#                if mod == Qt.AltModifier:
#                    print('*'*30)
#                    print('alt pressed')
#                    if key == Qt.Key_Left or key == Qt.Key_Right:
#                        print('alt-left') if key == Qt.Key_Left else print('alt-right')
##                       action = QAbstractItemView.MoveLeft if key == Qt.Key_Left else QAbstractItemView.MoveRight
##                       idx = obj.moveCursor(action, Qt.NoModifier)
##                       item = obj.itemFromIndex(idx)
##                       obj.setCurrentItem(item)
#                        return True
#
#            return False


    PROGRAM_NAME = 'KiCad Schematic Component Manager'

    #--------------------------------------------------------------------------------
    class EventFilter(QObject):
        def __init__(self, parent):
            super().__init__(parent)

        def eventFilter(self, obj, e):
            if e.type() == QEvent.KeyPress or e.type() == QEvent.ShortcutOverride:
                key = e.key()
                mod = e.modifiers()

                #print(obj.focusWidget().metaObject().className())

            return False
    #--------------------------------------------------------------------------------
    def scroll_left(self):
        print('alt-left')
        if self.ToolIndex == 3 or self.ToolIndex == 2:
            self.ToolList[self.ToolIndex].finish_edit()
            
        self.ToolIndex -= 1
        if self.ToolIndex < 0:
            self.ToolIndex = len(self.ToolList) - 1
            
        print('Tool Index: ' + str(self.ToolIndex))
        self.ToolList[self.ToolIndex].setFocus()
    #--------------------------------------------------------------------------------    
    def scroll_right(self):
        print('alt-right')
        if self.ToolIndex == 3 or self.ToolIndex == 2:
            self.ToolList[self.ToolIndex].finish_edit()
            
        self.ToolIndex += 1
        if self.ToolIndex == len(self.ToolList):
            self.ToolIndex = 0

        print('Tool Index: ' + str(self.ToolIndex))
        self.ToolList[self.ToolIndex].setFocus()
    #--------------------------------------------------------------------------------    
    def mouse_change_tool(self, s):
        print('Tool ' + s)
        if s == 'CmpTable':
            self.ToolIndex = 0
        elif s == 'Selector':
            self.ToolIndex = 1
        elif s == 'Inspector':
            self.ToolIndex = 2
        elif s == 'FieldInspector':
            self.ToolIndex = 3
            
        if self.ToolIndex != 3:
            self.ToolList[3].finish_edit()  # save field properties when leave field inspector
    #--------------------------------------------------------------------------------    
    def add_user_property(self):
        self.Inspector.save_cmps()
        self.FieldInspector.save_fields()
        
        self.Inspector.add_property()
    #--------------------------------------------------------------------------------
    def remove_user_property(self):
        #self.Inspector.save_cmps()
        self.FieldInspector.save_fields()

        self.Inspector.remove_property()
    #--------------------------------------------------------------------------------        
    def rename_user_property(self):
        #self.Inspector.save_cmps()
        self.FieldInspector.save_fields()
                    
        self.Inspector.rename_property()
    #--------------------------------------------------------------------------------    
    def __init__(self):
        super().__init__()
        
        self.initUI()
        
        self.installEventFilter(self.EventFilter(self))
        
        self.setFocusPolicy(Qt.WheelFocus)
        self.setTabOrder(self.CmpTable,      self.Inspector )
        self.setTabOrder(self.Inspector,     self.Selector)
        self.setTabOrder(self.Selector,      self.FieldInspector)
        #self.setTabOrder(self.FieldInspector, self.CmpTable)

        #----------------------------------------------------
        #
        #   Application Hotkeys
        #
        self.shortcutLeft  = QShortcut(QKeySequence(Qt.ALT + Qt.Key_Left), self)
        self.shortcutRight = QShortcut(QKeySequence(Qt.ALT + Qt.Key_Right), self)
        self.shortcutLeft.setContext(Qt.ApplicationShortcut)
        self.shortcutRight.setContext(Qt.ApplicationShortcut)
        self.shortcutLeft.activated.connect(self.scroll_left)
        self.shortcutRight.activated.connect(self.scroll_right)
        
    #--------------------------------------------------------------------------------    
    def initUI(self):
        
        #----------------------------------------------------
        #
        #    Main Window
        #
        work_zone = QWidget(self)
        Layout    = QHBoxLayout(work_zone)
        self.setCentralWidget(work_zone)
        
        openAction = QAction(QIcon( os.path.join(resources_path, 'open24.png') ), 'Open', self)
        openAction.setShortcut('Ctrl+O')
        openAction.setStatusTip('Open Schematic File')
        openAction.triggered.connect(self.open_file)
        
        saveAction = QAction(QIcon( os.path.join(resources_path, 'save24.png') ), 'Save', self)
        saveAction.setShortcut('Ctrl+S')
        saveAction.setStatusTip('Save Schematic File')
        saveAction.triggered.connect(self.save_file)
                
        saveAsAction = QAction(QIcon( os.path.join(resources_path, 'save-as24.png') ), 'Save As...', self)
        saveAsAction.setShortcut('Ctrl+Shift+S')
        saveAsAction.setStatusTip('Save Schematic File As...')
        saveAsAction.triggered.connect(self.save_file_as)
        
                        
        exitAction = QAction(QIcon( os.path.join(resources_path, 'exit24.png') ), 'Exit', self)
        exitAction.setShortcut('Ctrl+Q')
        exitAction.setStatusTip('Exit application')
        exitAction.triggered.connect(self.close)
        
        settingsAction = QAction(QIcon( os.path.join(resources_path, 'settings24.png') ), 'Settings', self)
        settingsAction.setShortcut('Ctrl+Alt+S')
        settingsAction.setStatusTip('Edit settings')
        settingsAction.triggered.connect(self.edit_settings)
        
        helpAction = QAction(QIcon( os.path.join(resources_path, 'help_book24.png') ), 'User\'s Manual', self)
        helpAction.setShortcut('F1')
        helpAction.setStatusTip('User\'s Manual')
        helpAction.triggered.connect(self.show_user_manual_slot)
        
        helpSDAction = QAction(QIcon( os.path.join(resources_path, 'gear24.png') ), 'Settings Dialog', self)
        helpSDAction.setShortcut('Ctrl+F1')
        helpSDAction.setStatusTip('Settings Dialog Help')
        helpSDAction.triggered.connect(self.show_setting_dialog_help_slot)
                
        helpHKAction = QAction(QIcon( os.path.join(resources_path, 'rocket24.png') ), 'Hotkeys', self)
        helpHKAction.setShortcut('Shift+F1')
        helpHKAction.setStatusTip('Hotkeys Help')
        helpHKAction.triggered.connect(self.show_hotkeys_help_slot)

        self.statusBar().showMessage('Ready')

        #--------------------------------------------
        #
        #    Main Menu
        #
        menubar = self.menuBar()
        fileMenu = menubar.addMenu('&File')
        fileMenu.addAction(openAction)
        fileMenu.addAction(saveAction)
        fileMenu.addAction(saveAsAction)
        fileMenu.addAction(exitAction)

        #--------------------------------------------
        #
        #    Options Menu
        #
        optionsMenu = menubar.addMenu('&Options')
        optionsMenu.addAction(settingsAction)
        
        #--------------------------------------------
        #
        #    Help Menu
        #
        helpMenu = menubar.addMenu('&Help')
        helpMenu.addAction(helpAction)
        helpMenu.addAction(helpSDAction)
        helpMenu.addAction(helpHKAction)
                
        #--------------------------------------------
        #
        #    Toolbar
        #
        toolbar = self.addToolBar('Exit')
        toolbar.addAction(exitAction)        
        toolbar.addAction(openAction)        
        toolbar.addAction(saveAction)        
        toolbar.addAction(saveAsAction)        
        toolbar.addAction(settingsAction)        
        toolbar.addAction(helpAction)        
        
        #----------------------------------------------------
        #
        #    Settings Dialog
        #
        
        #----------------------------------------------------
        #
        #    Components Table
        #
        self.CmpTabBox    = QGroupBox('Components', self)
        self.CmpTabLayout = QVBoxLayout(self.CmpTabBox)
        self.CmpTabLayout.setContentsMargins(4,10,4,4)
        self.CmpTabLayout.setSpacing(10)

        self.CmpTabLayout.setSizeConstraint(QVBoxLayout.SetMaximumSize)

        self.CmpTable       = ComponentsTable(self) 
        #self.CmpChooseButton = QPushButton('Choose', self)
        
        self.CmpTabLayout.addWidget(self.CmpTable)
        #self.CmpTabLayout.addWidget(self.CmpChooseButton)
        
                
        #----------------------------------------------------
        #
        #    Selector
        #
        self.SelectorBox    = QGroupBox('Selector', self)
        self.SelectorLayout = QVBoxLayout(self.SelectorBox)
        self.SelectorLayout.setContentsMargins(4,10,4,4)
        self.SelectorLayout.setSpacing(2)
        
        self.SelectorBtnWidget = QWidget(self)
        self.SelectorBtnLayout = QHBoxLayout(self.SelectorBtnWidget)
        self.SelectorBtnLayout.setContentsMargins(4,10,4,4)
        self.SelectorBtnLayout.setSpacing(10)

        self.Selector = Selector(self)

        self.SelApplyButton = QPushButton('Apply', self)
        self.SelApplyButton.setToolTip('Alt+S: Apply selection patterns to components')

        self.SelClearButton = QPushButton('Clear', self)
        self.SelClearButton.setToolTip('Alt+C: Clear selection patterns')

        self.SelTemplateButton = QPushButton('Use Component', self)
        self.SelTemplateButton.setToolTip('Alt+T: Use Selected Component As Template')


        self.SelectorLayout.addWidget(self.Selector)
        self.SelectorBtnLayout.addWidget(self.SelTemplateButton)
        self.SelectorBtnLayout.addWidget(self.SelApplyButton)
        self.SelectorBtnLayout.addWidget(self.SelClearButton)
        self.SelectorLayout.addWidget(self.SelectorBtnWidget)
        
        self.shortcutSelApply = QShortcut(QKeySequence(Qt.ALT + Qt.Key_S), self)
        self.shortcutSelApply.activated.connect(self.Selector.apply_slot)
        
        self.shortcutSelClear = QShortcut(QKeySequence(Qt.ALT + Qt.Key_C), self)
        self.shortcutSelClear.activated.connect(self.Selector.clear_slot)
                
        self.shortcutSelTemplate = QShortcut(QKeySequence(Qt.ALT + Qt.Key_T), self)
        self.shortcutSelTemplate.activated.connect(self.Selector.use_comp_as_template_slot)
        
        #----------------------------------------------------
        #
        #    Inspector
        #
        self.Inspector       = Inspector(self)
        self.FieldInspector  = FieldInspector(self)

        self.InspectorBtnWidget = QWidget(self)
        self.InspectorBtnLayout = QHBoxLayout(self.InspectorBtnWidget)
        self.InspectorBtnLayout.setContentsMargins(4,10,4,4)
        self.InspectorBtnLayout.setSpacing(10)
        

        self.AddUserProperty    = QPushButton('Add Property', self)
        self.AddUserProperty.setToolTip('Alt+A: Add new user property')
        self.DeleteUserProperty = QPushButton('Delete Property', self)
        self.DeleteUserProperty.setToolTip('Alt+Delete: Delete user property')
        self.RenameUserProperty = QPushButton('Rename Property', self)
        self.RenameUserProperty.setToolTip('Alt+R: Rename user property')
        
        self.InspectorBox    = QGroupBox('Inspector', self)
        self.InspectorSplit  = QSplitter(Qt.Vertical, self)
        self.InspectorLayout = QVBoxLayout(self.InspectorBox)
        self.InspectorLayout.setContentsMargins(4,10,4,4)
        self.InspectorLayout.setSpacing(2)
        
        
        self.InspectorSplit.addWidget(self.Inspector)
        self.InspectorSplit.addWidget(self.FieldInspector)
        self.InspectorLayout.addWidget(self.InspectorSplit)
        
        self.InspectorBtnLayout.addWidget(self.AddUserProperty)
        self.InspectorBtnLayout.addWidget(self.DeleteUserProperty)
        self.InspectorBtnLayout.addWidget(self.RenameUserProperty)
                
        self.InspectorLayout.addWidget(self.InspectorBtnWidget)

        self.shortcutSelApply = QShortcut(QKeySequence(Qt.ALT + Qt.Key_A), self)
        self.shortcutSelApply.activated.connect(self.add_user_property)
        
        self.shortcutSelApply = QShortcut(QKeySequence(Qt.ALT + Qt.Key_Delete), self)
        self.shortcutSelApply.activated.connect(self.remove_user_property)
        
        self.shortcutSelApply = QShortcut(QKeySequence(Qt.ALT + Qt.Key_R), self)
        self.shortcutSelApply.activated.connect(self.rename_user_property)
        
        #----------------------------------------------------

        self.Splitter = QSplitter(self)
        self.Splitter.addWidget(self.CmpTabBox)
        self.Splitter.addWidget(self.SelectorBox)   
        self.Splitter.addWidget(self.InspectorBox) 
                 
        self.centralWidget().layout().addWidget(self.Splitter)
        
        
        #----------------------------------------------------
        #
        #     Signals and Slots connections
        #
        self.CmpTable.cells_chosen.connect(self.Inspector.load_cmp)
        self.CmpTable.cells_chosen.connect(self.Selector.comp_template_slot)
        self.CmpTable.file_load.connect(self.file_loaded_slot)
        self.CmpTable.cmps_updated.connect(self.Selector.process_comps_slot)
        self.CmpTable.cmps_selected.connect(self.set_status_text_slot)

        self.SelApplyButton.clicked.connect(self.Selector.apply_slot)
        self.SelClearButton.clicked.connect(self.Selector.clear_slot)
        self.SelTemplateButton.clicked.connect(self.Selector.use_comp_as_template_slot)
        
        self.Selector.select_comps_signal.connect(self.CmpTable.select_comps_slot)

        self.Inspector.load_field.connect(self.FieldInspector.load_field_slot)
        self.Inspector.update_comps.connect(self.data_changed_slot)
        self.Inspector.update_comps.connect(self.CmpTable.update_cmp_list_slot)
        self.FieldInspector.data_changed.connect(self.data_changed_slot)
        CmpMgr.file_saved.connect(self.file_saved_slot)
        
        self.CmpTable.mouse_click.connect(self.mouse_change_tool)
        self.Inspector.mouse_click.connect(self.mouse_change_tool)
        self.FieldInspector.mouse_click.connect(self.mouse_change_tool)

        self.Inspector.header().sectionResized.connect(self.FieldInspector.column_resize)
        
        self.AddUserProperty.clicked.connect(self.add_user_property)
        self.DeleteUserProperty.clicked.connect(self.remove_user_property)
        self.RenameUserProperty.clicked.connect(self.rename_user_property)
        
        #----------------------------------------------------
        self.ToolList = []
        self.ToolList.append(self.CmpTable)
        self.ToolList.append(self.Selector)
        self.ToolList.append(self.Inspector)
        self.ToolList.append(self.FieldInspector)
        self.ToolIndex = 0
        
        
        #----------------------------------------------------
        #
        #    Window
        #
        self.setWindowTitle(self.PROGRAM_NAME)
        Settings = QSettings('kicad-tools', 'Schematic Component Manager')
        #print(Settings.allKeys())
        if Settings.contains('geometry'):
            self.restoreGeometry( Settings.value('geometry') )
        else:
            self.setGeometry(100, 100, 1024, 768)

        if Settings.contains('cmptable'):
            w0, w1 = Settings.value('cmptable')
            self.CmpTable.setColumnWidth( 0, int(w0) )
            self.CmpTable.setColumnWidth( 1, int(w1) )
            
        if Settings.contains('selector'):
            w0, w1 = Settings.value('selector')
            self.Selector.setColumnWidth( 0, int(w0) )
            self.Selector.setColumnWidth( 1, int(w1) )
                        
        if Settings.contains('inspector'):
            w0, w1 = Settings.value('inspector')
            self.Inspector.setColumnWidth( 0, int(w0) )
            self.Inspector.setColumnWidth( 1, int(w1) )
            self.FieldInspector.setColumnWidth( 0, int(w0) )
            self.FieldInspector.setColumnWidth( 1, int(w1) )
            #self.Inspector.setColumnWidth( 2, int(w2) )
            
        if Settings.contains('splitter'):
            self.Splitter.restoreState( Settings.value('splitter') )
            
        if Settings.contains('inssplitter'):
            self.InspectorSplit.restoreState( Settings.value('inssplitter') )
            
        #----------------------------------------------------
        #
        #    Process command line arguments
        #
        if len(sys.argv) > 1:
            fname = sys.argv[1]
            if os.path.exists(fname):
                self.CmpTable.load_file(fname)
            else:
                print('E: input file "' + fname + '"does not exist')
            
        self.show()
    #---------------------------------------------------------------------------
    def closeEvent(self, event):
        Settings = QSettings('kicad-tools', 'Schematic Component Manager')
        Settings.setValue( 'geometry', self.saveGeometry() )
        Settings.setValue( 'cmptable',  [self.CmpTable.columnWidth(0), self.CmpTable.columnWidth(1)] )
        Settings.setValue( 'selector',  [self.Selector.columnWidth(0), self.Selector.columnWidth(1)] )
        Settings.setValue( 'inspector', [self.Inspector.columnWidth(0), self.Inspector.columnWidth(1)] )
        Settings.setValue( 'splitter', self.Splitter.saveState() )
        Settings.setValue( 'inssplitter', self.InspectorSplit.saveState() )
        QWidget.closeEvent(self, event)
    #---------------------------------------------------------------------------
    def open_file(self):
        #filename = QFileDialog.getOpenFileName(self, 'Open schematic file', '/opt/cad/kicad', 'KiCad Schematic Files (*.sch)')
        dialog = QFileDialog(self)
        dialog.setFileMode(QFileDialog.ExistingFile)
        dialog.setNameFilter('KiCad Schematic Files (*.sch)')
        
        filenames = []
        if dialog.exec_():
            filenames = dialog.selectedFiles()
        if len(filenames) == 0:
            return
        
        CmpMgr.set_curr_file_path( filenames[0] )
        self.CmpTable.load_file( filenames[0] )
    #---------------------------------------------------------------------------
    def save_file(self):
        self.FieldInspector.save_fields()
        self.Inspector.save_cmps()
        
        curr_file = CmpMgr.curr_file_path()
        message = 'Save File "' + curr_file + '"'
        print(message)
        self.statusBar().showMessage(message)
        
        CmpMgr.save_file(curr_file)
    #---------------------------------------------------------------------------
    def save_file_as(self):
        self.Inspector.save_cmps()
        self.FieldInspector.save_fields()
        filenames = QFileDialog.getSaveFileName(self, 'Save File As...', '', 'KiCad Schematic Files (*.sch)')
            
        if filenames[0] == '':
            return
            
        print('Save File As "' + filenames[0] + '"')
        CmpMgr.save_file(filenames[0])
        CmpMgr.set_curr_file_path( filenames[0] )
    #---------------------------------------------------------------------------
    def file_loaded_slot(self):
        text = CmpMgr.curr_file_path()
        self.set_title(text)
    #---------------------------------------------------------------------------
    def data_changed_slot(self):
        text = CmpMgr.curr_file_path() + ' *'
        self.set_title(text)
    #---------------------------------------------------------------------------
    def file_saved_slot(self):
        text = CmpMgr.curr_file_path()
        self.set_title(text)
    #---------------------------------------------------------------------------
    def set_title(self, text = ''):
        text = ' - ' + text if len(text) > 0 else ''
        self.setWindowTitle(self.PROGRAM_NAME + ' v' + VERSION + text)
    #---------------------------------------------------------------------------
    def set_status_text_slot(self, text):
        self.statusBar().showMessage(text)
    #---------------------------------------------------------------------------
    def edit_settings(self):
        print('edit settings')
        SettingsDialog = TSettingsDialog(self)
        SettingsDialog.resize(400, 400)
        SettingsDialog.Tabs.setMinimumWidth(800)
        SettingsDialog.show()
    #---------------------------------------------------------------------------
    def show_user_manual_slot(self):
        help = THelpForm(self, 'User\'s Manual', 'main.html')
    #---------------------------------------------------------------------------
    def show_setting_dialog_help_slot(self):
        help = THelpForm(self, 'Settings Dialog', 'settings.html')
    #---------------------------------------------------------------------------
    def show_hotkeys_help_slot(self):
        help = THelpForm(self, 'Hotkeys', 'hotkeys.html')
Beispiel #2
0
    def __init__(self, parent: QWidget,
            msg: Optional[str]=None,
            title: Optional[str]=None,
            fields: Optional[LayoutFields]=None,
            kind: PasswordAction=PasswordAction.CHANGE,
            password_check_fn: Optional[PasswordCheckCallbackType]=None) -> None:
        WindowModalDialog.__init__(self, parent)

        OK_button = OkButton(self)
        # NOTE(rt12): This preserves existing behaviour for the `is_new` case.
        OK_button.setEnabled(kind != PasswordAction.NEW)

        def state_change_fn(state: bool) -> None:
            OK_button.setEnabled(state)

        if msg is None:
            if kind == PasswordAction.NEW:
                msg = _('Your wallet needs a password.')
                msg += ' ' + _('Use this dialog to set your password.')
            else:
                msg = _('Your wallet is password protected.')
                msg += ' ' + _('Use this dialog to change your password.')
        self.playout = PasswordLayout(msg, fields, kind, state_change_fn, password_check_fn)
        self.setWindowTitle(self.playout.title() if title is None else title)

        vbox = QVBoxLayout(self)
        vbox.setSizeConstraint(QVBoxLayout.SetFixedSize)
        vbox.addLayout(self.playout.layout())
        vbox.addStretch(1)
        vbox.addLayout(Buttons(CancelButton(self), OK_button))
Beispiel #3
0
    def __setupUi(self):
        layout = QVBoxLayout()

        # Scene with the link editor.
        self.scene = LinksEditScene()
        self.view = QGraphicsView(self.scene)
        self.view.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        self.view.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        self.view.setRenderHint(QPainter.Antialiasing)

        self.scene.editWidget.geometryChanged.connect(self.__onGeometryChanged)

        # Ok/Cancel/Clear All buttons.
        buttons = QDialogButtonBox(
            QDialogButtonBox.Ok | QDialogButtonBox.Cancel
            | QDialogButtonBox.Reset, Qt.Horizontal)

        clear_button = buttons.button(QDialogButtonBox.Reset)
        clear_button.setText(self.tr("Clear All"))

        buttons.accepted.connect(self.accept)
        buttons.rejected.connect(self.reject)
        clear_button.clicked.connect(self.scene.editWidget.clearLinks)

        layout.addWidget(self.view)
        layout.addWidget(buttons)

        self.setLayout(layout)
        layout.setSizeConstraint(QVBoxLayout.SetFixedSize)

        self.setSizeGripEnabled(False)
Beispiel #4
0
    def __init__(self, parent, start, stop):
        super().__init__(parent)
        self.setWindowTitle("Crop data")
        vbox = QVBoxLayout(self)
        grid = QGridLayout()
        self.start_checkbox = QCheckBox("Start time:")
        self.start_checkbox.setChecked(True)
        self.start_checkbox.stateChanged.connect(self.toggle_start)
        grid.addWidget(self.start_checkbox, 0, 0)
        self._start = QDoubleSpinBox()
        self._start.setMaximum(999999)
        self._start.setValue(start)
        self._start.setDecimals(2)
        self._start.setSuffix(" s")
        grid.addWidget(self._start, 0, 1)

        self.stop_checkbox = QCheckBox("Stop time:")
        self.stop_checkbox.setChecked(True)
        self.stop_checkbox.stateChanged.connect(self.toggle_stop)
        grid.addWidget(self.stop_checkbox, 1, 0)
        self._stop = QDoubleSpinBox()
        self._stop.setMaximum(999999)
        self._stop.setValue(stop)
        self._stop.setDecimals(2)
        self._stop.setSuffix(" s")
        grid.addWidget(self._stop, 1, 1)
        vbox.addLayout(grid)
        buttonbox = QDialogButtonBox(QDialogButtonBox.Ok
                                     | QDialogButtonBox.Cancel)
        vbox.addWidget(buttonbox)
        buttonbox.accepted.connect(self.accept)
        buttonbox.rejected.connect(self.reject)
        vbox.setSizeConstraint(QVBoxLayout.SetFixedSize)
Beispiel #5
0
    def __init__(self):
        super().__init__()

        self.setWindowTitle('Simple Form')
        
        self.first_name = self._create_name_field()
        self.last_name = self._create_name_field()
        self.full_name = QLabel()
        self.error_message = self._create_error_field()

        fields = QFormLayout()
        fields.addRow('First Name', self.first_name)
        fields.addRow('Last Name', self.last_name)
        fields.addRow('Full Name', self.full_name)
        fields.addRow(None, self.error_message)

        self.send_button = self._create_button('Send', self.send)
        self.clear_button = self._create_button('Clear', self.reset_names)
        close_button = self._create_button('&Close', qApp.quit, is_enabled=True, is_default=True)

        buttons = QHBoxLayout()
        buttons.addStretch(1)
        buttons.addWidget(self.send_button)
        buttons.addWidget(self.clear_button)
        buttons.addWidget(close_button)

        vb = QVBoxLayout()
        vb.addLayout(fields)
        vb.addStretch(1)
        vb.addLayout(buttons)
        
        vb.setSizeConstraint(QLayout.SetFixedSize)
        self.setLayout(vb)    
    def __init__(self, parent: QWidget,
            msg: Optional[str]=None,
            title: Optional[str]=None,
            fields: Optional[LayoutFields]=None,
            kind: PasswordAction=PasswordAction.CHANGE,
            password_check_fn: Optional[PasswordCheckCallbackType]=None) -> None:
        WindowModalDialog.__init__(self, parent)

        ok_button = OkButton(self)
        # NOTE(rt12): I think the passphrase cases need to be updated to enable the button.
        ok_button.setEnabled(kind == PasswordAction.PASSPHRASE)
        self._ok_button = ok_button

        def state_change_fn(state: bool) -> None:
            nonlocal ok_button
            ok_button.setEnabled(state)

        if msg is None:
            if kind == PasswordAction.NEW:
                msg = _('Your wallet needs a password.')
                msg += ' ' + _('Use this dialog to set your password.')
            else:
                msg = _('Your wallet is password protected.')
                msg += ' ' + _('Use this dialog to change your password.')
        self.playout = PasswordLayout(msg, fields, kind, state_change_fn, password_check_fn)
        self.setWindowTitle(self.playout.title() if title is None else title)

        vbox = QVBoxLayout(self)
        vbox.setSizeConstraint(QVBoxLayout.SetFixedSize)
        vbox.addLayout(self.playout.layout())
        vbox.addStretch(1)
        vbox.addLayout(Buttons(CancelButton(self), ok_button))

        self.playout.new_pw.text_submitted_signal.connect(self._on_text_submitted)
        self.playout.conf_pw.text_submitted_signal.connect(self._on_text_submitted)
Beispiel #7
0
    def __setupUi(self):
        layout = QVBoxLayout()
        label = QLabel(self)

        pixmap, _ = config.splash_screen()

        label.setPixmap(pixmap)

        layout.addWidget(label, Qt.AlignCenter)

        name = QApplication.applicationName()
        version = QApplication.applicationVersion()

        text = ABOUT_TEMPLATE.format(
            name=escape(name),
            version=escape(version),
        )
        # TODO: Also list all known add-on versions??.
        text_label = QLabel(text)
        layout.addWidget(text_label, Qt.AlignCenter)

        buttons = QDialogButtonBox(
            QDialogButtonBox.Close, Qt.Horizontal, self)
        layout.addWidget(buttons)
        buttons.rejected.connect(self.accept)
        layout.setSizeConstraint(QVBoxLayout.SetFixedSize)
        self.setLayout(layout)
Beispiel #8
0
    def __init__(self, parent, limit):
        super().__init__(parent)
        self.setWindowModality(Qt.ApplicationModal)
        self.setWindowTitle('Parsing Replay')
        self.setMinimumSize(QSize(400, 75))
        self.setMaximumSize(QSize(400, 75))
        vlayout = QVBoxLayout(self)
        vlayout.setSizeConstraint(QLayout.SetMinAndMaxSize)

        self.pbar = QProgressBar(self)
        self.pbar.setRange(0, limit)
        self.pbar.setAlignment(Qt.AlignCenter)
        self.pbar.setFormat("Parsing Netstream %p%")
        self.pbar.setMinimumSize(QSize(380, 20))
        self.pbar.setMaximumSize(QSize(380, 20))
        size_policy = QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        self.pbar.setSizePolicy(size_policy)
        vlayout.addWidget(self.pbar)

        self.btn_cancel = QPushButton(self)
        self.btn_cancel.setSizePolicy(size_policy)
        self.btn_cancel.setMinimumSize(QSize(120, 23))
        self.btn_cancel.setMaximumSize(QSize(120, 23))
        self.btn_cancel.setText("MISSION ABORT!")
        size_policy = QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        self.btn_cancel.setSizePolicy(size_policy)
        vlayout.addWidget(self.btn_cancel)

        self.btn_cancel.clicked.connect(self.close)
    def __init__(self, text=''):
        super().__init__()
        self.pw = ButtonsLineEdit(text)
        self.pw.setMinimumWidth(220)
        self.reveal_button = self.pw.addButton(self.reveal_png, self.toggle_visible,
                                               _("Toggle visibility"))
        self.reveal_button.setFocusPolicy(Qt.NoFocus)
        keyboard_button = self.pw.addButton("keyboard.png", self.toggle_keyboard,
            _("Virtual keyboard"))
        keyboard_button.setFocusPolicy(Qt.NoFocus)
        self.pw.setEchoMode(QLineEdit.Password)
        # self.pw.setMinimumWidth(200)
        self.keyboard = VirtualKeyboard(self.pw)
        self.keyboard.setVisible(False)
        layout = QVBoxLayout()
        layout.setContentsMargins(0, 0, 0, 0)
        layout.setSpacing(0)
        layout.setSizeConstraint(QVBoxLayout.SetFixedSize)
        layout.addWidget(self.pw)
        layout.addWidget(self.keyboard)
        self.setLayout(layout)

        # Pass-throughs
        self.returnPressed = self.pw.returnPressed
        self.setFocus = self.pw.setFocus
        self.setMaxLength = self.pw.setMaxLength
        self.setPlaceholderText = self.pw.setPlaceholderText
        self.setText = self.pw.setText
        self.setValidator = self.pw.setValidator
        self.text = self.pw.text
        self.textChanged = self.pw.textChanged
        self.editingFinished = self.pw.editingFinished
        self.textEdited = self.pw.textEdited
Beispiel #10
0
class BoilTab(QTabWidget):
    def __init__(self, parent=None):
        super(BoilTab, self).__init__(parent)
        self.create_layout_boilTab()

    def create_layout_boilTab(self):

        self.graph = NewGraph()
        self.graph.createGraph()
        self.graph.setTitle("Boil Temperature")
        self.graph.setAxisTitles(f"Temperature ({DEGREES}C)", "Time (mins)")

        # V layout for input box inside widget to allow fixed width
        displayedWidget = QWidget()
        displayedWidget.setFixedWidth(150)
        self.boilVLayout = QVBoxLayout()
        self.boilVLayout.addStretch(1)
        self.boilVLayout.setSizeConstraint(5)
        displayedWidget.setLayout(self.boilVLayout)
        boilScrollArea = QScrollArea()
        boilScrollArea.setWidget(displayedWidget)
        boilScrollArea.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOn)

        # Main H layout for mash tab
        hLayout = QHBoxLayout()
        hLayout.addWidget(boilScrollArea)
        hLayout.addWidget(self.graph.plot, 1)
        self.setLayout(hLayout)
    def __init__(self, parent=None):
        super(ProjectTreeColumn, self).__init__(parent,
                                                Qt.WindowStaysOnTopHint)
        vbox = QVBoxLayout(self)
        vbox.setSizeConstraint(QVBoxLayout.SetDefaultConstraint)
        vbox.setContentsMargins(0, 0, 0, 0)
        self._buttons = []

        self._combo_project = QComboBox()
        self._combo_project.setMinimumHeight(30)
        self._combo_project.setContextMenuPolicy(Qt.CustomContextMenu)
        vbox.addWidget(self._combo_project)

        self._projects_area = QStackedLayout()
        logger.debug("This is the projects area")
        logger.debug(self._projects_area)
        vbox.addLayout(self._projects_area)

        self.projects = []

        self._combo_project.currentIndexChanged[int].connect(self._change_current_project)
        self._combo_project.customContextMenuRequested['const QPoint &'].connect(self.context_menu_for_root)
        connections = (
            {'target': 'main_container',
             'signal_name': 'addToProject',#(QString)
             'slot': self._add_file_to_project},
            {'target': 'main_container',
             'signal_name': 'showFileInExplorer',#(QString)
             'slot': self._show_file_in_explorer},
        )
        IDE.register_service('projects_explorer', self)
        IDE.register_signals('projects_explorer', connections)
        ExplorerContainer.register_tab(translations.TR_TAB_PROJECTS, self)
Beispiel #12
0
    def initUI(self):
        self.resize(400,300)
##        self.setSizePolicy(QSizePolicy.Fixed,
##                           QSizePolicy.Fixed
##        self.setSizePolicy(QSizePolicy.Maximum,
##                           QSizePolicy.Maximum
##                           )
##
        ## const
        base = QWidget(self)
##        base.setSizePolicy(QSizePolicy.Maximum,
##                           QSizePolicy.Maximum
##                           )

        scrollarea = QScrollArea(base)
        label = QLabel()
        scrollarea.setWidget(label)
        scrollarea.setWidgetResizable(True)
        scrollarea.setAlignment(Qt.AlignHCenter|Qt.AlignVCenter)
        label.setSizePolicy(QSizePolicy.Maximum,
                           QSizePolicy.MinimumExpanding
                           )
        label.setAlignment(Qt.AlignLeft|Qt.AlignTop)
        label.setWordWrap(True)
        self.scrollarea = scrollarea
        self.label = label

        label_buttons = QDialogButtonBox(parent=self)
        for i,s in enumerate(self.labels):
            btn = label_buttons.addButton(s, QDialogButtonBox.ActionRole)
            btn.setShortcut(QKeySequence(str(i+1)))
##            print(s)
##            dir(btn)
        label_buttons.clicked.connect(self.process)
##        print(label_buttons.buttons())

        cancelbutton = QPushButton("Cancel",parent=base)
####        startbutton = QPushButton("start", parent=base)
####        startbutton.setEnabled(False)
        self.cancelbutton = cancelbutton
####        startbutton.clicked.connect(self.step)
####        self.activate = lambda: startbutton.setEnabled(True)
        cancelbutton.clicked.connect(self.exit)
        self.end.connect(lambda: print("end"))

        ## arrange
        self.setCentralWidget(base)

        baseLO = QVBoxLayout(base)
        baseLO.setSizeConstraint(QLayout.SetMinimumSize)

        baseLO.addWidget(scrollarea)


        buttomLO = QHBoxLayout()
        buttomLO.addWidget(label_buttons)
        buttomLO.addStretch()
####        buttomLO.addWidget(startbutton)
        buttomLO.addWidget(cancelbutton)
        baseLO.addLayout(buttomLO)
Beispiel #13
0
    def __init__(self, size=15, parent=None):
        super().__init__(parent=parent)
        self.chessboard_data = np.zeros((size, size), dtype=np.int8)
        self.chessboard_panel = ChessBoard(self.chessboard_data)

        self.preset_btn = QPushButton('Preset')
        self.start_btn = QPushButton('Start')
        self.stop_btn = QPushButton('Stop')
        self.preset_btn.clicked.connect(self.preset)
        self.start_btn.clicked.connect(self.start)
        self.stop_btn.clicked.connect(self.stop)

        self.setWindowTitle('Gomoku Desktop')
        self.chessboard_panel.setEnabled(False)
        layout = QVBoxLayout()
        layout.addWidget(self.chessboard_panel)
        buttons_layout = QHBoxLayout()
        buttons_layout.addWidget(self.preset_btn)
        buttons_layout.addWidget(self.start_btn)
        buttons_layout.addWidget(self.stop_btn)
        layout.addLayout(buttons_layout)
        self.setLayout(layout)
        layout.setSizeConstraint(QLayout.SetFixedSize)

        self.preset_players = []
        self.players = {}
        self.current_color = Color.BLACK

        self._is_presetting = False
        self._is_playing = False
        self.preset_btn.setEnabled(True)
        self.start_btn.setEnabled(True)
        self.stop_btn.setEnabled(False)
    def __init__(self, columns: int = 2, parent=None):
        super().__init__(self.TITLE, parent=parent)

        self._bindings_color = styles.get("keybindings.bindings.color")
        self._highlight_color = styles.get("keybindings.highlight.color")
        self._labels: List[QLabel] = []
        self._search = QLineEdit()
        self._search_matches: Set[str] = set()
        self._description_label = QLabel()

        self._search.setPlaceholderText("search")

        layout = QVBoxLayout()
        layout.setSizeConstraint(QLayout.SetFixedSize)
        content_layout = QHBoxLayout()
        for _ in range(columns):
            label = QLabel()
            self._labels.append(label)
            content_layout.addWidget(label)
        layout.addLayout(content_layout)
        layout.addWidget(self._description_label)
        layout.addWidget(self._search)
        self.setLayout(layout)

        self._search.textChanged.connect(self._update_text)
        for mode in api.modes.ALL:
            mode.entered.connect(self._update_text)

        self._update_text()
        self._search.setFocus()
        self.show()
 def __init__(self, parent, wallet):
     WindowModalDialog.__init__(self, parent)
     is_encrypted = wallet.storage.is_encrypted()
     if not wallet.has_password():
         msg = _('Your wallet is not protected.')
         msg += ' ' + _('Use this dialog to add a password to your wallet.')
     else:
         if not is_encrypted:
             msg = _(
                 'Your bitcoins are password protected. However, your wallet file '
                 'is not encrypted.')
         else:
             msg = _('Your wallet is password protected and encrypted.')
         msg += ' ' + _('Use this dialog to change your password.')
     OK_button = OkButton(self)
     self.playout = PasswordLayout(wallet, msg, PW_CHANGE, OK_button)
     self.setWindowTitle(self.playout.title())
     self.setWindowIcon(read_QIcon("electrum-sv.png"))
     vbox = QVBoxLayout(self)
     vbox.setSizeConstraint(QVBoxLayout.SetFixedSize)
     vbox.addLayout(self.playout.layout())
     vbox.addStretch(1)
     vbox.addLayout(Buttons(CancelButton(self), OK_button))
     self.playout.encrypt_cb.setChecked(is_encrypted
                                        or not wallet.has_password())
Beispiel #16
0
    def initUi(self):
        topLayout = QHBoxLayout()
        label = QLabel("号码")
        edit = QLineEdit()
        hidbutton = QPushButton("展示")

        hidbutton.clicked.connect(self.showHidd)

        topLayout.addWidget(label)
        topLayout.addWidget(edit)
        topLayout.addWidget(hidbutton)
        topLayout.addStretch()

        self.setWindowTitle("打开网页")
        self.browser = QWebEngineView()
        self.browser.load(QUrl("http://www.baidu.com"))

        extension = QVBoxLayout()
        extension.addWidget(self.browser)
        self.ext = QWidget()
        self.ext.setLayout(extension)

        mainLayout = QVBoxLayout()
        mainLayout.addLayout(topLayout)
        mainLayout.addWidget(self.ext)

        self.setLayout(mainLayout)
        #固定大小
        mainLayout.setSizeConstraint(QLayout.SetFixedSize)
        self.ext.hide()
Beispiel #17
0
    def __init__(self, parent):
        super().__init__(parent)
        self.setFrameStyle(QFrame.StyledPanel)
        layout = QVBoxLayout(self)
        layout.setContentsMargins(2, 2, 2, 2)
        palette = self.palette()
        palette.setColor(QPalette.Window, QColor("#fff"))
        self.setPalette(palette)
        self.setWindowFlags(Qt.ToolTip)

        self.line = QFrame(self)
        self.line.setFrameShape(QFrame.HLine)
        self.line.setFrameShadow(QFrame.Sunken)

        self.title_label = QLabel()
        self.title_label.setMinimumWidth(300)
        self.title_label.setFont(parent.font())
        self.docstring_textedit = QTextEdit(self)
        self.docstring_textedit.setReadOnly(True)
        self.docstring_textedit.setFont(parent.font())

        palette = self.docstring_textedit.palette()
        palette.setColor(QPalette.WindowText, QColor("#888"))
        palette.setColor(QPalette.Text, QColor("#888"))
        self.docstring_textedit.setPalette(palette)
        self.docstring_textedit.setFrameShape(QFrame.NoFrame)
        self.docstring_textedit.document().setDocumentMargin(0)
        self.title_label.setPalette(palette)

        layout.setSpacing(2)
        layout.addWidget(self.title_label)
        layout.addWidget(self.line)
        layout.addWidget(self.docstring_textedit)
        layout.setSizeConstraint(QVBoxLayout.SetFixedSize)
Beispiel #18
0
Datei: taf.py Projekt: jpli/tafor
    def initUI(self):
        window = QWidget(self)
        layout = QVBoxLayout(window)
        layout.setSizeConstraint(QLayout.SetFixedSize)
        self.primary = TafPrimarySegment()
        self.becmg1, self.becmg2, self.becmg3 = TafBecmgSegment('BECMG1'), TafBecmgSegment('BECMG2'), TafBecmgSegment('BECMG3')
        self.tempo1, self.tempo2 = TafTempoSegment('TEMPO1'), TafTempoSegment('TEMPO2')
        self.nextButton = QPushButton()
        self.nextButton.setEnabled(False)
        self.nextButton.setText(QCoreApplication.translate('Editor', 'Next'))
        layout.addWidget(self.primary)
        layout.addWidget(self.becmg1)
        layout.addWidget(self.becmg2)
        layout.addWidget(self.becmg3)
        layout.addWidget(self.tempo1)
        layout.addWidget(self.tempo2)
        layout.addWidget(self.nextButton, 0, Qt.AlignRight|Qt.AlignBottom)
        self.setLayout(layout)

        self.setStyleSheet('QLineEdit {width: 50px;} QComboBox {width: 50px}')

        self.becmg1.hide()
        self.becmg2.hide()
        self.becmg3.hide()
        self.tempo1.hide()
        self.tempo2.hide()
Beispiel #19
0
class ListWidget(QScrollArea):
   def __init__(self, clearMouseOver, parent = None):
      QScrollArea.__init__(self, parent)
      self.clearMouseOver = clearMouseOver
      self.mouseOver = False
      
      self.widget = QWidget() # Just adding the layout directly doesn't work right, so wrap it in a QWidget
      self.setWidget(self.widget)
      self.setWidgetResizable(True)
      self.setMouseTracking(True)
      self.createLayout()
      
      
   def createLayout(self):
      self.layout = QVBoxLayout(self.widget)
      self.layout.setSpacing(0)
      self.layout.setContentsMargins(0, 0, 0, 0)
      self.layout.setSizeConstraint(QLayout.SetMinimumSize)

      
   def add(self, item):
      self.layout.addWidget(item)
      
   def clear(self):
      QWidget().setLayout(self.layout)
      self.createLayout()
      
   
   def mousePressEvent(self, event):
      if event.button() == Qt.RightButton:
         self.clearMouseOver()
         self.mouseOver = True
      QScrollArea.mousePressEvent(self, event)
Beispiel #20
0
    def __init__(self, windowsManager, parent=None):
        super().__init__(parent)
        self.windowsManager = windowsManager

        aGroup = QGroupBox("알림 발행 토픽")
        aBox = QHBoxLayout()
        self.topicSettingText = self.windowsManager.qTextWidgetSetter(
            QLineEdit(), "", False)
        aBox.addWidget(self.topicSettingText)
        aGroup.setLayout(aBox)

        cGroup = QGroupBox("푸시 알림 간격")
        cBox = QHBoxLayout()
        self.pushIntervalStart = QLineEdit()
        cBox.addWidget(self.pushIntervalStart)
        cBox.addWidget(QLabel("분 부터 "))
        self.pushIntervalEnd = QLineEdit()
        cBox.addWidget(self.pushIntervalEnd)
        cBox.addWidget(QLabel("분 사이"))
        cGroup.setLayout(cBox)

        # 메인 레이아웃 세팅
        mainLayout = QVBoxLayout()
        mainLayout.setSizeConstraint(QLayout.SetFixedSize)
        mainLayout.addWidget(aGroup)
        mainLayout.addWidget(cGroup)

        bt = self.windowsManager.qButtonMaker(
            "설정 저장", self.buttonClicked, (-1, 50),
            (QSizePolicy.Expanding, QSizePolicy.Expanding))
        mainLayout.addWidget(bt)

        self.setLayout(mainLayout)
        self.setWindowTitle('Memorize Words')
Beispiel #21
0
class VarPositionalParser(QScrollArea):
    def __init__(self, loadSaved=False):
        super().__init__()
        self.arg_list = []
        self.mainWidget = QWidget()

        self.layout = QVBoxLayout(self.mainWidget)

        self.layout.setSizeConstraint(QLayout.SetFixedSize)
        self.argName = QLabel('args*')

        self.button_line = QWidget()
        self.button_line_layout = QHBoxLayout(self.button_line)

        self.addButton = QPushButton()
        self.addButton.setIcon(self.style().standardIcon(QStyle.SP_ArrowDown))

        self.removeButton = QPushButton()
        self.removeButton.setIcon(self.style().standardIcon(QStyle.SP_ArrowUp))

        self.button_line_layout.addWidget(self.addButton)
        self.button_line_layout.addWidget(self.removeButton)

        self.layout.addWidget(self.argName)
        self.layout.addWidget(self.button_line)
        # BAUSTELLE
        # wird durch edit->methodChanged->updateParams und edit->updateParams aufgerufen()

        self.addButton.clicked.connect(self.addArgument)
        self.removeButton.clicked.connect(self.removeArgument)

        #self.setLayout(self.layout)
        self.setWidget(self.mainWidget)
        self.setWidgetResizable(True)

    def addArgument(self, argName=None, argValue=None):

        argument = VarArg()

        if argName:
            argument.s_arg_name = argName

        if argValue:
            argument.s_arg_val = argValue

        # this is called when loading saved arguments
        if argName or argValue:
            argument.setText()

        self.layout.insertWidget(self.layout.count() - 1, argument)
        self.arg_list.append(argument)

    def removeArgument(self):

        #self.layout.removeWidget(self.lastAddedArgument)
        if self.arg_list:
            lastAddedArgument = self.arg_list[-1]
            lastAddedArgument.deleteLater()
            lastAddedArgument = None
            del self.arg_list[-1]
Beispiel #22
0
    def __init__(self, parent=None):
        super(ProjectTreeColumn, self).__init__(parent,
                                                Qt.WindowStaysOnTopHint)
        vbox = QVBoxLayout(self)
        vbox.setSizeConstraint(QVBoxLayout.SetDefaultConstraint)
        vbox.setContentsMargins(0, 0, 0, 0)
        self._buttons = []

        self._combo_project = QComboBox()
        self._combo_project.setMinimumHeight(30)
        self._combo_project.setContextMenuPolicy(Qt.CustomContextMenu)
        vbox.addWidget(self._combo_project)

        self._projects_area = QStackedLayout()
        logger.debug("This is the projects area")
        logger.debug(self._projects_area)
        vbox.addLayout(self._projects_area)

        self.projects = []

        self._combo_project.currentIndexChanged[int].connect(self._change_current_project)
        self._combo_project.customContextMenuRequested['const QPoint &'].connect(self.context_menu_for_root)
        connections = (
            {'target': 'main_container',
             'signal_name': 'addToProject',#(QString)
             'slot': self._add_file_to_project},
            {'target': 'main_container',
             'signal_name': 'showFileInExplorer',#(QString)
             'slot': self._show_file_in_explorer},
        )
        IDE.register_service('projects_explorer', self)
        IDE.register_signals('projects_explorer', connections)
        ExplorerContainer.register_tab(translations.TR_TAB_PROJECTS, self)
Beispiel #23
0
 def initUI(self):
     if not self.parentWidget(): self.resize(400, 300)
     ##        self.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
     self.setFrameShape(QFrame.NoFrame)
     # construct and set
     base = QWidget(self, objectName="base")
     self.base = base
     self.setWidgetResizable(True)
     ##        base.setMinimumWidth(280)
     base.setSizePolicy(
         QSizePolicy(QSizePolicy.Maximum, QSizePolicy.MinimumExpanding))
     margin = QVBoxLayout(base, objectName="margin")
     margin.setSizeConstraint(QLayout.SetMaximumSize)
     scroll_layout = QVBoxLayout(objectName="scroll")
     self.scroll_layout = scroll_layout
     base.setLayout(margin)
     margin.addLayout(scroll_layout)
     scroll_layout.setSizeConstraint(QLayout.SetMaximumSize)
     margin.addStretch(20)
     # set
     self.setWidget(base)
     # set trigger
     vSB = self.verticalScrollBar()
     vSB.setObjectName("vSB")
     self.vSB = vSB
     vSB.rangeChanged.connect(self.scroll_to_bottom)
Beispiel #24
0
    def __init__(self, parent=None, aw=None):
        super(SamplingDlg, self).__init__(parent, aw)
        self.setWindowTitle(QApplication.translate("Message", "Sampling",
                                                   None))
        self.setModal(True)

        self.org_delay = self.aw.qmc.delay
        self.org_flagKeepON = self.aw.qmc.flagKeepON
        self.org_flagOpenCompleted = self.aw.qmc.flagOpenCompleted

        self.keepOnFlag = QCheckBox(
            QApplication.translate("Label", "Keep ON", None))
        self.keepOnFlag.setFocusPolicy(Qt.NoFocus)
        self.keepOnFlag.setChecked(bool(self.aw.qmc.flagKeepON))

        self.openCompletedFlag = QCheckBox(
            QApplication.translate("Label", "Open Completed Roast in Viewer",
                                   None))
        self.openCompletedFlag.setFocusPolicy(Qt.NoFocus)
        self.openCompletedFlag.setChecked(bool(self.aw.qmc.flagOpenCompleted))

        self.interval = QDoubleSpinBox()
        self.interval.setSingleStep(1)
        self.interval.setValue(self.aw.qmc.delay / 1000.)
        self.interval.setRange(self.aw.qmc.min_delay / 1000., 40.)
        self.interval.setDecimals(1)
        self.interval.setAlignment(Qt.AlignRight)
        self.interval.setSuffix("s")

        intervalLayout = QHBoxLayout()
        intervalLayout.addStretch()
        intervalLayout.addWidget(self.interval)
        intervalLayout.addStretch()

        # connect the ArtisanDialog standard OK/Cancel buttons
        self.dialogbuttons.accepted.connect(self.ok)
        self.dialogbuttons.rejected.connect(self.close)

        flagGrid = QGridLayout()
        flagGrid.addWidget(self.keepOnFlag, 0, 0)
        flagGrid.addWidget(self.openCompletedFlag, 1, 0)

        flagLayout = QHBoxLayout()
        flagLayout.addStretch()
        flagLayout.addLayout(flagGrid)
        flagLayout.addStretch()
        buttonsLayout = QHBoxLayout()
        buttonsLayout.addStretch()
        buttonsLayout.addWidget(self.dialogbuttons)

        #incorporate layouts
        layout = QVBoxLayout()
        layout.addLayout(intervalLayout)
        layout.addLayout(flagLayout)
        layout.addStretch()
        layout.addLayout(buttonsLayout)
        layout.setSizeConstraint(QLayout.SetFixedSize)
        self.setLayout(layout)
        self.dialogbuttons.button(QDialogButtonBox.Ok).setFocus()
Beispiel #25
0
    def __createFilesLayout(self):
        layout = QVBoxLayout()
        layout.setSizeConstraint(QLayout.SetMinAndMaxSize)
        layout.setContentsMargins(5, 5, 5, 5)
        layout.setAlignment(Qt.AlignHCenter)
        layout.addStretch(1)

        return layout
Beispiel #26
0
    def __init__(self, parent=None, msg: Optional[str]=None, force_keyboard: bool=False,
            password_check_fn: PasswordCheckCallbackType=None,
            fields: Optional[LayoutFields]=None,
            title: Optional[str]=None) -> None:
        super().__init__(parent, title or _("Enter Password"))

        self.pw = pw = PasswordLineEdit()
        self._ok_button = OkButton(self)

        about_label = QLabel((msg or PASSWORD_REQUEST_TEXT) +"\n")
        about_label.setWordWrap(True)

        logo_grid = QGridLayout()
        logo_grid.setSpacing(8)
        logo_grid.setColumnMinimumWidth(0, 70)
        logo_grid.setColumnStretch(1,1)

        logo = QLabel()
        logo.setAlignment(Qt.AlignCenter)
        lockfile = "lock.png"
        logo.setPixmap(QPixmap(icon_path(lockfile)).scaledToWidth(36))

        logo_grid.addWidget(logo,  0, 0)
        logo_grid.addWidget(about_label, 0, 1, 1, 2)

        grid = QGridLayout()
        grid.setSpacing(8)
        grid.setColumnStretch(1,1)
        row = 0

        if fields is not None:
            for field_label, field_widget in fields:
                field_label.setAlignment(Qt.AlignTop)
                grid.addWidget(field_label, row, 0, Qt.AlignRight | Qt.AlignVCenter)
                grid.addWidget(field_widget, row, 1, Qt.AlignLeft)
                row += 1

        pwlabel = QLabel(_('Password') +":")
        pwlabel.setAlignment(Qt.AlignTop)
        grid.addWidget(pwlabel, row, 0, Qt.AlignRight | Qt.AlignVCenter)
        grid.addWidget(pw, row, 1, Qt.AlignLeft)
        row += 1

        vbox = QVBoxLayout()
        vbox.addLayout(logo_grid)
        vbox.addLayout(grid)
        vbox.addStretch(1)
        vbox.addLayout(Buttons(CancelButton(self), self._ok_button), Qt.AlignBottom)
        vbox.setSizeConstraint(QVBoxLayout.SetFixedSize)
        self.setLayout(vbox)

        self.pw.text_submitted_signal.connect(self._on_text_submitted)

        # Real-time password validation and OK button disabling/enabling.
        self._password_check_fn = password_check_fn
        if password_check_fn is not None:
            self._ok_button.setEnabled(False)
            self.pw.textChanged.connect(self._on_text_changed)
Beispiel #27
0
    def __init__(self, *args):
        QDialog.__init__(self, *args)
        self.setWindowTitle(_('Settings'))

        self.fsuae_command_edit = self.__lineedit()
        self.fsuae_documents_dir_edit = self.__lineedit()
        self.fsuae_rp9_dir_edit = self.__lineedit()
        self.temp_dir_edit = self.__lineedit()
        self.workbench_135_hd_edit = self.__lineedit()
        self.workbench_211_hd_edit = self.__lineedit()
        self.workbench_311_hd_edit = self.__lineedit()

        dlglyt = QVBoxLayout()
        dlglyt.setSizeConstraint(QLayout.SetFixedSize)
        self.setLayout(dlglyt)

        grid = QGridLayout()
        dlglyt.addLayout(grid)
        grid.setSpacing(10)

        grid.addWidget(self.__label(_('FS-UAE command:')), 0, 0)
        grid.addWidget(self.fsuae_command_edit, 0, 1)
        grid.addWidget(self.__dirbutton(self.fsuae_command_edit, False), 0, 2)

        grid.addWidget(self.__label(_('FS-UAE documents directory:')), 1, 0)
        grid.addWidget(self.fsuae_documents_dir_edit, 1, 1)
        grid.addWidget(self.__dirbutton(self.fsuae_documents_dir_edit, True),
                       1, 2)

        grid.addWidget(self.__label(_('RP9 extraction directory:')), 2, 0)
        grid.addWidget(self.fsuae_rp9_dir_edit, 2, 1)
        grid.addWidget(self.__dirbutton(self.fsuae_rp9_dir_edit, True), 2, 2)

        grid.addWidget(self.__label(_('Temp directory:')), 3, 0)
        grid.addWidget(self.temp_dir_edit, 3, 1)
        grid.addWidget(self.__dirbutton(self.temp_dir_edit, True), 3, 2)

        grid.addWidget(self.__label(_('Workbench-135 harddisk:')), 4, 0)
        grid.addWidget(self.workbench_135_hd_edit, 4, 1)
        grid.addWidget(self.__dirbutton(self.workbench_135_hd_edit, False), 4,
                       2)

        grid.addWidget(self.__label(_('Workbench-211 harddisk:')), 5, 0)
        grid.addWidget(self.workbench_211_hd_edit, 5, 1)
        grid.addWidget(self.__dirbutton(self.workbench_211_hd_edit, False), 5,
                       2)

        grid.addWidget(self.__label(_('Workbench-311 harddisk:')), 6, 0)
        grid.addWidget(self.workbench_311_hd_edit, 6, 1)
        grid.addWidget(self.__dirbutton(self.workbench_311_hd_edit, False), 6,
                       2)

        dlglyt.addSpacing(10)
        button_box = QDialogButtonBox(QDialogButtonBox.Ok
                                      | QDialogButtonBox.Cancel)
        button_box.accepted.connect(self.accept)
        button_box.rejected.connect(self.reject)
        dlglyt.addWidget(button_box)
Beispiel #28
0
    def initUI(self):
        self.resize(400, 300)
        ##        self.setSizePolicy(QSizePolicy.Fixed,
        ##                           QSizePolicy.Fixed
        ##        self.setSizePolicy(QSizePolicy.Maximum,
        ##                           QSizePolicy.Maximum
        ##                           )
        ##
        ## const
        base = QWidget(self)
        ##        base.setSizePolicy(QSizePolicy.Maximum,
        ##                           QSizePolicy.Maximum
        ##                           )

        fig = plt.Figure(dpi=200)
        canvas = FigureCanvas(fig)
        canvas.setParent(base)
        ax = fig.add_subplot(1, 1, 1)
        self.figure = fig
        self.canvas = canvas
        self.ax = ax
        ax.axis("off")

        label_buttons = QDialogButtonBox(parent=self)
        for i, s in enumerate(self.labels):
            btn = label_buttons.addButton(s, QDialogButtonBox.ActionRole)
            btn.setShortcut(QKeySequence(str(i + 1)))


##            print(s)
##            dir(btn)
        label_buttons.clicked.connect(self.process)
        ##        print(label_buttons.buttons())

        cancelbutton = QPushButton("Cancel", parent=base)
        ####        startbutton = QPushButton("start", parent=base)
        ####        startbutton.setEnabled(False)
        self.cancelbutton = cancelbutton
        ####        startbutton.clicked.connect(self.step)
        ####        self.activate = lambda: startbutton.setEnabled(True)
        cancelbutton.clicked.connect(self.exit)
        self.end.connect(lambda: print("end"))

        ## arrange
        self.setCentralWidget(base)

        baseLO = QVBoxLayout(base)
        baseLO.setSizeConstraint(QLayout.SetMinimumSize)

        baseLO.addWidget(canvas)

        buttomLO = QHBoxLayout()
        buttomLO.addWidget(label_buttons)
        buttomLO.addStretch()
        ####        buttomLO.addWidget(startbutton)
        buttomLO.addWidget(cancelbutton)
        baseLO.addLayout(buttomLO)
    def __init__(self, parent=None):
        super(ProjectTreeColumn, self).__init__(parent)
        vbox = QVBoxLayout(self)
        vbox.setSizeConstraint(QVBoxLayout.SetDefaultConstraint)
        vbox.setContentsMargins(0, 0, 0, 0)
        vbox.setSpacing(0)
        self._buttons = []
        frame = QFrame()
        frame.setObjectName("actionbar")
        box = QVBoxLayout(frame)
        box.setContentsMargins(1, 1, 1, 1)
        box.setSpacing(0)

        self._combo_project = QComboBox()
        self._combo_project.setSizePolicy(
            QSizePolicy.Expanding, QSizePolicy.Fixed)
        self._combo_project.setSizeAdjustPolicy(
            QComboBox.AdjustToMinimumContentsLengthWithIcon)
        self._combo_project.setObjectName("combo_projects")
        box.addWidget(self._combo_project)
        vbox.addWidget(frame)
        self._combo_project.setContextMenuPolicy(Qt.CustomContextMenu)
        self._projects_area = QStackedLayout()
        logger.debug("This is the projects area")
        vbox.addLayout(self._projects_area)

        # Empty widget
        self._empty_proj = QLabel(translations.TR_NO_PROJECTS)
        self._empty_proj.setAlignment(Qt.AlignCenter)
        self._empty_proj.setAutoFillBackground(True)
        self._empty_proj.setBackgroundRole(QPalette.Base)
        self._projects_area.addWidget(self._empty_proj)
        self._projects_area.setCurrentWidget(self._empty_proj)

        self.projects = []

        self._combo_project.activated.connect(
            self._change_current_project)
        self._combo_project.customContextMenuRequested[
            'const QPoint&'].connect(self.context_menu_for_root)

        connections = (
            {
                "target": "main_container",
                "signal_name": "addToProject",
                "slot": self._add_file_to_project
            },
            {
                "target": "main_container",
                "signal_name": "showFileInExplorer",
                "slot": self._show_file_in_explorer
            },
        )
        IDE.register_service('projects_explorer', self)
        IDE.register_signals('projects_explorer', connections)
        ExplorerContainer.register_tab(translations.TR_TAB_PROJECTS, self)
Beispiel #30
0
class GUIEvaluation(QWidget):
    finished = pyqtSignal()

    def __init__(self, analysis, eval_window):
        super(GUIEvaluation, self).__init__()
        self.eval_window = eval_window

        self.analysis = analysis
        self.evaluation = Evaluation(self.analysis)
        thread = threading.Thread(target=self.evaluation.execute, args=())
        thread.start()
        self.layout = QVBoxLayout(self)
        self.layout.setSizeConstraint(QLayout.SetNoConstraint)
        self.layout.setContentsMargins(0, 0, 0, 0)

        self.view = EvaluationView(self, parent=self)
        self.layout.addWidget(self.view)

        self.view.scene.update_states()
        temp = self.evaluation.final_task

        self.navigation = EvaluationNavigation(self)
        self.navigation.add_item(self.evaluation.final_task,
                                 self.analysis.name)

        self.navigation_dock = eval_window.navigation_dock

        timer = QTimer()
        timer.start(0.25)
        timer.timeout.connect(self.view.scene.update_states)

        self.view.scene.update_states()
        while thread.is_alive():
            QApplication.processEvents()

    def run(self):
        self.eval = Evaluation(self.analysis)
        self.result = self.evaluation.execute()

    def double_click(self, g_action):
        task = self.navigation.current_task().childs[g_action.name]
        if type(task) is Atomic:
            return

        self.navigation.add_item(task, g_action.name)

        self.change_view(task)

        if not self.navigation_dock.isVisible():
            self.navigation_dock.show()

    def change_view(self, task):
        self.layout.removeWidget(self.view)
        self.view = EvaluationView(self, task)
        self.layout.addWidget(self.view)
        self.eval_window.data_editor.clear()
    def __init__(self, parent=None):
        super(ProjectTreeColumn, self).__init__(parent)
        vbox = QVBoxLayout(self)
        vbox.setSizeConstraint(QVBoxLayout.SetDefaultConstraint)
        vbox.setContentsMargins(0, 0, 0, 0)
        vbox.setSpacing(0)
        self._buttons = []
        frame = QFrame()
        frame.setObjectName("actionbar")
        box = QVBoxLayout(frame)
        box.setContentsMargins(1, 1, 1, 1)
        box.setSpacing(0)

        self._combo_project = QComboBox()
        self._combo_project.setSizePolicy(QSizePolicy.Expanding,
                                          QSizePolicy.Fixed)
        self._combo_project.setSizeAdjustPolicy(
            QComboBox.AdjustToMinimumContentsLengthWithIcon)
        self._combo_project.setObjectName("combo_projects")
        box.addWidget(self._combo_project)
        vbox.addWidget(frame)
        self._combo_project.setContextMenuPolicy(Qt.CustomContextMenu)
        self._projects_area = QStackedLayout()
        logger.debug("This is the projects area")
        vbox.addLayout(self._projects_area)

        # Empty widget
        self._empty_proj = QLabel(translations.TR_NO_PROJECTS)
        self._empty_proj.setAlignment(Qt.AlignCenter)
        self._empty_proj.setAutoFillBackground(True)
        self._empty_proj.setBackgroundRole(QPalette.Base)
        self._projects_area.addWidget(self._empty_proj)
        self._projects_area.setCurrentWidget(self._empty_proj)

        self.projects = []

        self._combo_project.currentIndexChanged.connect(
            self._change_current_project)
        self._combo_project.customContextMenuRequested[
            'const QPoint&'].connect(self.context_menu_for_root)

        connections = (
            {
                "target": "main_container",
                "signal_name": "addToProject",
                "slot": self._add_file_to_project
            },
            {
                "target": "main_container",
                "signal_name": "showFileInExplorer",
                "slot": self._show_file_in_explorer
            },
        )
        IDE.register_service('projects_explorer', self)
        IDE.register_signals('projects_explorer', connections)
        ExplorerContainer.register_tab(translations.TR_TAB_PROJECTS, self)
Beispiel #32
0
 def initAboutTabUI(self):
     layout = QVBoxLayout()
     layout.setSizeConstraint(QLayout.SetMinimumSize)
     self.aboutTab.setLayout(layout)
     aboutTabText = QLabel(aboutInfo)
     aboutTabText.setSizePolicy(QSizePolicy.Expanding,
                                QSizePolicy.Expanding)
     aboutTabText.setWordWrap(True)
     layout.addWidget(aboutTabText)
     layout.setAlignment(Qt.AlignCenter)
    def setupUi(self):

        self.lb0 = QLabel("Receiver(s) comma(,) separated:", self)
        self.le1 = QLineEdit()
        self.le1.setText(', '.join([i for i in self.emailrec_str]))
        self.le1.textChanged.connect(self.on_text_changed)

        self.btnSave = QPushButton("Receivers saved", self)
        self.btnSave.clicked.connect(self.btn_save)
        self.btnSave.setEnabled(False)

        self.btnSend = QPushButton("Send e-mail", self)
        self.btnSend.clicked.connect(self.btn_send_email)
        self.btnSend.setEnabled(False)

        self.btnBrowse = QPushButton("Pick files", self)
        self.btnBrowse.clicked.connect(self.btn_browse_files)

        self.btnZip = QPushButton("Zip folder", self)
        self.btnZip.clicked.connect(self.zip_folder)

        self.btnClear = QPushButton("Clear list", self)
        self.btnClear.clicked.connect(self.btn_clear_list)
        self.btnClear.setEnabled(False)

        self.threadpool = QThreadPool()

        # set layout
        grid_0 = QGridLayout()
        grid_0.addWidget(self.lb0, 0, 0)
        grid_0.addWidget(self.le1, 1, 0)
        grid_0.addWidget(self.btnSave, 2, 0)

        grid_1 = QGridLayout()
        grid_1.addWidget(self.btnSend, 0, 0)
        grid_1.addWidget(self.btnBrowse, 0, 1)
        grid_1.addWidget(self.btnZip, 0, 2)
        grid_1.addWidget(self.btnClear, 0, 3)

        grid_2 = QGridLayout()
        self.lb1 = QLabel("No files selected!", self)
        grid_2.addWidget(self.lb1, 0, 0)

        v0 = QVBoxLayout()
        v0.addLayout(grid_0)
        v0.addLayout(grid_1)
        v0.addLayout(grid_2)

        self.setLayout(v0)
        self.setWindowTitle("E-mail data")

        # re-adjust/minimize the size of the e-mail dialog
        # depending on the number of attachments
        v0.setSizeConstraint(v0.SetFixedSize)
Beispiel #34
0
    def __init__(self, parent, nchan, have_picard=True, have_sklearn=True):
        super().__init__(parent)
        self.setWindowTitle("Run ICA")
        vbox = QVBoxLayout(self)
        grid = QGridLayout()
        grid.addWidget(QLabel("Method:"), 0, 0)
        self.method = QComboBox()
        self.methods = {"Infomax": "infomax"}
        if have_sklearn:
            self.methods["FastICA"] = "fastica"
        if have_picard:
            self.methods["Picard"] = "picard"
        self.method.addItems(self.methods.keys())
        if have_picard:
            self.method.setCurrentText("Picard")
        else:
            self.method.setCurrentText("Infomax")
        min_len = max(len(key) for key in self.methods.keys())
        self.method.setMinimumContentsLength(min_len)
        grid.addWidget(self.method, 0, 1)

        self.extended_label = QLabel("Extended:")
        grid.addWidget(self.extended_label, 1, 0)
        self.extended = QCheckBox()
        self.extended.setChecked(True)
        grid.addWidget(self.extended, 1, 1)

        self.ortho_label = QLabel("Orthogonal:")
        grid.addWidget(self.ortho_label, 2, 0)
        self.ortho = QCheckBox()
        self.ortho.setChecked(False)
        grid.addWidget(self.ortho, 2, 1)

        self.toggle_options()
        self.method.currentIndexChanged.connect(self.toggle_options)

        grid.addWidget(QLabel("Number of components:"), 3, 0)
        self.n_components = QSpinBox()
        self.n_components.setMinimum(0)
        self.n_components.setMaximum(nchan)
        self.n_components.setValue(nchan)
        self.n_components.setAlignment(Qt.AlignRight)
        grid.addWidget(self.n_components, 3, 1)
        grid.addWidget(QLabel("Exclude bad segments:"), 4, 0)
        self.exclude_bad_segments = QCheckBox()
        self.exclude_bad_segments.setChecked(True)
        grid.addWidget(self.exclude_bad_segments)
        vbox.addLayout(grid)
        buttonbox = QDialogButtonBox(QDialogButtonBox.Ok |
                                     QDialogButtonBox.Cancel)
        vbox.addWidget(buttonbox)
        buttonbox.accepted.connect(self.accept)
        buttonbox.rejected.connect(self.reject)
        vbox.setSizeConstraint(QVBoxLayout.SetFixedSize)
Beispiel #35
0
class QScrollableBox(QWidget):
    def __init__(self, parent):
        super(QScrollableBox, self).__init__(parent)
        mainLayout = QVBoxLayout()
        mainLayout.setContentsMargins(0, 0, 0, 0)
        self.scrollArea = QScrollArea(self)
        sizePolicy = QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        self.scrollArea.setSizePolicy(sizePolicy)
        self.scrollArea.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        self.scrollArea.setVerticalScrollBarPolicy(Qt.ScrollBarAsNeeded)
        self.scrollArea.setWidgetResizable(True)

        mainLayout.addWidget(self.scrollArea)
        self.setLayout(mainLayout)
        scrollContents = QWidget()
        self.m_layout = QVBoxLayout()
        self.m_layout.setContentsMargins(0, 0, 0, 0)
        self.m_layout.setSizeConstraint(QLayout.SetNoConstraint)
        scrollContents.setLayout(self.m_layout)

        self.scrollArea.setWidget(scrollContents)

    def addWidget(self, w):
        if not w:
            return
        count = self.m_layout.count()
        if count > 1:
            self.m_layout.removeItem(self.m_layout.itemAt(count - 1))
        self.m_layout.addWidget(w)
        w.show()
        self.m_layout.addStretch()
        self.scrollArea.update()

    def removeWidget(self, w):
        self.m_layout.removeWidget(w)
        self.scrollArea.update()

    def insertWidget(self, i, w):
        self.m_layout.insertWidget(i, w)
        self.scrollArea.update()

    def clearWidgets(self):
        item = self.m_layout.takeAt(0)
        while item != None:
            item.widget().deleteLater()
            self.m_layout.removeItem(item)
            del item

        self.scrollArea.update()

    def indexOf(self, w):
        return self.m_layout.indexOf(w)
Beispiel #36
0
    def __init__(self, mainwindow):
        """Creates the about dialog. You can simply exec_() it."""
        super(AboutDialog, self).__init__(mainwindow)

        self.setWindowTitle(_("About {appname}").format(appname = appinfo.appname))
        layout = QVBoxLayout()
        self.setLayout(layout)

        tabw = QTabWidget()
        layout.addWidget(tabw)

        tabw.addTab(About(self), _("About"))
        tabw.addTab(Credits(self), _("Credits"))
        tabw.addTab(Version(self), _("Version"))

        button = QDialogButtonBox(QDialogButtonBox.Ok)
        button.setCenterButtons(True)
        button.accepted.connect(self.accept)
        layout.addWidget(button)
        layout.setSizeConstraint(QLayout.SetFixedSize)
Beispiel #37
0
def run_iface_config_window(icon):
    win = QDialog()
    win.setWindowTitle('CAN Interface Configuration')
    win.setWindowIcon(icon)
    win.setWindowFlags(Qt.CustomizeWindowHint | Qt.WindowTitleHint | Qt.WindowCloseButtonHint)
    win.setAttribute(Qt.WA_DeleteOnClose)              # This is required to stop background timers!

    combo = QComboBox(win)
    combo.setEditable(True)
    combo.setInsertPolicy(QComboBox.NoInsert)
    combo.setSizeAdjustPolicy(QComboBox.AdjustToContents)
    combo.setFont(get_monospace_font())

    combo_completer = QCompleter()
    combo_completer.setCaseSensitivity(Qt.CaseSensitive)
    combo_completer.setModel(combo.model())
    combo.setCompleter(combo_completer)

    bitrate = QSpinBox(win)
    bitrate.setMaximum(1000000)
    bitrate.setMinimum(10000)
    bitrate.setValue(1000000)

    baudrate = QComboBox(win)
    baudrate.setEditable(True)
    baudrate.setInsertPolicy(QComboBox.NoInsert)
    baudrate.setSizeAdjustPolicy(QComboBox.AdjustToContents)
    baudrate.setFont(get_monospace_font())

    baudrate_completer = QCompleter(win)
    baudrate_completer.setModel(baudrate.model())
    baudrate.setCompleter(baudrate_completer)

    baudrate.setValidator(QIntValidator(min(STANDARD_BAUD_RATES), max(STANDARD_BAUD_RATES)))
    baudrate.insertItems(0, map(str, STANDARD_BAUD_RATES))
    baudrate.setCurrentText(str(DEFAULT_BAUD_RATE))

    ok = QPushButton('OK', win)

    def update_slcan_options_visibility():
        if RUNNING_ON_LINUX:
            slcan_active = '/' in combo.currentText()
        else:
            slcan_active = True
        slcan_group.setEnabled(slcan_active)

    combo.currentTextChanged.connect(update_slcan_options_visibility)

    ifaces = None

    def update_iface_list():
        nonlocal ifaces
        ifaces = iface_lister.get_list()
        known_keys = set()
        remove_indices = []
        was_empty = combo.count() == 0
        # Marking known and scheduling for removal
        for idx in count():
            tx = combo.itemText(idx)
            if not tx:
                break
            known_keys.add(tx)
            if tx not in ifaces:
                logger.debug('Removing iface %r', tx)
                remove_indices.append(idx)
        # Removing - starting from the last item in order to retain indexes
        for idx in remove_indices[::-1]:
            combo.removeItem(idx)
        # Adding new items - starting from the last item in order to retain the final order
        for key in list(ifaces.keys())[::-1]:
            if key not in known_keys:
                logger.debug('Adding iface %r', key)
                combo.insertItem(0, key)
        # Updating selection
        if was_empty:
            combo.setCurrentIndex(0)

    result = None
    kwargs = {}

    def on_ok():
        nonlocal result, kwargs
        try:
            baud_rate_value = int(baudrate.currentText())
        except ValueError:
            show_error('Invalid parameters', 'Could not parse baud rate', 'Please specify correct baud rate',
                       parent=win)
            return
        if not (min(STANDARD_BAUD_RATES) <= baud_rate_value <= max(STANDARD_BAUD_RATES)):
            show_error('Invalid parameters', 'Baud rate is out of range',
                       'Baud rate value should be within [%s, %s]' %
                       (min(STANDARD_BAUD_RATES), max(STANDARD_BAUD_RATES)),
                       parent=win)
            return
        kwargs['baudrate'] = baud_rate_value
        kwargs['bitrate'] = int(bitrate.value())
        result_key = str(combo.currentText()).strip()
        if not result_key:
            show_error('Invalid parameters', 'Interface name cannot be empty', 'Please select a valid interface',
                       parent=win)
            return
        try:
            result = ifaces[result_key]
        except KeyError:
            result = result_key
        win.close()

    ok.clicked.connect(on_ok)

    layout = QVBoxLayout(win)
    layout.addWidget(QLabel('Select CAN interface'))
    layout.addWidget(combo)

    slcan_group = QGroupBox('SLCAN adapter settings', win)
    slcan_layout = QVBoxLayout(slcan_group)

    slcan_layout.addWidget(QLabel('CAN bus bit rate:'))
    slcan_layout.addWidget(bitrate)
    slcan_layout.addWidget(QLabel('Adapter baud rate (not applicable to USB-CAN adapters):'))
    slcan_layout.addWidget(baudrate)

    slcan_group.setLayout(slcan_layout)

    layout.addWidget(slcan_group)
    layout.addWidget(ok)
    layout.setSizeConstraint(layout.SetFixedSize)
    win.setLayout(layout)

    with BackgroundIfaceListUpdater() as iface_lister:
        update_slcan_options_visibility()
        update_iface_list()
        timer = QTimer(win)
        timer.setSingleShot(False)
        timer.timeout.connect(update_iface_list)
        timer.start(int(BackgroundIfaceListUpdater.UPDATE_INTERVAL / 2 * 1000))
        win.exec()

    return result, kwargs
Beispiel #38
0
Datei: qtx.py Projekt: winks/pynt
class PyntGui(object):
  pynt = None
  AVATAR_SIZE = 60
  AVATAR_DEFAULT = 'assets/example.org_user.jpg'
  WINDOW_TITLE = 'Pynt, for #pants'
  ICON_APP = 'assets/icons/pynt.png'
  ICON_USER = '******'
  ICON_TIME = 'assets/icons/time.png'
  ICON_URL = 'assets/icons/connect.png'

  def __init__(self, pynt):
    self.pynt = pynt
    self.bootstrap()

  def bootstrap(self):
    self.no_margin = QMargins(0, 0, 0, 0)
    self.app = App()
    self.app.setWindowIcon(QIcon(self.ICON_APP))
    if platform.system() == 'Windows':
      myappid = 'f5n.pynt.alpha'
      ctypes.windll.shell32.SetCurrentProcessExplicitAppUserModelID(myappid)

    self.scroll_area = QScrollArea()
    self.scroll_area.setContentsMargins(self.no_margin)
    self.scroll_area.setBackgroundRole(QPalette.Dark);
    self.scroll_area.setWidgetResizable(True)
    self.scroll_area.setWindowTitle(self.WINDOW_TITLE)

    self.main_layout = QVBoxLayout()
    self.main_layout.setSpacing(0)
    self.main_layout.setContentsMargins(self.no_margin)
    self.main_layout.addWidget(self.scroll_area)

    self.contents = QWidget()
    self.contents.setContentsMargins(self.no_margin)
    self.contents.setSizePolicy(QSizePolicy.Ignored, QSizePolicy.Ignored)
    #self.contents.setScaledContents(True)

    self.scroll_area.setWidget(self.contents)

    self.layout = QVBoxLayout(self.contents)
    self.layout.setSizeConstraint(QLayout.SetMinimumSize)

    return self

  def addStuff(self, posts):
    for post in posts:
      # xpanel holds one post
      xpanel_layout = QHBoxLayout()
      xpanel_layout.setSpacing(5)
      xpanel_layout.setContentsMargins(self.no_margin)

      xpanel = QFrame()
      xpanel.setContentsMargins(self.no_margin)
      xpanel.setLayout(xpanel_layout)

      avatar_label = self.updated_avatar(self.AVATAR_DEFAULT)

      # panel holds controls and view
      panel_layout = QVBoxLayout()
      panel_layout.setSpacing(0)
      panel_layout.setContentsMargins(self.no_margin)

      panel = QFrame()
      panel.setLayout(panel_layout)
      panel.setContentsMargins(self.no_margin)
      panel.setStyleSheet("background-color:green;")

      # control holds the controls at the top
      control_layout = QHBoxLayout()
      control_layout.setSpacing(0)
      control_layout.setContentsMargins(self.no_margin)

      controls = QFrame()
      controls.setStyleSheet("background-color:#ffeeee;")
      controls.setContentsMargins(self.no_margin)
      controls.setLayout(control_layout)

      # ctrl_ is inside control
      ctrl_url = QPushButton()
      ctrl_url.setContentsMargins(self.no_margin)
      ctrl_url.setStyleSheet("QPushButton { color: black; }")
      ctrl_url.setFlat(True)
      ctrl_url.setIcon(QIcon(self.ICON_URL))

      ctrl_updated = QPushButton()
      ctrl_updated.setContentsMargins(self.no_margin)
      ctrl_updated.setStyleSheet("color:#000000;")
      ctrl_updated.setFlat(True)
      ctrl_updated.setIcon(QIcon(self.ICON_TIME))

      ctrl_user = QPushButton()
      ctrl_user.setContentsMargins(self.no_margin)
      ctrl_user.setStyleSheet("QPushButton { color: black; }")
      ctrl_user.setFlat(True)
      ctrl_user.setIcon(QIcon(self.ICON_USER))

      # view displays HTML
      view = WebView()
      #view.setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Maximum)
      view.setMinimumHeight(200)
      view.setContentsMargins(self.no_margin)
      view.setStyleSheet("background-color:#eeeeff;")


      # set the data to the widgets
      domain = post["guid"].split('/')[0]
      path = "assets/{}_user.jpg".format(domain)
      avatar_label = self.updated_avatar(path)

      ctrl_url.setText(post["url"])
      ctrl_updated.setText(post["edited_at"])
      ctrl_user.setText(self.pynt.users[domain]["display_name"])
      view.setHtml(post["body_html"])

      # now put everything together
      control_layout.addWidget(ctrl_user)
      control_layout.addWidget(ctrl_updated)
      control_layout.addWidget(ctrl_url)

      panel_layout.addWidget(controls)
      panel_layout.addWidget(view)

      xpanel_layout.addWidget(avatar_label, 0, Qt.AlignTop)
      xpanel_layout.addWidget(panel)

      self.layout.addWidget(xpanel)

    return self

  def updated_avatar(self, path):
    pixmap = QPixmap(path).scaled(self.AVATAR_SIZE,
                                  self.AVATAR_SIZE)
    image_label = QLabel()
    image_label.setPixmap(pixmap)

    return image_label

  def run(self):
    self.scroll_area.show()
    return self.app.exec_()
Beispiel #39
0
class PasswordDialog(QDialog):

    """ Basic dialog with a textbox input field for the password/-phrase and OK/Cancel buttons """

    def __init__(self, parent, message, title='Enter Password'):
        """
            :param parent: The parent window/dialog used to enable modal behaviour
            :type parent: :class:`gtk.Widget`
            :param message: The message that gets displayed above the textbox
            :type message: str
            :param title: Displayed in the dialogs titlebar
            :type title: str or None
        """
        super(PasswordDialog, self).__init__(parent, Qt.WindowCloseButtonHint | Qt.WindowTitleHint)
        self.setWindowTitle(title)
        self.layout = QVBoxLayout()
        self.layout.setSizeConstraint(QLayout.SetFixedSize)
        self.layout.setSpacing(10)

        # create icon and label
        self.header_box = QHBoxLayout()
        self.header_box.setSpacing(10)
        self.header_box.setAlignment(Qt.AlignLeft)
        self.header_text = QLabel(message)
        icon = QLabel()
        icon.setPixmap(QIcon.fromTheme('dialog-password', QApplication.style().standardIcon(QStyle.SP_DriveHDIcon)).pixmap(32))
        self.header_box.addWidget(icon)
        self.header_box.addWidget(self.header_text)
        self.layout.addLayout(self.header_box)

        # create the text input field
        self.pw_box = QLineEdit()
        self.pw_box.setMinimumSize(0, 25)
        # password will not be shown on screen
        self.pw_box.setEchoMode(QLineEdit.Password)
        self.layout.addWidget(self.pw_box)
        self.layout.addSpacing(10)

        # OK and Cancel buttons
        self.buttons = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel, parent=self)
        self.buttons.accepted.connect(self.on_accepted)
        self.buttons.rejected.connect(self.reject)
        self.layout.addWidget(self.buttons)

        self.setLayout(self.layout)
        self.pw_box.setFocus()

    def on_accepted(self):
        """ Event handler for accept signal: block when input field empty """
        if self.pw_box.text() != '':
            self.accept()
        else:
            self.pw_box.setFocus()

    def get_pw(self):
        """ Get pw inputfiled value, returns python unicode instead of QString in py2"""
        try:
            return str(self.pw_box.text())
        except UnicodeEncodeError:
            return unicode(self.pw_box.text().toUtf8(), encoding="UTF-8")

    def get_password(self):
        """ Dialog runs itself and returns the password/-phrase entered
            or throws an exception if the user cancelled/closed the dialog
            :returns: The entered password/-phrase
            :rtype: str
            :raises: UserInputError
        """
        try:
            if self.exec_():
                return self.get_pw()
            else:
                raise UserInputError()
        finally:
            self.destroy()
def run_iface_config_window(icon):
    win = QDialog()
    win.setWindowTitle('CAN Interface Configuration')
    win.setWindowIcon(icon)
    win.setWindowFlags(Qt.CustomizeWindowHint | Qt.WindowTitleHint | Qt.WindowCloseButtonHint)

    combo = QComboBox(win)
    combo.setEditable(True)
    combo.setInsertPolicy(QComboBox.NoInsert)
    combo.setSizeAdjustPolicy(QComboBox.AdjustToContents)
    combo.setFont(get_monospace_font())

    combo_completer = QCompleter()
    combo_completer.setCaseSensitivity(Qt.CaseSensitive)
    combo_completer.setModel(combo.model())
    combo.setCompleter(combo_completer)

    bitrate = QSpinBox()
    bitrate.setMaximum(1000000)
    bitrate.setMinimum(10000)
    bitrate.setValue(1000000)

    extra_args = QLineEdit()
    extra_args.setFont(get_monospace_font())

    ok = QPushButton('OK', win)

    ifaces = None

    def update_iface_list():
        nonlocal ifaces
        ifaces = iface_lister.get_list()
        known_keys = set()
        remove_indices = []
        was_empty = combo.count() == 0
        # Marking known and scheduling for removal
        for idx in count():
            tx = combo.itemText(idx)
            if not tx:
                break
            known_keys.add(tx)
            if tx not in ifaces:
                logger.debug('Removing iface %r', tx)
                remove_indices.append(idx)
        # Removing - starting from the last item in order to retain indexes
        for idx in remove_indices[::-1]:
            combo.removeItem(idx)
        # Adding new items - starting from the last item in order to retain the final order
        for key in list(ifaces.keys())[::-1]:
            if key not in known_keys:
                logger.debug('Adding iface %r', key)
                combo.insertItem(0, key)
        # Updating selection
        if was_empty:
            combo.setCurrentIndex(0)

    result = None
    kwargs = {}

    def on_ok():
        nonlocal result, kwargs
        a = str(extra_args.text())
        if a:
            try:
                kwargs = dict(eval(a))
            except Exception as ex:
                show_error('Invalid parameters', 'Could not parse optional arguments', ex, parent=win)
                return
        kwargs['bitrate'] = int(bitrate.value())
        result_key = str(combo.currentText()).strip()
        if not result_key:
            show_error('Invalid parameters', 'Interface name cannot be empty', 'Please select a valid interface',
                       parent=win)
            return
        try:
            result = ifaces[result_key]
        except KeyError:
            result = result_key
        win.close()

    ok.clicked.connect(on_ok)

    layout = QVBoxLayout()
    layout.addWidget(QLabel('Select CAN interface or serial port for SLCAN:'))
    layout.addWidget(combo)
    layout.addWidget(QLabel('Interface bitrate (SLCAN only):'))
    layout.addWidget(bitrate)
    layout.addWidget(QLabel('Optional arguments (refer to PyUAVCAN for info):'))
    layout.addWidget(extra_args)
    layout.addWidget(ok)
    layout.setSizeConstraint(layout.SetFixedSize)
    win.setLayout(layout)

    with BackgroundIfaceListUpdater() as iface_lister:
        update_iface_list()
        timer = QTimer(win)
        timer.setSingleShot(False)
        timer.timeout.connect(update_iface_list)
        timer.start(int(BackgroundIfaceListUpdater.UPDATE_INTERVAL / 2 * 1000))
        win.exec()

    return result, kwargs
def run_iface_config_window(icon):
    ifaces = list_ifaces()

    win = QDialog()
    win.setWindowTitle('CAN Interface Configuration')
    win.setWindowIcon(icon)
    win.setWindowFlags(Qt.CustomizeWindowHint | Qt.WindowTitleHint | Qt.WindowCloseButtonHint)

    combo = QComboBox(win)
    combo.setEditable(True)
    combo.setInsertPolicy(QComboBox.NoInsert)
    combo.setSizeAdjustPolicy(QComboBox.AdjustToContents)
    combo.addItems(ifaces.keys())

    combo_completer = QCompleter()
    combo_completer.setCaseSensitivity(Qt.CaseSensitive)
    combo_completer.setModel(combo.model())
    combo.setCompleter(combo_completer)

    bitrate = QSpinBox()
    bitrate.setMaximum(1000000)
    bitrate.setMinimum(10000)
    bitrate.setValue(1000000)

    extra_args = QLineEdit()
    extra_args.setFont(get_monospace_font())

    ok = QPushButton('OK', win)

    result = None
    kwargs = {}

    def on_ok():
        nonlocal result, kwargs
        a = str(extra_args.text())
        if a:
            try:
                kwargs = dict(eval(a))
            except Exception as ex:
                show_error('Invalid parameters', 'Could not parse optional arguments', ex, parent=win)
                return
        kwargs['bitrate'] = int(bitrate.value())
        result_key = str(combo.currentText()).strip()
        try:
            result = ifaces[result_key]
        except KeyError:
            result = result_key
        win.close()

    ok.clicked.connect(on_ok)

    layout = QVBoxLayout()
    layout.addWidget(QLabel('Select CAN interface or serial port for SLCAN:'))
    layout.addWidget(combo)
    layout.addWidget(QLabel('Interface bitrate (SLCAN only):'))
    layout.addWidget(bitrate)
    layout.addWidget(QLabel('Optional arguments (refer to Pyuavcan for info):'))
    layout.addWidget(extra_args)
    layout.addWidget(ok)
    layout.setSizeConstraint(layout.SetFixedSize)
    win.setLayout(layout)
    win.exec()

    return result, kwargs