def changeTileWidth(): """Change tile width (tile block size) and reset image-scene""" dlg = QDialog(self) dlg.setWindowTitle("Viewer Tile Width") dlg.setModal(True) spinBox = QSpinBox(parent=dlg) spinBox.setRange(128, 10 * 1024) spinBox.setValue(self.editor.imageScenes[0].tileWidth()) ctrl_layout = QHBoxLayout() ctrl_layout.addSpacerItem(QSpacerItem(10, 0, QSizePolicy.Expanding)) ctrl_layout.addWidget(QLabel("Tile Width:")) ctrl_layout.addWidget(spinBox) button_box = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel, parent=dlg) button_box.accepted.connect(dlg.accept) button_box.rejected.connect(dlg.reject) dlg_layout = QVBoxLayout() dlg_layout.addLayout(ctrl_layout) dlg_layout.addWidget( QLabel("Setting will apply current view immediately,\n" "and all other views upon restart.") ) dlg_layout.addWidget(button_box) dlg.setLayout(dlg_layout) if dlg.exec_() == QDialog.Accepted: for s in self.editor.imageScenes: if s.tileWidth != spinBox.value(): s.setTileWidth(spinBox.value()) s.reset()
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)
def initUI(self): self.graphicsView = GraphicsView(self) self.graphicsView.setDragMode(QGraphicsView.RubberBandDrag) self.graphicsView.setOptimizationFlags(QGraphicsView.DontSavePainterState) self.graphicsView.setViewportUpdateMode(QGraphicsView.SmartViewportUpdate) self.graphicsView.setTransformationAnchor(QGraphicsView.AnchorUnderMouse) self.graphicsView.setRenderHint(QPainter.Antialiasing, True) #Make a graphics scene self.scene = GraphicsScene() self.graphicsView.setScene(self.scene) #Create a graph that can contain nodes and edges self.graph = Graph(self, self.scene, self.graphicsView) self.tokensInScene = [] # initial zoomlevel self.zoomLevel = 250 #Final layout topLayout = QHBoxLayout() topLayout.setContentsMargins(0, 0, 0, 0) topLayout.setSpacing(0) topLayout.addWidget(self.graphicsView) self.setLayout(topLayout)
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)
def __init__(self, tableName, parent=None): super(TableEditor, self).__init__(parent) self.model = QSqlTableModel(self) self.model.setTable(tableName) self.model.setEditStrategy(QSqlTableModel.OnManualSubmit) self.model.select() self.model.setHeaderData(0, Qt.Horizontal, "ID") self.model.setHeaderData(1, Qt.Horizontal, "First name") self.model.setHeaderData(2, Qt.Horizontal, "Last name") view = QTableView() view.setModel(self.model) submitButton = QPushButton("Submit") submitButton.setDefault(True) revertButton = QPushButton("&Revert") quitButton = QPushButton("Quit") buttonBox = QDialogButtonBox(Qt.Vertical) buttonBox.addButton(submitButton, QDialogButtonBox.ActionRole) buttonBox.addButton(revertButton, QDialogButtonBox.ActionRole) buttonBox.addButton(quitButton, QDialogButtonBox.RejectRole) submitButton.clicked.connect(self.submit) revertButton.clicked.connect(self.model.revertAll) quitButton.clicked.connect(self.close) mainLayout = QHBoxLayout() mainLayout.addWidget(view) mainLayout.addWidget(buttonBox) self.setLayout(mainLayout) self.setWindowTitle("Cached Table")
def __init__(self, citylist, accurate_url, appid, parent=None): super(CityListDlg, self).__init__(parent) self.citylist = citylist self.accurate_url = accurate_url self.appid = appid self.listWidget = QListWidget() self.listWidget.addItems(self.citylist) buttonLayout = QVBoxLayout() self.buttonBox = QDialogButtonBox() self.buttonBox.setOrientation(Qt.Horizontal) self.buttonBox.setStandardButtons(QDialogButtonBox.Ok | QDialogButtonBox.Cancel) self.buttonBox.rejected.connect(self.reject) self.buttonBox.accepted.connect(self.accept) layoutT = QVBoxLayout() layout = QHBoxLayout() layout.addWidget(self.listWidget) layout.addLayout(buttonLayout) for text, slot in ((self.tr("&Add..."), self.add), (self.tr("&Remove..."), self.remove), (self.tr("&Up"), self.up), (self.tr("&Down"), self.down), (self.tr("De&fault"), self.default), (self.tr("&Sort"), self.listWidget.sortItems)): button = QPushButton(text) buttonLayout.addWidget(button) button.clicked.connect(slot) buttonLayout.addWidget(self.buttonBox) self.status = QLabel() layoutT.addLayout(layout) layoutT.addWidget(self.status) self.setLayout(layoutT) self.checklength()
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)
def initMainUi(self): role_names = self.parentApplet.dataSelectionApplet.topLevelOperator.DatasetRoles.value self.list_widgets = [] # Create a tab for each role for role_index, role_name in enumerate(role_names): select_button = QPushButton("Select " + role_name + " Files...", clicked=partial(self.select_files, role_index) ) clear_button = QPushButton("Clear " + role_name + " Files", clicked=partial(self.clear_files, role_index) ) button_layout = QHBoxLayout() button_layout.addWidget(select_button) button_layout.addSpacerItem( QSpacerItem(0,0,hPolicy=QSizePolicy.Expanding) ) button_layout.addWidget(clear_button) button_layout.setContentsMargins(0, 0, 0, 0) button_layout_widget = QWidget() button_layout_widget.setLayout(button_layout) button_layout_widget.setSizePolicy( QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Maximum) ) list_widget = QListWidget(parent=self) list_widget.setSizePolicy( QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) ) self.list_widgets.append( list_widget ) tab_layout = QVBoxLayout() tab_layout.setContentsMargins(0, 0, 0, 0) tab_layout.addWidget( button_layout_widget ) tab_layout.addWidget( list_widget ) layout_widget = QWidget(parent=self) layout_widget.setLayout(tab_layout) self.addTab(layout_widget, role_name)
def __init__(self, parent=None): super(CentralWidget, self).__init__(parent) self.parent = parent #This variables are used to save the splitter sizes before hide self.lateralPanel = LateralPanel() self._add_functions = { "central": self._insert_widget_inside, "lateral": self._insert_widget_base, } self._items = {} hbox = QHBoxLayout(self) hbox.setContentsMargins(0, 0, 0, 0) hbox.setSpacing(0) #Create Splitters to divide the UI 3 regions self._splitterBase = dynamic_splitter.DynamicSplitter(Qt.Horizontal) self._splitterBase.setOpaqueResize(True) self._splitterInside = dynamic_splitter.DynamicSplitter(Qt.Vertical) self._splitterInside.setOpaqueResize(True) self._splitterBase.addWidget(self._splitterInside) #Add to Main Layout hbox.addWidget(self._splitterBase) IDE.register_service('central_container', self)
def __init__(self, *args): super().__init__(BrickletRotaryPotiV2, *args) self.rp = self.device self.cbe_position = CallbackEmulator(self.rp.get_position, None, self.cb_position, self.increase_error_count) self.position_knob = KnobWidget(self) self.position_knob.setFocusPolicy(Qt.NoFocus) self.position_knob.set_total_angle(300) self.position_knob.set_range(-150, 150) self.position_knob.set_scale(30, 3) self.position_knob.set_knob_radius(25) self.current_position = CurveValueWrapper() plots = [('Position', Qt.red, self.current_position, str)] self.plot_widget = PlotWidget('Position', plots, update_interval=0.025, y_resolution=1.0) layout = QHBoxLayout(self) layout.addWidget(self.plot_widget) layout.addWidget(self.position_knob)
def createBottomLeftTabWidget(self): self.bottomLeftTabWidget = QTabWidget() self.bottomLeftTabWidget.setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Ignored) tab1 = QWidget() tableWidget = QTableWidget(10, 10) tab1hbox = QHBoxLayout() tab1hbox.setContentsMargins(5, 5, 5, 5) tab1hbox.addWidget(tableWidget) tab1.setLayout(tab1hbox) tab2 = QWidget() textEdit = QTextEdit() textEdit.setPlainText("Twinkle, twinkle, little star,\n" "How I wonder what you are.\n" "Up above the world so high,\n" "Like a diamond in the sky.\n" "Twinkle, twinkle, little star,\n" "How I wonder what you are!\n") tab2hbox = QHBoxLayout() tab2hbox.setContentsMargins(5, 5, 5, 5) tab2hbox.addWidget(textEdit) tab2.setLayout(tab2hbox) self.bottomLeftTabWidget.addTab(tab1, "&Table") self.bottomLeftTabWidget.addTab(tab2, "Text &Edit")
def createChartView( self, _x2idx: dict, _idx2x: list ) -> QHBoxLayout: chart = QChart() # assign y range self.calcRangeY() self.setAxisY(self.begin_y, self.end_y) value_layout = QFormLayout() # add each series for v in self.series_table.values(): v.addSeries(_x2idx, _idx2x, chart, self.axis_x, self.axis_y) if v.show_value: value_layout.addWidget(v.show_group) # create chartview and layout for view and value chartview = ChartView(chart, self.wizard) chartview.setRenderHint(QPainter.Antialiasing) global_layout = QHBoxLayout() global_layout.addWidget(chartview, self.chart_stretch) global_layout.addLayout(value_layout) return global_layout
def __make_cell(self, c, name, col_type, col_type_def): cell = QWidget(self.inner) rbtn = QRadioButton('', cell) rbtn.toggled.connect(lambda: self.rbtn_clicked(name + '_' + str(c))) hbl = QHBoxLayout(cell) hbl.addWidget(rbtn) hbl.setContentsMargins(0, 0, 0, 0) hbl.setAlignment(Qt.AlignCenter) cell.setLayout(hbl) if name == 'cat': if col_type == 'object': rbtn.setChecked(True) self.lst_cat.append(rbtn) elif name == 'num': if col_type != 'object': rbtn.setChecked(True) if col_type_def == 'object': rbtn.setEnabled(False) self.lst_num.append(rbtn) elif name == 'obj': if col_type == 'object' and self.params.task == 'Regression': rbtn.setEnabled(False) elif col_type != 'object' and self.params.task == 'Classification': rbtn.setEnabled(False) if self.params.columns[c] == self.params.objective: rbtn.setChecked(True) self.lst_obj.append(rbtn) return cell
class RightPanel(FFrame): def __init__(self, app, parent=None): super().__init__(parent) self._app = app self.widget = None self._layout = QHBoxLayout(self) self.setLayout(self._layout) self.setObjectName('right_panel') self.set_theme_style() self.setup_ui() def set_theme_style(self): style_str = ''' #{0} {{ background: transparent; }} '''.format(self.objectName()) self.setStyleSheet(style_str) def set_widget(self, widget): if self.widget and self.widget != widget: self._layout.removeWidget(self.widget) self.widget.hide() widget.show() self._layout.addWidget(widget) else: self._layout.addWidget(widget) self.widget = widget def setup_ui(self): self._layout.setContentsMargins(0, 0, 0, 0) self._layout.setSpacing(0)
class CentralPanel(FFrame): def __init__(self, app, parent=None): super().__init__(parent) self._app = app self.left_panel_container = LeftPanel_Container(self._app, self) self.right_panel_container = RightPanel_Container(self._app, self) self.left_panel = self.left_panel_container.left_panel self.right_panel = self.right_panel_container.right_panel self._layout = QHBoxLayout(self) self.set_theme_style() self.setup_ui() def set_theme_style(self): style_str = ''' #{0} {{ background: transparent; }} '''.format(self.objectName()) self.setStyleSheet(style_str) def setup_ui(self): self._layout.setContentsMargins(0, 0, 0, 0) self._layout.setSpacing(0) self._layout.addWidget(self.left_panel_container) self._layout.addWidget(self.right_panel_container)
def __init__(self, win): QWidget.__init__(self) self.win = win self.setWindowTitle('Electrum - '+_('Payment Request')) self.setMinimumSize(800, 250) self.address = '' self.label = '' self.amount = 0 self.setFocusPolicy(QtCore.Qt.NoFocus) main_box = QHBoxLayout() self.qrw = QRCodeWidget() main_box.addWidget(self.qrw, 1) vbox = QVBoxLayout() main_box.addLayout(vbox) self.address_label = QLabel("") #self.address_label.setFont(QFont(MONOSPACE_FONT)) vbox.addWidget(self.address_label) self.label_label = QLabel("") vbox.addWidget(self.label_label) self.amount_label = QLabel("") vbox.addWidget(self.amount_label) vbox.addStretch(1) self.setLayout(main_box)
class TopPanel(FFrame): def __init__(self, app, parent=None): super().__init__(parent) self._app = app self._layout = QHBoxLayout(self) self.pc_panel = PlayerControlPanel(self._app, self) self.mo_panel = SongOperationPanel(self._app, self) self.setObjectName('top_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}; border-bottom: 3px inset {3}; }} '''.format(self.objectName(), theme.foreground.name(), theme.color0_light.name(), theme.color0_light.name()) self.setStyleSheet(style_str) def setup_ui(self): self._layout.setContentsMargins(0, 0, 0, 0) self._layout.setSpacing(0) self.setFixedHeight(50) self._layout.addSpacing(5) self._layout.addWidget(self.pc_panel) self._layout.addWidget(self.mo_panel)
def initUI(self): """Create User Interface. """ sourcePath = self.widgetSourcePath() parameters = self.widgetParameters() scroll = self.widgetImage() debug = self.widgetDebug() vbox1 = QVBoxLayout() vbox1.addLayout(sourcePath) hbox = QHBoxLayout() hbox.addLayout(parameters, 1) hbox.addLayout(scroll, 10) vbox1.addLayout(hbox) upSide = QWidget() upSide.setLayout(vbox1) vbox2 = QVBoxLayout() vbox2.addLayout(debug) downSide = QWidget() downSide.setLayout(vbox2) splitter = QSplitter(QtCore.Qt.Vertical) splitter.addWidget(upSide) splitter.addWidget(downSide) splitter.splitterMoved.connect(self.splitterMoved) mainLayout = QHBoxLayout() mainLayout.addWidget(splitter) self.setLayout(mainLayout) self.setGeometry(300, 300, 300, 150) self.show()
def createStart(self): self.startButton = QPushButton('Start battle') layout = QHBoxLayout() layout.addStretch(1) layout.addWidget(self.startButton) layout.addStretch(1) return layout
def intervalButtons(self): widget = QGroupBox('Interval') group = QButtonGroup(widget) layout = QHBoxLayout() widget.setLayout(layout) def setInterval(): self.interval = group.checkedId() interval = self.INTERVALS[self.interval][0] self.updateTitle() if interval: self.progress.show() self.progress.setMaximum(interval) value = self.timer.seconds() if value < interval: self.progress.resume() else: self.progress.stop() self.progress.setValue(min(interval, value)) else: self.progress.hide() for i, interval in enumerate(self.INTERVALS): button = QPushButton(interval[1]) button.setCheckable(True) button.clicked.connect(setInterval) group.addButton(button, i) layout.addWidget(button, 1 if i > 0 else 0) return widget
def __init__(self, parent=None): super(ToolOffsetDialog, self).__init__(parent) self._color = QColor(0, 0, 0, 150) self._state = False self.setWindowModality(Qt.ApplicationModal) self.setWindowFlags(self.windowFlags() | Qt.Tool | Qt.Dialog | Qt.WindowStaysOnTopHint | Qt.WindowSystemMenuHint) self.setMinimumSize(200, 200) buttonBox = QDialogButtonBox() buttonBox.setEnabled(False) STATUS.connect('not-all-homed', lambda w, axis: buttonBox.setEnabled(False)) STATUS.connect('all-homed', lambda w: buttonBox.setEnabled(True)) STATUS.connect('state-estop', lambda w: buttonBox.setEnabled(False)) STATUS.connect('state-estop-reset', lambda w: buttonBox.setEnabled(STATUS.machine_is_on() and STATUS.is_all_homed())) for i in('X', 'Y', 'Z'): b = 'button_%s' % i self[b] = QPushButton('Zero %s' % i) self[b].clicked.connect(self.zeroPress('%s' % i)) buttonBox.addButton(self[b], 3) v = QVBoxLayout() h = QHBoxLayout() self._o = TOOLVIEW_WIDGET() self._o._hal_init() self.setLayout(v) v.addWidget(self._o) b = QPushButton('OK') b.clicked.connect(lambda: self.close()) h.addWidget(b) h.addWidget(buttonBox) v.addLayout(h) self.setModal(True)
class Prompt(QWidget): """The prompt widget shown in the statusbar. Attributes: txt: The TextBase instance (QLabel) used to display the prompt text. lineedit: The MinimalLineEdit instance (QLineEdit) used for the input. _hbox: The QHBoxLayout used to display the text and prompt. """ def __init__(self, win_id, parent=None): super().__init__(parent) objreg.register('prompt', self, scope='window', window=win_id) self._hbox = QHBoxLayout(self) self._hbox.setContentsMargins(0, 0, 0, 0) self._hbox.setSpacing(5) self.txt = textbase.TextBase() self._hbox.addWidget(self.txt) self.lineedit = PromptLineEdit() self._hbox.addWidget(self.lineedit) prompter_obj = prompter.Prompter(win_id) objreg.register('prompter', prompter_obj, scope='window', window=win_id) self.destroyed.connect( functools.partial(objreg.delete, 'prompter', scope='window', window=win_id)) def __repr__(self): return utils.get_repr(self)
def __init__(self, parent, name): QWidget.__init__(self, parent) self.setStyleSheet(get_stylesheet("ribbonPane")) horizontal_layout = QHBoxLayout() horizontal_layout.setSpacing(0) horizontal_layout.setContentsMargins(0, 0, 0, 0) self.setLayout(horizontal_layout) vertical_widget = QWidget(self) horizontal_layout.addWidget(vertical_widget) horizontal_layout.addWidget(RibbonSeparator(self)) vertical_layout = QVBoxLayout() vertical_layout.setSpacing(0) vertical_layout.setContentsMargins(0, 0, 0, 0) vertical_widget.setLayout(vertical_layout) label = QLabel(name) label.setAlignment(Qt.AlignCenter) label.setStyleSheet("color:#666;") content_widget = QWidget(self) vertical_layout.addWidget(content_widget) vertical_layout.addWidget(label) content_layout = QHBoxLayout() content_layout.setAlignment(Qt.AlignLeft) content_layout.setSpacing(0) content_layout.setContentsMargins(0, 0, 0, 0) self.contentLayout = content_layout content_widget.setLayout(content_layout)
class UserListTab(QWidget): dbhelper = None def __init__(self, dbhelper, *args): super(UserListTab, self).__init__(*args) self.dbhelper = dbhelper self.horizontalLayout = QHBoxLayout(self) self.horizontalLayout.setObjectName("horizontalLayout") model = AlchemicalTableModel( self.dbhelper.get_app_db_session(), User, [('Name', User.name, 'name', {}), ('Full Name', User.fullname, 'fullname', {}), ('Password', User.password, 'password', {}), ('Date created', User.date_created, 'date_created', {})]) self.tableView = MyTableView() self.tableView.setModel(model) self.form = UserForm(model, self.dbhelper) selectionModel = self.tableView.selectionModel() selectionModel.selectionChanged.connect(self.form.set_mapper_index_from_selection) self.horizontalLayout.addWidget(self.form) self.horizontalLayout.addWidget(self.tableView) self.setLayout(self.horizontalLayout)
class BankAccountListTab(QWidget): dbhelper = None def __init__(self, dbhelper, *args): super(BankAccountListTab, self).__init__(*args) Lumberjack.info('spawning a << BankAccountListTab >>') self.dbhelper = dbhelper self.horizontalLayout = QHBoxLayout(self) model = AlchemicalTableModel( self.dbhelper.get_app_db_session(), BankAccount, [('Bank name', BankAccount.bank_name, 'bank_name', {}), ('User', BankAccount.user, 'user.name', {}), ('Account Nr.', BankAccount.account, 'account', {}), ('Balance', BankAccount.balance, 'balance', {'type': 'currency', }), ('Date created', BankAccount.date_created, 'date_created', {})]) # TODO - Create visual effect for negative balance or amount eg: green for positive, red for negative. self.tableView = MyTableView() self.tableView.setModel(model) self.form = BankAccountForm(model, self.dbhelper) self.form.tableBuddy = self.tableView selectionModel = self.tableView.selectionModel() selectionModel.selectionChanged.connect(self.form.set_mapper_index_from_selection) self.horizontalLayout.addWidget(self.form) self.horizontalLayout.addWidget(self.tableView) self.setLayout(self.horizontalLayout)
class LetterListTab(QWidget): dbhelper = None def __init__(self, dbhelper, *args): super(LetterListTab, self).__init__(*args) Lumberjack.info('spawning a << LetterListTab >>') self.dbhelper = dbhelper self.horizontalLayout = QHBoxLayout(self) model = AlchemicalTableModel( self.dbhelper.get_app_db_session(), Letter, [('Date', Letter.date, 'date', {}), ('Subject', Letter.subject, 'subject', {}), ('Sender', Letter.relation, 'relation.name', {}), ('Reference', Letter.reference, 'reference', {}), ('User', Letter.user, 'user.fullname', {}), ('Letter scan', Letter.scan_file, 'scan_file', {}), ('Letter type', Letter.letter_type, 'letter_type.letter', {}), ('Date created', Letter.date_created, 'date_created', {})]) self.tableView = MyTableView() self.tableView.setModel(model) self.form = LetterForm(model, self.dbhelper) selectionModel = self.tableView.selectionModel() selectionModel.selectionChanged.connect(self.form.set_mapper_index_from_selection) self.horizontalLayout.addWidget(self.form) self.horizontalLayout.addWidget(self.tableView) self.setLayout(self.horizontalLayout)
class RelationListTab(QWidget): dbhelper = None def __init__(self, dbhelper, *args): super(RelationListTab, self).__init__(*args) Lumberjack.info('spawning a << RelationListTab >>') self.dbhelper = dbhelper self.horizontalLayout = QHBoxLayout(self) self.horizontalLayout.setObjectName("horizontalLayout") model = AlchemicalTableModel( self.dbhelper.get_app_db_session(), Relation, [('Name', Relation.name, 'name', {}), ('Full Name', Relation.fullname, 'fullname', {}), ('Reference', Relation.reference, 'reference', {}), ('Bank account', Relation.bank_account, 'bank_account', {}), ('Relation type', Relation.relation_type, 'relation_type.relation', {}), ('Date created', Relation.date_created, 'date_created', {})]) self.tableView = MyTableView() self.tableView.setModel(model) self.form = RelationForm(model, self.dbhelper) selectionModel = self.tableView.selectionModel() selectionModel.selectionChanged.connect(self.form.set_mapper_index_from_selection) self.horizontalLayout.addWidget(self.form) self.horizontalLayout.addWidget(self.tableView) self.setLayout(self.horizontalLayout)
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
class EmailAddressListTab(QWidget): dbhelper = None def __init__(self, dbhelper, *args): super(EmailAddressListTab, self).__init__(*args) Lumberjack.info('spawning a << EmailAddressListTab >>') self.dbhelper = dbhelper self.horizontalLayout = QHBoxLayout(self) model = AlchemicalTableModel( self.dbhelper.get_app_db_session(), EmailAddress, [('User', EmailAddress.user, 'user.fullname', {}), ('Address', EmailAddress.address, 'address', {}), ('Date created', EmailAddress.date_created, 'date_created', {})]) self.tableView = MyTableView() self.tableView.setModel(model) self.form = EmailAddressForm(model, self.dbhelper) selectionModel = self.tableView.selectionModel() selectionModel.selectionChanged.connect(self.form.set_mapper_index_from_selection) self.horizontalLayout.addWidget(self.form) self.horizontalLayout.addWidget(self.tableView) self.setLayout(self.horizontalLayout)
def createDisplay(self): self.displayLCD = QGroupBox("") layout = QHBoxLayout() paletteLosses = QPalette() paletteVictory = QPalette() paletteLosses.setColor(paletteLosses.WindowText, QColor(255, 000, 000)) paletteVictory.setColor(paletteVictory.WindowText, QColor(000, 255, 000)) self.lossesLcd = QLCDNumber(3) self.lossesLcd.setSegmentStyle(QLCDNumber.Filled) self.lossesLcd.setPalette(paletteLosses) self.victoryLcd = QLCDNumber(3) self.victoryLcd.setSegmentStyle(QLCDNumber.Filled) self.victoryLcd.setPalette(paletteVictory) self.lossesLcd.setMinimumHeight(100) self.victoryLcd.setMinimumHeight(100) self.lossesLcd.setMinimumWidth(150) self.victoryLcd.setMinimumWidth(150) layout.addWidget(self.victoryLcd) layout.addWidget(self.lossesLcd) self.displayLCD.setLayout(layout)
class LogInWidget(QWidget): """ QWidget that takes in email, password, and allow user to submit. Parameters: Parent Window, Database connection Shows email input, password input, and a submit button. When submit is clicked, the Widget calls a validator function in parent window of type LogInWindow. """ def __init__(self, DBconnect, *args, **kwargs): """ Initializes object's database connection, email field, password field, and submit connection """ super().__init__(*args, **kwargs) self.DBconnect = DBconnect # tried to make custom signal, uneccesary #self.submittedSignal = clickSubmit() #self.submittedSignal.submitted.connect(self.parentWindow.submitClicked(string, string)) self.mainLayout = QVBoxLayout(self) self.formLayout = QFormLayout() self.emailLayout = QHBoxLayout() self.passwordLayout = QHBoxLayout() self.email = QLineEdit() self.password = QLineEdit() self.password.setEchoMode(QLineEdit.Password) self.submit = QPushButton("Log In") self.newuser = QPushButton("New User") # SHOULD BE? self.submit.clicked.connect(partial(self.parentWindow.submitClicked, self.email.text(), self.password.text())) self.formLayout.addRow("Email", self.email) self.formLayout.addRow("Password", self.password) widg_width = self.frameGeometry().width() pic_width = int((widg_width * .25)) self.logo_pic = QPixmap('images/house_logo.png') self.logo_pic = self.logo_pic.scaled(pic_width, pic_width, Qt.KeepAspectRatio) self.logo = QLabel() self.logo.setPixmap(self.logo_pic) self.mainLayout.addWidget(self.logo, alignment=Qt.AlignHCenter) self.mainLayout.addLayout(self.formLayout) self.buttonLayout = QHBoxLayout() # alligns the buttons horizontally self.buttonLayout.addWidget(self.submit) self.buttonLayout.addWidget(self.newuser) self.mainLayout.addLayout(self.buttonLayout) # self.mainLayout.addWidget(self.newuser, alignment=Qt.AlignHCenter) def checkEmailValid(self, text): """ Checks if given email is valid (not related to DB) through checking domain and checking syntax Parameters: email (String) Output: (True if valid False if invalid (Bool), email if valid and error if not valid (String)) (Tuple) """ print("Email passed in checkEmailValid: ", text) try: v = validate_email(text) # validate and get info return (True, v["email"]) # replace with normalized form except EmailNotValidError as e: # email is not valid, exception message is human-readable print(str(e)) return (False, str(e)) def logInValid(self, in_email, in_pwd): """ Checks with database through the db connection if the email and password exist Parameters: email (String) password (String) Output: (True if exists False if does not exist (Bool), userId (Int)) (Tuple) """ email = in_email.text() pwd = in_pwd.text() print("logInValid email:", email) emailValidity = self.checkEmailValid(email) if emailValidity[0] == True: checkUserInfo = self.DBconnect.checkUser(email, pwd) print("Does it exist: ", checkUserInfo) if checkUserInfo[0]: return (checkUserInfo) else: self.password.clear() self.email.clear() self.email.setPlaceholderText("No account found") self.password.setPlaceholderText("Try again") return ((False, None)) else: self.password.clear() self.email.clear() self.email.setPlaceholderText("Invalid email") print(emailValidity[1]) return ((False, None))
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_()
def __init__(self, parent=None): super().__init__(parent) self.setSubTitle(self.tr("<h2>Create Your Avatar</h2>")) vlayout = QVBoxLayout(self) labelLayout = QHBoxLayout() labelImage = QLabel() labelImage.setPixmap( QPixmap(":/data/images/preferences-desktop-personal.png")) labelImage.setMaximumSize(64, 64) labelLayout.addWidget(labelImage) label = QLabel(self) label.setWordWrap(True) label.setText( self. tr("<p>This screen helps you set your <strong>user picture</strong>. You can either choose an image from a \ file or you can capture an image from your camera. Select an option from the <strong>options</strong> menu.</p>" )) labelLayout.addWidget(label) vlayout.addLayout(labelLayout) vlayout.addItem( QSpacerItem(20, 40, QSizePolicy.Preferred, QSizePolicy.Preferred)) centerLayout = QHBoxLayout() centerLayout.addItem( QSpacerItem(40, 20, QSizePolicy.Preferred, QSizePolicy.Preferred)) groupBox = QGroupBox() groupBox.setMaximumWidth(500) vlayout2 = QVBoxLayout(groupBox) hlayout = QHBoxLayout() comboBox = QComboBox() comboBox.setMinimumWidth(250) comboBox.addItems([self.tr("Options"), self.tr("Choose an image...")]) #Camera control self.cameraInfo = None self.camera = None self.cameraImageCapture = None cameras = QCameraInfo.availableCameras() if len(cameras): self.cameraInfo = cameras[0] comboBox.addItem(self.tr("Camera ") + self.cameraInfo.deviceName()) self.camera = QCamera(self.cameraInfo) self.camera.setCaptureMode(QCamera.CaptureStillImage) self.cameraImageCapture = QCameraImageCapture(self.camera) self.imageProcessing = self.camera.imageProcessing() self.imageProcessing.setWhiteBalanceMode( QCameraImageProcessing.WhiteBalanceSunlight) self.imageProcessing.setContrast(1) self.imageProcessing.setSaturation(1) self.imageProcessing.setSharpeningLevel(1) self.imageProcessing.setDenoisingLevel(1) #self.imageProcessing.setColorFilter(QCameraImageProcessing.ColorFilterWhiteboard) #FIXME Qt5.5 self.cameraImageCapture.imageCaptured.connect(self.imageCapture) self.buttonCam = QPushButton() self.buttonCam.setText(self.tr("Capture")) self.buttonCam.setIcon(QIcon(":/data/images/webcamreceive.png")) self.buttonCam.setVisible(False) self.buttonReplay = QPushButton() self.buttonReplay.setText(self.tr("Recapture")) self.buttonReplay.setIcon(QIcon(":/data/images/view-refresh.png")) self.buttonReplay.setVisible(False) hlayout.addWidget(comboBox) hlayout.addItem( QSpacerItem(300, 20, QSizePolicy.Preferred, QSizePolicy.Preferred)) hlayout.addWidget(self.buttonCam) hlayout.addWidget(self.buttonReplay) vlayout2.addLayout(hlayout) hlayout2 = QHBoxLayout() hlayout2.addItem( QSpacerItem(40, 20, QSizePolicy.Preferred, QSizePolicy.Preferred)) self.cameraLabel = QLabel() self.cameraLabel.setScaledContents(True) self.cameraLabel.setStyleSheet("background-color: black;") self.cameraLabel.setMinimumSize(320, 240) self.cameraLabel.setMaximumSize(320, 240) self.cameraView = QCameraViewfinder() self.cameraView.setMaximumSize(320, 240) self.cameraView.setMinimumSize(320, 240) self.cameraView.hide() hlayout2.addWidget(self.cameraLabel) hlayout2.addWidget(self.cameraView) hlayout2.addItem( QSpacerItem(40, 20, QSizePolicy.Preferred, QSizePolicy.Preferred)) vlayout2.addLayout(hlayout2) centerLayout.addWidget(groupBox) centerLayout.addItem( QSpacerItem(40, 20, QSizePolicy.Preferred, QSizePolicy.Preferred)) vlayout.addLayout(centerLayout) vlayout.addItem( QSpacerItem(20, 40, QSizePolicy.Preferred, QSizePolicy.Preferred)) comboBox.currentIndexChanged.connect(self.avatarSelect) self.buttonCam.clicked.connect(self.buttonCamChanged) self.buttonReplay.clicked.connect(self.buttonReplayChanged) self.userAvatar = None
class SourceWidget(QWidget): """ Used to display summary information about a source in the list view. """ def __init__(self, parent, source): """ Set up the child widgets. """ super().__init__(parent) self.source = source layout = QVBoxLayout() self.setLayout(layout) self.summary = QWidget(self) self.summary_layout = QHBoxLayout() self.summary.setLayout(self.summary_layout) self.attached = load_svg('paperclip.svg') self.attached.setMaximumSize(16, 16) self.name = QLabel() self.summary_layout.addWidget(self.name) self.summary_layout.addStretch() self.summary_layout.addWidget(self.attached) layout.addWidget(self.summary) self.updated = QLabel() layout.addWidget(self.updated) self.details = QLabel() self.details.setWordWrap(True) layout.addWidget(self.details) self.update() def setup(self, controller): """ Pass through the controller object to this widget. """ self.controller = controller def display_star_icon(self): """ Show the correct star icon """ if getattr(self, 'starred', None): # Delete icon if it exists. self.summary_layout.removeWidget(self.starred) if self.source.is_starred: self.starred = load_svg('star_on.svg') else: self.starred = load_svg('star_off.svg') self.summary_layout.addWidget(self.starred) self.starred.setMaximumSize(16, 16) self.starred.mousePressEvent = self.toggle_star def update(self): """ Updates the displayed values with the current values from self.source. TODO: Style this widget properly and work out what should be in the self.details label. """ self.updated.setText(arrow.get(self.source.last_updated).humanize()) self.display_star_icon() self.name.setText("<strong>{}</strong>".format( self.source.journalist_designation)) self.details.setText("Lorum ipsum dolor sit amet thingy dodah...") def toggle_star(self, event): """ Called when the star is clicked. """ self.controller.update_star(self.source)
class SettingsWindow(QMainWindow, BaseWindow, Ui_SettingsWindow): def __init__(self, parent): super().__init__() self.parent = parent self.setupUi(self) self.setWindowTitle("Settings") self.HeaderLayout = QHBoxLayout() self.HeaderLayout.setContentsMargins(36, 1, 1, 0) self.HeaderLayout.setSpacing(0) self.CentralLayout.addLayout(self.HeaderLayout) self.CloseButton = \ QPushButton(QIcon(":resources/icons/close.svg"), "") self.CloseButton.setIconSize(QSize(20, 20)) self.CloseButton.setFixedSize(36, 32) self.CloseButton.setProperty("HeaderButton", True) self.CloseButton.setProperty("CloseButton", True) self.CloseButton.clicked.connect(self.close) self.HeaderLabel = QLabel("Settings") self.HeaderLabel.setAlignment(Qt.AlignCenter) self.HeaderLayout.addWidget(self.HeaderLabel, 1) self.HeaderLayout.addWidget(self.CloseButton, 0, Qt.AlignRight) self.LibraryFolderLineEdit = QLineEdit() self.LibraryFolderLineEdit.setText(str(get_library_folder())) self.LibraryFolderLineEdit.setContextMenuPolicy(Qt.NoContextMenu) self.LibraryFolderLineEdit.setReadOnly(True) self.LibraryFolderLineEdit.setCursorPosition(0) self.SetLibraryFolderButton = \ QPushButton(QIcon(":resources/icons/folder.svg"), "") self.SetLibraryFolderButton.clicked.connect(self.set_library_folder) self.LaunchWhenSystemStartsCheckBox = QCheckBox( "Launch When System Starts") self.LaunchWhenSystemStartsCheckBox.setChecked( get_launch_when_system_starts()) self.LaunchWhenSystemStartsCheckBox.clicked.connect( self.toggle_launch_when_system_starts) self.LaunchMinimizedToTrayCheckBox = QCheckBox( "Launch Minimized To Tray") self.LaunchMinimizedToTrayCheckBox.setChecked( get_launch_minimized_to_tray()) self.LaunchMinimizedToTrayCheckBox.clicked.connect( self.toggle_launch_minimized_to_tray) self.EnableHighDpiScalingCheckBox = \ QCheckBox("Enable High DPI Scaling") self.EnableHighDpiScalingCheckBox.clicked.connect( self.toggle_enable_high_dpi_scaling) self.EnableHighDpiScalingCheckBox.setChecked( get_enable_high_dpi_scaling()) self.SettingsLayout = QVBoxLayout() self.SettingsLayout.setContentsMargins(6, 6, 6, 6) self.SettingsLayout.setSpacing(6) self.CentralLayout.addLayout(self.SettingsLayout) self.LibraryFolderLayout = QHBoxLayout() self.LibraryFolderLayout.setContentsMargins(1, 1, 1, 1) self.LibraryFolderLayout.setSpacing(0) self.SettingsLayout.addWidget(QLabel("Library Folder:")) self.SettingsLayout.addLayout(self.LibraryFolderLayout) self.LibraryFolderLayout.addWidget(self.LibraryFolderLineEdit) self.LibraryFolderLayout.addWidget(self.SetLibraryFolderButton) self.SettingsLayout.addWidget(QLabel("System:")) if get_platform() == 'Windows': self.SettingsLayout.addWidget(self.LaunchWhenSystemStartsCheckBox) self.DefaultLibraryPageComboBox = QComboBox() self.DefaultLibraryPageComboBox.addItems(library_pages.keys()) self.DefaultLibraryPageComboBox.setCurrentIndex( get_default_library_page()) self.DefaultLibraryPageComboBox.activated[str].connect( self.change_default_library_page) self.SettingsLayout.addWidget(self.LaunchMinimizedToTrayCheckBox) self.SettingsLayout.addWidget(self.EnableHighDpiScalingCheckBox) self.SettingsLayout.addWidget(QLabel("Interface:")) self.DefaultLibraryPageLayout = QHBoxLayout() self.DefaultLibraryPageLayout.setContentsMargins(1, 1, 1, 1) self.DefaultLibraryPageLayout.setSpacing(0) self.DefaultLibraryPageLayout.addWidget( QLabel("Default Library Page:"), 1) self.DefaultLibraryPageLayout.addWidget( self.DefaultLibraryPageComboBox) self.SettingsLayout.addLayout(self.DefaultLibraryPageLayout) self.resize(self.sizeHint()) self.show() def set_library_folder(self): library_folder = str(get_library_folder()) new_library_folder = QFileDialog.getExistingDirectory( self, "Select Library Folder", library_folder) if new_library_folder and (library_folder != new_library_folder): self.LibraryFolderLineEdit.setText(new_library_folder) set_library_folder(new_library_folder) self.parent.draw_library(clear=True) def toggle_launch_when_system_starts(self, is_checked): set_launch_when_system_starts(is_checked) def toggle_launch_minimized_to_tray(self, is_checked): set_launch_minimized_to_tray(is_checked) def toggle_enable_high_dpi_scaling(self, is_checked): set_enable_high_dpi_scaling(is_checked) def change_default_library_page(self, page): set_default_library_page(page) def showEvent(self, event): if self.parent.isVisible(): x = self.parent.x() + (self.parent.width() - self.width()) * 0.5 y = self.parent.y() + (self.parent.height() - self.height()) * 0.5 self.move(x, y) event.accept()
def _init_layout(self): """ Create the GUI widgets (but leave them empty). """ hostname_combobox = QComboBox(parent=self) self._hostname_combobox = hostname_combobox hostname_combobox.setEditable(True) hostname_combobox.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Maximum) for hostname in self._suggested_hostnames: hostname_combobox.addItem(hostname) # EventFilter is installed after everything else is initialized. (See below.) #hostname_combobox.installEventFilter(self) self._connect_button = QPushButton("Connect", parent=self, clicked=self._handle_new_hostname) hostname_layout = QHBoxLayout() hostname_layout.addWidget(hostname_combobox) hostname_layout.addWidget(self._connect_button) hostinfo_table = QTableWidget() hostinfo_table.setColumnCount(len(SERVER_INFO_FIELDS)) hostinfo_table.setHorizontalHeaderLabels(SERVER_INFO_FIELDS) hostinfo_table.horizontalHeader().setVisible(True) hostinfo_table.verticalHeader().setVisible(False) hostinfo_table.setRowCount(1) hostinfo_table.setItem(0, 0, QTableWidgetItem("Placeholder")) hostinfo_table.setVisible(False) hostinfo_table.resizeRowsToContents() hostinfo_table.horizontalHeader().setStretchLastSection(True) table_height = hostinfo_table.verticalHeader().sectionSize( 0) + hostinfo_table.rowHeight(0) hostinfo_table.resize(QSize(hostinfo_table.width(), table_height)) hostinfo_table.setMaximumSize(QSize(1000, table_height)) hostinfo_table.setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Fixed) host_layout = QVBoxLayout() host_layout.addLayout(hostname_layout) host_layout.addWidget(hostinfo_table) host_groupbox = QGroupBox("DVID Host", parent=self) host_groupbox.setLayout(host_layout) host_groupbox.setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Preferred) repo_treewidget = QTreeWidget(parent=self) repo_treewidget.setHeaderLabels( TREEVIEW_COLUMNS) # TODO: Add type, shape, axes, etc. repo_treewidget.setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Preferred) repo_treewidget.itemSelectionChanged.connect( self._handle_data_selection) data_layout = QVBoxLayout() data_layout.addWidget(repo_treewidget) data_groupbox = QGroupBox("Data Volumes", parent=self) data_groupbox.setLayout(data_layout) node_listwidget = QListWidget(parent=self) node_listwidget.setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Preferred) node_listwidget.itemSelectionChanged.connect(self._update_status) node_layout = QVBoxLayout() node_layout.addWidget(node_listwidget) node_groupbox = QGroupBox("Nodes", parent=self) node_groupbox.setLayout(node_layout) new_data_edit = QLineEdit(parent=self) new_data_edit.textEdited.connect(self._update_status) full_url_label = QLabel(parent=self) full_url_label.setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Maximum) text_flags = full_url_label.textInteractionFlags() full_url_label.setTextInteractionFlags(text_flags | Qt.TextSelectableByMouse) new_data_layout = QVBoxLayout() new_data_layout.addWidget(new_data_edit) new_data_groupbox = QGroupBox("New Data Volume", parent=self) new_data_groupbox.setLayout(new_data_layout) new_data_groupbox.setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Maximum) buttonbox = QDialogButtonBox(Qt.Horizontal, parent=self) buttonbox.setStandardButtons(QDialogButtonBox.Ok | QDialogButtonBox.Cancel) buttonbox.accepted.connect(self.accept) buttonbox.rejected.connect(self.reject) buttonbox.button(QDialogButtonBox.Ok).setEnabled(False) layout = QVBoxLayout() layout.addWidget(host_groupbox) layout.addWidget(data_groupbox) layout.addWidget(node_groupbox) if self._mode == "specify_new": layout.addWidget(new_data_groupbox) else: new_data_groupbox.hide() layout.addWidget(full_url_label) layout.addWidget(buttonbox) # Stretch factors layout.setStretchFactor(data_groupbox, 3) layout.setStretchFactor(node_groupbox, 1) self.setLayout(layout) self.setWindowTitle("Select DVID Volume") self.resize(1000, 1000) # Initially disabled data_groupbox.setEnabled(False) node_groupbox.setEnabled(False) new_data_groupbox.setEnabled(False) # Set tab order self.setTabOrder(hostname_combobox, repo_treewidget) self.setTabOrder(repo_treewidget, node_listwidget) self.setTabOrder(node_listwidget, buttonbox) # Save instance members self._hostinfo_table = hostinfo_table self._data_groupbox = data_groupbox self._node_groupbox = node_groupbox self._new_data_groupbox = new_data_groupbox self._repo_treewidget = repo_treewidget self._node_listwidget = node_listwidget self._new_data_edit = new_data_edit self._full_url_label = full_url_label self._buttonbox = buttonbox # Finally install eventfilter (after everything is initialized) hostname_combobox.installEventFilter(self)
def __init__( self ): # this is to start grid builder before .show ***note grid builder will require a array of data type called loginfo in the future*** super().__init__() #self.initUI() #this code runs GridBuilder ############################################################################# _widget = QWidget() layout = QGridLayout() layout.setContentsMargins(0, 0, 0, 0) layout.setSpacing(10) name_label = QLabel("Team Configuration") name_label.setMaximumWidth(150) name_label.setMaximumHeight(35) lead_check_button = QCheckBox("Lead?") lead_check_button.setMaximumWidth(150) layout_lead_ip = QHBoxLayout() ip_label = QLabel("Lead IP Address") ip_label.setMaximumWidth(150) ip_label.setMaximumHeight(25) ip_edit = QTextEdit() ip_edit.setMaximumWidth(300) ip_edit.setMaximumHeight(25) layout_lead_ip.addWidget(ip_label) layout_lead_ip.addWidget(ip_edit) layout_lead_ip.setSpacing(0) layout_connections = QHBoxLayout() connections_text_label = QLabel( "Number of Established connectons to lead") connections_text_label.setMaximumWidth(300) connections_text_label.setMaximumHeight(35) connections_label = QLabel("Number") connections_label.setMaximumWidth(150) connections_label.setMaximumHeight(35) layout_connections.addWidget(connections_text_label) layout_connections.addWidget(connections_label) layout_connections.setSpacing(0) connect_project_button = QPushButton("Connect") connect_project_button.setMaximumWidth(150) widget = QWidget() widget.setLayout(layout) layout.addWidget(name_label, 0, 0, 1, 2) layout.addWidget(lead_check_button, 1, 0, 1, 2) layout.addLayout(layout_lead_ip, 2, 0, 1, 2) layout.addLayout(layout_connections, 3, 0, 1, 2) layout.addWidget(connect_project_button, 4, 1) layout.setAlignment(Qt.AlignVCenter | Qt.AlignHCenter) widget.setLayout(layout) _layout = QVBoxLayout(_widget) _layout.addWidget(widget) _layout.setAlignment(Qt.AlignVCenter | Qt.AlignHCenter) self.setCentralWidget(_widget) ############################################################################# self.setGeometry(400, 400, 400, 400) self.setWindowTitle("Team Configuration")
def __init__(self): super().__init__() self.status_signal.connect(self.status_slot) self.message_signal.connect(self.message_slot) self.df_load_thread = None self.df_assign_thread = None main_layout = QVBoxLayout() main_layout.addWidget( QLabel('<b style="color:green">GUI interface to ' 'access pandas data-frame</b>')) select_file_layout = QHBoxLayout() select_file_layout.addWidget(QLabel("Choose File: ")) self.file_location = QLineEdit() select_file_layout.addWidget(self.file_location) self.file_type = QComboBox() self.file_type.addItems(["CSV", "EXCEL", "SQLITE"]) select_file_layout.addWidget(self.file_type) select_file = QPushButton("SELECT FILE") select_file.clicked.connect(self.load_df_clicked) select_file_layout.addWidget(select_file) main_layout.addLayout(select_file_layout) self.status = QLabel() main_layout.addWidget(self.status) main_layout.addWidget(QLabel("Column Names: ")) self.column_name = QTextEdit() main_layout.addWidget(self.column_name) variable_layout = QHBoxLayout() variable_layout.addWidget(QLabel("Variable Name: ")) self.variable_name = QLineEdit() variable_layout.addWidget(self.variable_name) save_variable = QPushButton("SAVE VARIABLE") save_variable.clicked.connect(self.save_variable_clicked) variable_layout.addWidget(save_variable) main_layout.addLayout(variable_layout) self.setLayout(main_layout)
def _createFirstScreen(self): vLayout = QVBoxLayout(self.centralWidget()) vLayout.setAlignment(Qt.AlignTop) vLayout.addWidget(QLabel()) hLayout = QHBoxLayout() hLayout.setSpacing(0) hLayout.setAlignment(Qt.AlignHCenter) formLayout = QFormLayout(self.centralWidget()) formLayout.setFormAlignment(Qt.AlignHCenter) formLayout.setLabelAlignment(Qt.AlignRight) btnGroup = QButtonGroup() btnGroup.setExclusive(True) title = QLabel() tPng = QPixmap("./graphics/ManageCraft.png") title.setPixmap(tPng) btn1 = QPushButton() btn1.setFixedSize(130, 40) btn1.setCheckable(True) btn1.setChecked(True) rcPng = QIcon("./graphics/RemoteBtnChecked.png") btn1.setIcon(rcPng) btn1.setIconSize(QSize(170, 40)) btn2 = QPushButton() btn2.setFixedSize(130, 40) btn2.setCheckable(True) btn2.setChecked(False) lcPng = QIcon("./graphics/LocalBtn.png") btn2.setIcon(lcPng) btn2.setIconSize(QSize(170, 40)) btn3 = QPushButton() btn3.setFixedSize(155, 45) cPng = QIcon("./graphics/ConnectBtn.png") btn3.setIcon(cPng) btn3.setIconSize(QSize(200, 40)) btn1.toggled.connect(self.remote) btnGroup.addButton(btn1) btn2.toggled.connect(self.local) btnGroup.addButton(btn2) btn3.clicked.connect(partial(self.browseR)) btn2.pressed.connect( partial(self.btnPressToggle, btn2, "LocalBtnChecked.png")) btn2.released.connect( partial(self.btnPressToggle, btn2, "LocalBtn.png")) btn3.pressed.connect( partial(self.btnPressToggle, btn3, "ConnectBtnChecked.png")) btn3.released.connect( partial(self.btnPressToggle, btn3, "ConnectBtn.png")) host = QLabel() hPng = QPixmap("./graphics/Host.png") host.setPixmap(hPng) user = QLabel() uPng = QPixmap("./graphics/Username.png") user.setPixmap(uPng) pas = QLabel() pPng = QPixmap("./graphics/Password.png") pas.setPixmap(pPng) formLayout.addRow(host, self.host) formLayout.addRow(user, self.user) formLayout.addRow(pas, self.pas) vLayout.addWidget(title, alignment=Qt.AlignCenter) hLayout.addWidget(btn1, alignment=Qt.AlignHCenter) hLayout.addWidget(btn2, alignment=Qt.AlignHCenter) vLayout.addLayout(hLayout) vLayout.addLayout(formLayout) vLayout.addWidget(btn3, alignment=Qt.AlignCenter) vLayout.addWidget(self.err, alignment=Qt.AlignHCenter) self.frameR.setLayout(vLayout) self.mainMenu = False self._createSecondScreen()
class Window(QWidget): def __init__(self): super(Window, self).__init__() self.mainLayout = QVBoxLayout() self.createGlWidgetLabels() self.createGlWidgets() self.spinboxC = self.createSlider("c", 4, 0, 100, 0.1, 1) self.spinboxDx = self.createSlider("dx", 0.1, 0.001, 1, 0.001, 3) self.spinboxDt = self.createSlider("dt", 1 / 60, 0.001, 1, 0.001, 3) self.spinboxAttenuation = self.createSlider("attenuation", 1, 0.5, 1, 0.00001, 5) self.spinboxTauEpsilon = self.createSlider("τ_ε", 1, 0, 10, 0.001, 3) self.spinboxTauSigma = self.createSlider("τ_σ", 1, 0, 10, 0.001, 3) self.spinboxAlpha = self.createSlider("α", 0, 0, 2, 0.001, 3) self.spinboxBeta = self.createSlider("β", 0, 0, 2, 0.001, 3) self.buttonReset = QPushButton("Reset") self.buttonReset.clicked.connect(self.glWidgetImplicit.reset) self.mainLayout.addWidget(self.buttonReset) self.setLayout(self.mainLayout) self.setWindowTitle("1D Wave") self.animate() def animate(self): self.timer = QTimer(self) self.timer.timeout.connect(self.glWidgetImplicit.update) self.timer.start(1000 / QApplication.primaryScreen().refreshRate()) def createGlWidgetLabels(self): layoutGlLabel = QHBoxLayout() label = QLabel("1D Fractional Zener Wave") label.setAlignment(Qt.AlignCenter) label.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed) layoutGlLabel.addWidget(label) self.mainLayout.addLayout(layoutGlLabel) def createGlWidgets(self): self.layoutGlWidget = QHBoxLayout() self.glWidgetImplicit = GLWidget() self.layoutGlWidget.addWidget(self.glWidgetImplicit) self.mainLayout.addLayout(self.layoutGlWidget) def createSlider(self, label, value, minimum, maximum, step, decimals): layout = QHBoxLayout() label = QLabel(label) label.setAlignment(Qt.AlignRight) layout.addWidget(label) spinbox = QDoubleSpinBox() spinbox.setValue(value) spinbox.setRange(minimum, maximum) spinbox.setSingleStep(step) spinbox.setDecimals(decimals) layout.addWidget(spinbox) self.mainLayout.addLayout(layout) spinbox.valueChanged.connect(self.setParameters) return spinbox def setParameters(self): self.setWave1dParameters(self.glWidgetImplicit) def setWave1dParameters(self, widget): widget.wave1d.setParameters( self.spinboxC.value(), self.spinboxDx.value(), self.spinboxDt.value(), self.spinboxAttenuation.value(), self.spinboxTauEpsilon.value(), self.spinboxTauSigma.value(), self.spinboxAlpha.value(), self.spinboxBeta.value(), )
def __init__(self, name, typeLoop, parent=None): super(defineTunnels, self).__init__(parent) if 'in' in name: self.setWindowTitle('Define input tunnels') else: self.setWindowTitle('Define output tunnels') self.setWindowFlags(self.windowFlags() & QtCore.Qt.WindowCloseButtonHint) self.adjustSize() listformat = ["int", "float", "str", "path", "bool"] if 'If' in typeLoop: self.list1 = ["array", "list", "simple"] self.list2 = ["array", "list", "simple"] else: if 'in' in name: self.list1 = ["array", "list"] self.list2 = ["list", "simple"] else: self.list1 = ["list", "simple"] self.list2 = ["array", "list"] self.vbox = QVBoxLayout(self) hbox = QHBoxLayout() label = QLabel("Tunnel Name : ") hbox.addWidget(label) label = QLineEdit(name) label.setDisabled(True) label.setAlignment(QtCore.Qt.AlignTop) hbox.addWidget(label) hbox2 = QHBoxLayout() self.comboFormat = QComboBox(self) self.comboFormat.addItems(listformat) hbox2.addWidget(self.comboFormat) hbox3 = QHBoxLayout() label = QLabel("Format left Tunnel ") hbox3.addWidget(label) self.comboLeft = QComboBox(self) self.comboLeft.addItems(self.list1) self.comboLeft.currentIndexChanged.connect(self.changeComboRight) hbox3.addWidget(self.comboLeft) hbox4 = QHBoxLayout() label = QLabel("Format right Tunnel ") hbox4.addWidget(label) self.comboRight = QLineEdit(self.list2[0]) self.comboRight.setEnabled(False) hbox4.addWidget(self.comboRight) buttonOk = QPushButton('Ok', self) buttonCancel = QPushButton('Cancel', self) hbox5 = QHBoxLayout() hbox5.addWidget(buttonOk) hbox5.addWidget(buttonCancel) buttonOk.clicked.connect(self.OK) buttonCancel.clicked.connect(self.CANCEL) self.vbox.addLayout(hbox) self.vbox.addLayout(hbox2) self.vbox.addLayout(hbox3) self.vbox.addLayout(hbox4) self.vbox.addLayout(hbox5)
def request_trezor_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) # KeepKey recovery doesn't need a word count if method == TIM_NEW: vbox.addWidget(gb) gb.setTitle(_("Select your seed length:")) bg = QButtonGroup() for i, count in enumerate([12, 18, 24]): rb = QRadioButton(gb) rb.setText(_("{} 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_mue.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())
class QtApplication(QWidget): globalStop = pyqtSignal() def __init__(self, dimension): super(QtApplication, self).__init__() self.mainLayout = QGridLayout() self.setLayout(self.mainLayout) self.ProcessingTest = False self.expertMode = False self.FwUnderUsed = '' self.FwDict = {} self.FwStatusVerboseDict = {} self.FPGAConfigDict = {} self.LogList = {} self.PYTHON_VERSION = str(sys.version).split(" ")[0] self.dimension = dimension self.HVpowersupply = PowerSupply(powertype="HV") self.LVpowersupply = PowerSupply(powertype="LV") self.setLoginUI() self.initLog() self.createLogin() def setLoginUI(self): self.setGeometry(300, 300, 400, 500) self.setWindowTitle('Phase2 Pixel Module Test GUI') if False and sys.platform.startswith("darwin"): QApplication.setStyle(QStyleFactory.create('macintosh')) QApplication.setPalette(QApplication.style().standardPalette()) elif sys.platform.startswith("linux") or sys.platform.startswith( "win") or sys.platform.startswith("darwin"): darkPalette = QPalette() darkPalette.setColor(QPalette.Window, QColor(53, 53, 53)) darkPalette.setColor(QPalette.WindowText, Qt.white) darkPalette.setColor(QPalette.Base, QColor(25, 25, 25)) darkPalette.setColor(QPalette.AlternateBase, QColor(53, 53, 53)) darkPalette.setColor(QPalette.ToolTipBase, Qt.darkGray) darkPalette.setColor(QPalette.ToolTipText, Qt.white) darkPalette.setColor(QPalette.Text, Qt.white) darkPalette.setColor(QPalette.Button, QColor(53, 53, 53)) darkPalette.setColor(QPalette.ButtonText, Qt.white) darkPalette.setColor(QPalette.BrightText, Qt.red) darkPalette.setColor(QPalette.Link, QColor(42, 130, 218)) darkPalette.setColor(QPalette.Highlight, QColor(42, 130, 218)) darkPalette.setColor(QPalette.HighlightedText, Qt.black) darkPalette.setColor(QPalette.Disabled, QPalette.Window, Qt.lightGray) darkPalette.setColor(QPalette.Disabled, QPalette.WindowText, Qt.gray) darkPalette.setColor(QPalette.Disabled, QPalette.Base, Qt.darkGray) darkPalette.setColor(QPalette.Disabled, QPalette.ToolTipBase, Qt.darkGray) darkPalette.setColor(QPalette.Disabled, QPalette.ToolTipText, Qt.white) darkPalette.setColor(QPalette.Disabled, QPalette.Text, Qt.gray) darkPalette.setColor(QPalette.Disabled, QPalette.Button, QColor(73, 73, 73)) darkPalette.setColor(QPalette.Disabled, QPalette.ButtonText, Qt.lightGray) darkPalette.setColor(QPalette.Disabled, QPalette.BrightText, Qt.lightGray) darkPalette.setColor(QPalette.Disabled, QPalette.Highlight, Qt.lightGray) darkPalette.setColor(QPalette.Disabled, QPalette.HighlightedText, Qt.gray) QApplication.setStyle(QStyleFactory.create('Fusion')) QApplication.setPalette(darkPalette) else: print("This GUI supports Win/Linux/MacOS only") self.show() def initLog(self): for index, (firmwareName, fwAddress) in enumerate(FirmwareList.items()): LogFileName = "{0}/Gui/.{1}.log".format(os.environ.get("GUI_dir"), firmwareName) try: logFile = open(LogFileName, "w") self.LogList[index] = LogFileName logFile.close() except: QMessageBox(None, "Error", "Can not create log files: {}".format(LogFileName)) ############################################################### ## Login page and related functions ############################################################### def createLogin(self): self.LoginGroupBox = QGroupBox("") self.LoginGroupBox.setCheckable(False) TitleLabel = QLabel( '<font size="12"> Phase2 Pixel Module Test </font>') TitleLabel.setFont(QFont("Courier")) TitleLabel.setMaximumHeight(30) UsernameLabel = QLabel("Username:"******"Password:"******"HostName:") if self.expertMode == False: self.HostName = QComboBox() self.HostName.addItems(DBServerIP.keys()) self.HostName.currentIndexChanged.connect(self.changeDBList) HostLabel.setBuddy(self.HostName) else: HostLabel.setText("HostIPAddr") self.HostEdit = QLineEdit('128.146.38.1') self.HostEdit.setEchoMode(QLineEdit.Normal) self.HostEdit.setMinimumWidth(150) self.HostEdit.setMaximumHeight(30) DatabaseLabel = QLabel("Database:") if self.expertMode == False: self.DatabaseCombo = QComboBox() self.DBNames = DBNames['All'] self.DatabaseCombo.addItems(self.DBNames) self.DatabaseCombo.setCurrentIndex(0) else: self.DatabaseEdit = QLineEdit('SampleDB') self.DatabaseEdit.setEchoMode(QLineEdit.Normal) self.DatabaseEdit.setMinimumWidth(150) self.DatabaseEdit.setMaximumHeight(30) self.disableCheckBox = QCheckBox("&Do not connect to DB") self.disableCheckBox.setMaximumHeight(30) if self.expertMode: self.disableCheckBox.toggled.connect(self.HostEdit.setDisabled) self.disableCheckBox.toggled.connect(self.DatabaseEdit.setDisabled) else: self.disableCheckBox.toggled.connect(self.HostName.setDisabled) self.disableCheckBox.toggled.connect( self.DatabaseCombo.setDisabled) self.expertCheckBox = QCheckBox("&Expert Mode") self.expertCheckBox.setMaximumHeight(30) self.expertCheckBox.setChecked(self.expertMode) self.expertCheckBox.clicked.connect(self.switchMode) button_login = QPushButton("&Login") button_login.setDefault(True) button_login.clicked.connect(self.checkLogin) layout = QGridLayout() layout.setSpacing(20) layout.addWidget(TitleLabel, 0, 1, 1, 3, Qt.AlignCenter) layout.addWidget(UsernameLabel, 1, 1, 1, 1, Qt.AlignRight) layout.addWidget(self.UsernameEdit, 1, 2, 1, 2) layout.addWidget(PasswordLabel, 2, 1, 1, 1, Qt.AlignRight) layout.addWidget(self.PasswordEdit, 2, 2, 1, 2) layout.addWidget(HostLabel, 3, 1, 1, 1, Qt.AlignRight) if self.expertMode: layout.addWidget(self.HostEdit, 3, 2, 1, 2) else: layout.addWidget(self.HostName, 3, 2, 1, 2) layout.addWidget(DatabaseLabel, 4, 1, 1, 1, Qt.AlignRight) if self.expertMode: layout.addWidget(self.DatabaseEdit, 4, 2, 1, 2) else: layout.addWidget(self.DatabaseCombo, 4, 2, 1, 2) layout.addWidget(self.disableCheckBox, 5, 2, 1, 1, Qt.AlignLeft) layout.addWidget(self.expertCheckBox, 5, 3, 1, 1, Qt.AlignRight) layout.addWidget(button_login, 6, 1, 1, 3) layout.setRowMinimumHeight(6, 50) layout.setColumnStretch(0, 1) layout.setColumnStretch(1, 1) layout.setColumnStretch(2, 2) layout.setColumnStretch(3, 1) self.LoginGroupBox.setLayout(layout) self.LogoGroupBox = QGroupBox("") self.LogoGroupBox.setCheckable(False) self.LogoGroupBox.setMaximumHeight(100) self.LogoLayout = QHBoxLayout() OSULogoLabel = QLabel() OSUimage = QImage("icons/osuicon.jpg").scaled(QSize(200, 60), Qt.KeepAspectRatio, Qt.SmoothTransformation) OSUpixmap = QPixmap.fromImage(OSUimage) OSULogoLabel.setPixmap(OSUpixmap) CMSLogoLabel = QLabel() CMSimage = QImage("icons/cmsicon.png").scaled(QSize(200, 60), Qt.KeepAspectRatio, Qt.SmoothTransformation) CMSpixmap = QPixmap.fromImage(CMSimage) CMSLogoLabel.setPixmap(CMSpixmap) self.LogoLayout.addWidget(OSULogoLabel) self.LogoLayout.addStretch(1) self.LogoLayout.addWidget(CMSLogoLabel) self.LogoGroupBox.setLayout(self.LogoLayout) self.mainLayout.addWidget(self.LoginGroupBox, 0, 0) self.mainLayout.addWidget(self.LogoGroupBox, 1, 0) def changeDBList(self): try: self.DBNames = DBNames[str(self.HostName.currentText())] self.DatabaseCombo.clear() self.DatabaseCombo.addItems(self.DBNames) self.DatabaseCombo.setCurrentIndex(0) except: print("Unable to change database") def switchMode(self): if self.expertMode: self.expertMode = False else: self.expertMode = True self.destroyLogin() self.createLogin() def destroyLogin(self): self.LoginGroupBox.deleteLater() self.LogoGroupBox.deleteLater() self.mainLayout.removeWidget(self.LoginGroupBox) def checkLogin(self): msg = QMessageBox() try: if self.expertMode == True: self.TryUsername = self.UsernameEdit.text() self.TryPassword = self.PasswordEdit.text() self.TryHostAddress = self.HostEdit.text() self.TryDatabase = self.DatabaseEdit.text() else: self.TryUsername = self.UsernameEdit.text() self.TryPassword = self.PasswordEdit.text() self.TryHostAddress = DBServerIP[str( self.HostName.currentText())] self.TryDatabase = str(self.DatabaseCombo.currentText()) except: print("Unexpected content detected ") try: if self.TryUsername == '': msg.information(None, "Error", "Please enter a valid username", QMessageBox.Ok) return if self.disableCheckBox.isChecked() == False: print("Connect to database...") self.connection = QtStartConnection(self.TryUsername, self.TryPassword, self.TryHostAddress, self.TryDatabase) if isActive(self.connection): self.destroyLogin() self.createMain() self.checkFirmware() else: self.connection = "Offline" self.destroyLogin() self.createMain() self.checkFirmware() except Exception as err: print("Failed to connect the database: {}".format(repr(err))) ############################################################### ## Login page and related functions (END) ############################################################### ############################################################### ## Main page and related functions ############################################################### def createMain(self): statusString, colorString = checkDBConnection(self.connection) self.FirmwareStatus = QGroupBox("Hello,{}!".format(self.TryUsername)) self.FirmwareStatus.setDisabled(True) DBStatusLabel = QLabel() DBStatusLabel.setText("Database connection:") DBStatusValue = QLabel() DBStatusValue.setText(statusString) DBStatusValue.setStyleSheet(colorString) self.StatusList = [] self.StatusList.append([DBStatusLabel, DBStatusValue]) try: for index, (firmwareName, fwAddress) in enumerate(FirmwareList.items()): FwNameLabel = QLabel() FwNameLabel.setText(firmwareName) FwStatusValue = QLabel() #FwStatusComment, FwStatusColor = self.getFwComment(firmwareName,fwAddress) #FwStatusValue.setText(FwStatusComment) #FwStatusValue.setStyleSheet(FwStatusColor) self.StatusList.append([FwNameLabel, FwStatusValue]) self.FwStatusVerboseDict[str(firmwareName)] = {} BeBoard = QtBeBoard() BeBoard.setBoardName(firmwareName) BeBoard.setIPAddress(FirmwareList[firmwareName]) BeBoard.setFPGAConfig(FPGAConfigList[firmwareName]) self.FwDict[firmwareName] = BeBoard except Exception as err: print("Failed to list the firmware: {}".format(repr(err))) self.UseButtons = [] StatusLayout = QGridLayout() for index, items in enumerate(self.StatusList): if index == 0: self.CheckButton = QPushButton("&Fw Check") self.CheckButton.clicked.connect(self.checkFirmware) StatusLayout.addWidget(self.CheckButton, index, 0, 1, 1) StatusLayout.addWidget(items[0], index, 1, 1, 1) StatusLayout.addWidget(items[1], index, 2, 1, 2) else: UseButton = QPushButton("&Use") UseButton.setDisabled(True) UseButton.toggle() UseButton.clicked.connect( lambda state, x="{0}".format(index - 1): self.switchFw(x)) if self.PYTHON_VERSION.startswith(("3.6", "3.7", "3.9")): UseButton.clicked.connect(self.update) if self.PYTHON_VERSION.startswith(("3.8")): UseButton.clicked.connect(self.destroyMain) UseButton.clicked.connect(self.createMain) UseButton.clicked.connect(self.checkFirmware) UseButton.setCheckable(True) self.UseButtons.append(UseButton) StatusLayout.addWidget(UseButton, index, 0, 1, 1) StatusLayout.addWidget(items[0], index, 1, 1, 1) StatusLayout.addWidget(items[1], index, 2, 1, 2) FPGAConfigButton = QPushButton("&Change uDTC firmware") if self.expertMode is False: FPGAConfigButton.setDisabled(True) FPGAConfigButton.setToolTip( 'Enter expert mode to change uDTC firmware') FPGAConfigButton.clicked.connect( lambda state, x="{0}".format(index - 1): self.setuDTCFw(x)) StatusLayout.addWidget(FPGAConfigButton, index, 4, 1, 1) SolutionButton = QPushButton("&Firmware Status") SolutionButton.clicked.connect(lambda state, x="{0}".format( index - 1): self.showCommentFw(x)) StatusLayout.addWidget(SolutionButton, index, 5, 1, 1) LogButton = QPushButton("&Log") LogButton.clicked.connect( lambda state, x="{0}".format(index - 1): self.showLogFw(x)) StatusLayout.addWidget(LogButton, index, 6, 1, 1) if self.FwUnderUsed != '': index = self.getIndex(self.FwUnderUsed, self.StatusList) self.occupyFw("{0}".format(index)) self.FirmwareStatus.setLayout(StatusLayout) self.FirmwareStatus.setDisabled(False) self.HVPowerRemoteControl = QCheckBox("Use HV power remote control") self.HVPowerRemoteControl.setChecked(True) self.HVPowerRemoteControl.toggled.connect(self.switchHVPowerPanel) self.HVPowerGroup = QGroupBox("HV Power") self.HVPowerLayout = QHBoxLayout() self.HVPowerStatusLabel = QLabel() self.HVPowerStatusLabel.setText("Choose HV Power:") self.HVPowerList = self.HVpowersupply.listResources() self.HVPowerCombo = QComboBox() self.HVPowerCombo.addItems(self.HVPowerList) self.HVPowerModelLabel = QLabel() self.HVPowerModelLabel.setText("HV Power Model:") self.HVPowerModelCombo = QComboBox() self.HVPowerModelCombo.addItems(HVPowerSupplyModel.keys()) self.HVPowerStatusValue = QLabel() self.UseHVPowerSupply = QPushButton("&Use") self.UseHVPowerSupply.clicked.connect(self.frozeHVPowerPanel) self.ReleaseHVPowerSupply = QPushButton("&Release") self.ReleaseHVPowerSupply.clicked.connect(self.releaseHVPowerPanel) self.ReleaseHVPowerSupply.setDisabled(True) self.HVPowerLayout.addWidget(self.HVPowerStatusLabel) self.HVPowerLayout.addWidget(self.HVPowerCombo) self.HVPowerLayout.addWidget(self.HVPowerModelLabel) self.HVPowerLayout.addWidget(self.HVPowerModelCombo) self.HVPowerLayout.addWidget(self.HVPowerStatusValue) self.HVPowerLayout.addStretch(1) self.HVPowerLayout.addWidget(self.UseHVPowerSupply) self.HVPowerLayout.addWidget(self.ReleaseHVPowerSupply) self.HVPowerGroup.setLayout(self.HVPowerLayout) self.LVPowerRemoteControl = QCheckBox("Use LV power remote control") self.LVPowerRemoteControl.setChecked(True) self.LVPowerRemoteControl.toggled.connect(self.switchLVPowerPanel) self.LVPowerGroup = QGroupBox("LV Power") self.LVPowerLayout = QHBoxLayout() self.LVPowerStatusLabel = QLabel() self.LVPowerStatusLabel.setText("Choose LV Power:") self.LVPowerList = self.LVpowersupply.listResources() self.LVPowerCombo = QComboBox() self.LVPowerCombo.addItems(self.LVPowerList) self.LVPowerModelLabel = QLabel() self.LVPowerModelLabel.setText("LV Power Model:") self.LVPowerModelCombo = QComboBox() self.LVPowerModelCombo.addItems(LVPowerSupplyModel.keys()) self.LVPowerStatusValue = QLabel() self.UseLVPowerSupply = QPushButton("&Use") self.UseLVPowerSupply.clicked.connect(self.frozeLVPowerPanel) self.ReleaseLVPowerSupply = QPushButton("&Release") self.ReleaseLVPowerSupply.clicked.connect(self.releaseLVPowerPanel) self.ReleaseLVPowerSupply.setDisabled(True) self.LVPowerLayout.addWidget(self.LVPowerStatusLabel) self.LVPowerLayout.addWidget(self.LVPowerCombo) self.LVPowerLayout.addWidget(self.LVPowerModelLabel) self.LVPowerLayout.addWidget(self.LVPowerModelCombo) self.LVPowerLayout.addWidget(self.LVPowerStatusValue) self.LVPowerLayout.addStretch(1) self.LVPowerLayout.addWidget(self.UseLVPowerSupply) self.LVPowerLayout.addWidget(self.ReleaseLVPowerSupply) self.LVPowerGroup.setLayout(self.LVPowerLayout) self.ArduinoGroup = ArduinoWidget() self.ArduinoGroup.stop.connect(self.GlobalStop) self.ArduinoControl = QCheckBox("Use arduino monitoring") self.ArduinoControl.setChecked(True) self.ArduinoControl.toggled.connect(self.switchArduinoPanel) self.MainOption = QGroupBox("Main") kMinimumWidth = 120 kMaximumWidth = 150 kMinimumHeight = 30 kMaximumHeight = 100 self.SummaryButton = QPushButton("&Status summary") self.SummaryButton.setDefault(True) self.SummaryButton.setMinimumWidth(kMinimumWidth) self.SummaryButton.setMaximumWidth(kMaximumWidth) self.SummaryButton.setMinimumHeight(kMinimumHeight) self.SummaryButton.setMaximumHeight(kMaximumHeight) self.SummaryButton.clicked.connect(self.openSummaryWindow) SummaryLabel = QLabel("Statistics of test status") self.NewTestButton = QPushButton("&New") self.NewTestButton.setMinimumWidth(kMinimumWidth) self.NewTestButton.setMaximumWidth(kMaximumWidth) self.NewTestButton.setMinimumHeight(kMinimumHeight) self.NewTestButton.setMaximumHeight(kMaximumHeight) self.NewTestButton.clicked.connect(self.openNewTest) self.NewTestButton.setDisabled(True) if self.FwUnderUsed != '': self.NewTestButton.setDisabled(False) if self.ProcessingTest == True: self.NewTestButton.setDisabled(True) NewTestLabel = QLabel("Open new test") self.ReviewButton = QPushButton("&Review") self.ReviewButton.setMinimumWidth(kMinimumWidth) self.ReviewButton.setMaximumWidth(kMaximumWidth) self.ReviewButton.setMinimumHeight(kMinimumHeight) self.ReviewButton.setMaximumHeight(kMaximumHeight) self.ReviewButton.clicked.connect(self.openReviewWindow) ReviewLabel = QLabel("Review all results") self.ReviewModuleButton = QPushButton("&Show Module") self.ReviewModuleButton.setMinimumWidth(kMinimumWidth) self.ReviewModuleButton.setMaximumWidth(kMaximumWidth) self.ReviewModuleButton.setMinimumHeight(kMinimumHeight) self.ReviewModuleButton.setMaximumHeight(kMaximumHeight) self.ReviewModuleButton.clicked.connect(self.openModuleReviewWindow) self.ReviewModuleEdit = QLineEdit('') self.ReviewModuleEdit.setEchoMode(QLineEdit.Normal) self.ReviewModuleEdit.setPlaceholderText('Enter Module ID') layout = QGridLayout() layout.addWidget(self.SummaryButton, 0, 0, 1, 1) layout.addWidget(SummaryLabel, 0, 1, 1, 2) layout.addWidget(self.NewTestButton, 1, 0, 1, 1) layout.addWidget(NewTestLabel, 1, 1, 1, 2) layout.addWidget(self.ReviewButton, 2, 0, 1, 1) layout.addWidget(ReviewLabel, 2, 1, 1, 2) layout.addWidget(self.ReviewModuleButton, 3, 0, 1, 1) layout.addWidget(self.ReviewModuleEdit, 3, 1, 1, 2) #################################################### # Functions for expert mode #################################################### if self.expertMode: self.DBConsoleButton = QPushButton("&DB Console") self.DBConsoleButton.setMinimumWidth(kMinimumWidth) self.DBConsoleButton.setMaximumWidth(kMaximumWidth) self.DBConsoleButton.setMinimumHeight(kMinimumHeight) self.DBConsoleButton.setMaximumHeight(kMaximumHeight) self.DBConsoleButton.clicked.connect(self.openDBConsole) DBConsoleLabel = QLabel("Console for database") layout.addWidget(self.DBConsoleButton, 4, 0, 1, 1) layout.addWidget(DBConsoleLabel, 4, 1, 1, 2) #################################################### # Functions for expert mode (END) #################################################### self.MainOption.setLayout(layout) self.AppOption = QGroupBox() self.AppLayout = QHBoxLayout() if self.expertMode is False: self.ExpertButton = QPushButton("&Enter Expert Mode") self.ExpertButton.clicked.connect(self.goExpert) self.RefreshButton = QPushButton("&Refresh") if self.PYTHON_VERSION.startswith("3.8"): self.RefreshButton.clicked.connect(self.disableBoxs) self.RefreshButton.clicked.connect(self.destroyMain) self.RefreshButton.clicked.connect(self.createMain) self.RefreshButton.clicked.connect(self.checkFirmware) elif self.PYTHON_VERSION.startswith(("3.7", "3.9")): self.RefreshButton.clicked.connect(self.disableBoxs) self.RefreshButton.clicked.connect(self.destroyMain) self.RefreshButton.clicked.connect(self.reCreateMain) #self.RefreshButton.clicked.connect(self.checkFirmware) self.RefreshButton.clicked.connect(self.enableBoxs) self.RefreshButton.clicked.connect(self.update) self.LogoutButton = QPushButton("&Logout") # Fixme: more conditions to be added if self.ProcessingTest: self.LogoutButton.setDisabled(True) self.LogoutButton.clicked.connect(self.destroyMain) self.LogoutButton.clicked.connect(self.setLoginUI) self.LogoutButton.clicked.connect(self.createLogin) self.ExitButton = QPushButton("&Exit") # Fixme: more conditions to be added if self.ProcessingTest: self.ExitButton.setDisabled(True) #self.ExitButton.clicked.connect(QApplication.quit) self.ExitButton.clicked.connect(self.close) if self.expertMode is False: self.AppLayout.addWidget(self.ExpertButton) self.AppLayout.addStretch(1) self.AppLayout.addWidget(self.RefreshButton) self.AppLayout.addWidget(self.LogoutButton) self.AppLayout.addWidget(self.ExitButton) self.AppOption.setLayout(self.AppLayout) self.mainLayout.addWidget(self.FirmwareStatus) self.mainLayout.addWidget(self.HVPowerGroup) self.mainLayout.addWidget(self.HVPowerRemoteControl) self.mainLayout.addWidget(self.LVPowerGroup) self.mainLayout.addWidget(self.LVPowerRemoteControl) self.mainLayout.addWidget(self.ArduinoGroup) self.mainLayout.addWidget(self.ArduinoControl) self.mainLayout.addWidget(self.MainOption) self.mainLayout.addWidget(self.AppOption) def reCreateMain(self): print("Refreshing the main page") self.createMain() self.checkFirmware() def disableBoxs(self): self.FirmwareStatus.setDisabled(True) self.MainOption.setDisabled(True) def enableBoxs(self): self.FirmwareStatus.setDisabled(False) self.MainOption.setDisabled(False) def destroyMain(self): self.FirmwareStatus.deleteLater() self.MainOption.deleteLater() self.AppOption.deleteLater() self.mainLayout.removeWidget(self.FirmwareStatus) self.mainLayout.removeWidget(self.HVPowerGroup) self.mainLayout.removeWidget(self.HVPowerRemoteControl) self.mainLayout.removeWidget(self.LVPowerGroup) self.mainLayout.removeWidget(self.LVPowerRemoteControl) self.mainLayout.removeWidget(self.ArduinoGroup) self.mainLayout.removeWidget(self.ArduinoControl) self.mainLayout.removeWidget(self.MainOption) self.mainLayout.removeWidget(self.AppOption) def openNewTest(self): FwModule = self.FwDict[self.FwUnderUsed] self.StartNewTest = QtStartWindow(self, FwModule) self.NewTestButton.setDisabled(True) self.LogoutButton.setDisabled(True) self.ExitButton.setDisabled(True) pass def openSummaryWindow(self): self.SummaryViewer = QtSummaryWindow(self) self.SummaryButton.setDisabled(True) def openReviewWindow(self): self.ReviewWindow = QtModuleReviewWindow(self) def openModuleReviewWindow(self): Module_ID = self.ReviewModuleEdit.text() if Module_ID != "": self.ModuleReviewWindow = QtModuleReviewWindow(self, Module_ID) else: QMessageBox.information(None, "Error", "Please enter a valid module ID", QMessageBox.Ok) def openDBConsole(self): self.StartDBConsole = QtDBConsoleWindow(self) def switchHVPowerPanel(self): if self.HVPowerRemoteControl.isChecked(): self.HVPowerGroup.setDisabled(False) else: self.HVPowerGroup.setDisabled(True) def frozeHVPowerPanel(self): # Block for HVPowerSupply operation self.HVpowersupply.setPowerModel( HVPowerSupplyModel[self.HVPowerModelCombo.currentText()]) self.HVpowersupply.setInstrument(self.HVPowerCombo.currentText()) self.HVpowersupply.getInfo() # self.HVpowersupply.TurnOn() # Block for GUI front-end statusString = self.HVpowersupply.getInfo() if statusString != "No valid device": self.HVPowerStatusValue.setStyleSheet("color:green") else: self.HVPowerStatusValue.setStyleSheet("color:red") if statusString: self.HVPowerCombo.setDisabled(True) self.HVPowerStatusValue.setText(statusString) self.UseHVPowerSupply.setDisabled(True) self.ReleaseHVPowerSupply.setDisabled(False) else: self.HVPowerStatusValue.setText(statusString) def releaseHVPowerPanel(self): self.HVpowersupply.TurnOff() self.HVPowerCombo.setDisabled(False) self.HVPowerStatusValue.setText("") self.UseHVPowerSupply.setDisabled(False) self.ReleaseHVPowerSupply.setDisabled(True) self.HVPowerList = self.HVpowersupply.listResources() def switchLVPowerPanel(self): if self.LVPowerRemoteControl.isChecked(): self.LVPowerGroup.setDisabled(False) else: self.LVPowerGroup.setDisabled(True) def frozeLVPowerPanel(self): # Block for LVPowerSupply operation self.LVpowersupply.setPowerModel( LVPowerSupplyModel[self.LVPowerModelCombo.currentText()]) self.LVpowersupply.setInstrument(self.LVPowerCombo.currentText()) self.LVpowersupply.getInfo() #self.LVpowersupply.TurnOn() # Block for GUI front-end statusString = self.LVpowersupply.getInfo() if statusString != "No valid device": self.LVPowerStatusValue.setStyleSheet("color:green") else: self.LVPowerStatusValue.setStyleSheet("color:red") if statusString: self.LVPowerCombo.setDisabled(True) self.LVPowerStatusValue.setText(statusString) self.UseLVPowerSupply.setDisabled(True) self.ReleaseLVPowerSupply.setDisabled(False) else: self.LVPowerStatusValue.setText("No valid device") def releaseLVPowerPanel(self): self.LVpowersupply.TurnOff() self.LVPowerCombo.setDisabled(False) self.LVPowerStatusValue.setText("") self.UseLVPowerSupply.setDisabled(False) self.ReleaseLVPowerSupply.setDisabled(True) self.LVPowerList = self.LVpowersupply.listResources() def switchArduinoPanel(self): if self.ArduinoControl.isChecked(): self.ArduinoGroup.setDisabled(False) else: self.ArduinoGroup.setDisabled(True) def checkFirmware(self): for index, (firmwareName, fwAddress) in enumerate(FirmwareList.items()): fileName = self.LogList[index] if firmwareName != self.FwUnderUsed: FwStatusComment, FwStatusColor, FwStatusVerbose = self.getFwComment( firmwareName, fileName) self.StatusList[index + 1][1].setText(FwStatusComment) self.StatusList[index + 1][1].setStyleSheet(FwStatusColor) self.FwStatusVerboseDict[str(firmwareName)] = FwStatusVerbose self.UseButtons[index].setDisabled(False) if self.FwUnderUsed != '': index = self.getIndex(self.FwUnderUsed, self.StatusList) self.StatusList[index + 1][1].setText("Connected") self.StatusList[index + 1][1].setStyleSheet("color: green") self.occupyFw("{0}".format(index)) def refreshFirmware(self): for index, (firmwareName, fwAddress) in enumerate(FirmwareList.items()): self.UseButtons[index].setDisabled(False) if self.FwUnderUsed != '': index = self.getIndex(self.FwUnderUsed, self.StatusList) self.occupyFw("{0}".format(index)) def getFwComment(self, firmwareName, fileName): comment, color, verboseInfo = fwStatusParser(self.FwDict[firmwareName], fileName) return comment, color, verboseInfo def getIndex(self, element, List2D): for index, item in enumerate(List2D): if item[0].text() == element: return index - 1 return -1 def switchFw(self, index): if self.UseButtons[int(index)].isChecked(): self.occupyFw(index) else: self.releaseFw(index) self.checkFirmware def occupyFw(self, index): if self.StatusList[int(index) + 1][1].text() == "Connected": self.NewTestButton.setDisabled(False) for i, button in enumerate(self.UseButtons): if i == int(index): button.setChecked(True) button.setText("&In use") button.setDisabled(False) self.CheckButton.setDisabled(True) self.FwUnderUsed = self.StatusList[i + 1][0].text() else: button.setDisabled(True) def releaseFw(self, index): for i, button in enumerate(self.UseButtons): if i == int(index): self.FwUnderUsed = '' button.setText("&Use") button.setDown(False) button.setDisabled(False) self.CheckButton.setDisabled(False) self.NewTestButton.setDisabled(True) else: button.setDisabled(False) def showCommentFw(self, index): fwName = self.StatusList[int(index) + 1][0].text() comment = self.StatusList[int(index) + 1][1].text() solution = FwStatusCheck[comment] verboseInfo = self.FwStatusVerboseDict[self.StatusList[int(index) + 1][0].text()] #QMessageBox.information(None, "Info", "{}".format(solution), QMessageBox.Ok) self.FwStatusWindow = QtFwStatusWindow(self, fwName, verboseInfo, solution) def showLogFw(self, index): fileName = self.LogList[int(index)] self.FwLogWindow = QtFwCheckWindow(self, fileName) def setuDTCFw(self, index): fwName = self.StatusList[int(index) + 1][0].text() firmware = self.FwDict[fwName] changeuDTCDialog = QtuDTCDialog(self, firmware) response = changeuDTCDialog.exec_() if response == QDialog.Accepted: firmware.setFPGAConfig(changeuDTCDialog.uDTCFile) self.checkFirmware() def goExpert(self): self.expertMode = True ## Authority check for expert mode self.destroyMain() self.createMain() self.checkFirmware() ############################################################### ## Global stop signal ############################################################### @QtCore.pyqtSlot() def GlobalStop(self): print("Critical status detected: Emitting Global Stop signal") self.globalStop.emit() self.HVpowersupply.TurnOff() self.releaseHVPowerPanel() self.LVpowersupply.TurnOff() self.releaseLVPowerPanel() ############################################################### ## Main page and related functions (END) ############################################################### def closeEvent(self, event): #Fixme: strict criterias for process checking should be added here: #if self.ProcessingTest == True: # QMessageBox.critical(self, 'Critical Message', 'There is running process, can not close!') # event.ignore() reply = QMessageBox.question(self, 'Window Close', 'Are you sure you want to exit?', QMessageBox.Yes | QMessageBox.No, QMessageBox.No) if reply == QMessageBox.Yes: print('Application terminated') self.HVpowersupply.TurnOff() self.LVpowersupply.TurnOff() os.system("rm -r {}/Gui/.tmp/*".format(os.environ.get("GUI_dir"))) event.accept() else: event.ignore()
def initUI(self): self.setGeometry(300, 300, 500, 250) self.setWindowTitle('Assignment6') name = QLabel('Name:') age = QLabel('Age:') score = QLabel('Score:') amount = QLabel('Amount:') key = QLabel('Key:') self.nameedit = QLineEdit() self.ageedit = QLineEdit() self.scoreedit = QLineEdit() self.amountedit = QLineEdit() self.keycombo = QComboBox(self) self.keycombo.addItem('Age') self.keycombo.addItem('Name') self.keycombo.addItem('Score') add = QPushButton('Add') delete = QPushButton('Del') find = QPushButton('Find') inc = QPushButton('Inc') show = QPushButton('Show') result = QLabel('Result:') self.resultedit = QTextEdit(self) #set Layout hbox = QHBoxLayout() hbox.addWidget(name) hbox.addWidget(self.nameedit) hbox.addWidget(age) hbox.addWidget(self.ageedit) hbox.addWidget(score) hbox.addWidget(self.scoreedit) hbox2 = QHBoxLayout() hbox2.addStretch(1) hbox2.addWidget(amount) hbox2.addWidget(self.amountedit) hbox2.addWidget(key) hbox2.addWidget(self.keycombo) hbox3 = QHBoxLayout() hbox3.addStretch(1) hbox3.addWidget(add) hbox3.addWidget(delete) hbox3.addWidget(find) hbox3.addWidget(inc) hbox3.addWidget(show) hbox4 = QHBoxLayout() hbox4.addWidget(result) hbox5 = QHBoxLayout() hbox5.addWidget(self.resultedit) vbox = QVBoxLayout() vbox.addStretch(5) vbox.addLayout(hbox) vbox.addLayout(hbox2) vbox.addLayout(hbox3) vbox.addLayout(hbox4) vbox.addLayout(hbox5) self.setLayout(vbox) #event connect add.clicked.connect(self.Add) delete.clicked.connect(self.Delete) find.clicked.connect(self.Find) inc.clicked.connect(self.Inc) show.clicked.connect(self.Show) self.setGeometry(300, 300, 500, 300) self.show()
def initUI(self): self.setGeometry(300, 300, 600, 200) self.setWindowTitle('CFTAC') self.setWindowIcon(QIcon('xbox_icon.ico')) instrumentGrid = QGridLayout() instrumentChoiceGroupBox = QGroupBox() scopeLabel = QLabel(self) scopeLabel.setText("Scope") instrumentGrid.addWidget(scopeLabel, 0, 0) self.scopeIDN = QLabel(self) self.scopeIDN.setText("Scope") instrumentGrid.addWidget(self.scopeIDN, 0, 1) waveformLabel = QLabel(self) waveformLabel.setText("Waveform Generator") instrumentGrid.addWidget(waveformLabel, 1, 0) self.waveformIDN = QLabel(self) self.waveformIDN.setText("Waveform") instrumentGrid.addWidget(self.waveformIDN, 1, 1) loadLabel = QLabel(self) loadLabel.setText("Chroma Load") instrumentGrid.addWidget(loadLabel, 2, 0) self.loadIDN = QLabel(self) self.loadIDN.setText("Chroma") instrumentGrid.addWidget(self.loadIDN, 2, 1) instrumentChoiceGroupBox.setLayout(instrumentGrid) sliderGrid = QGridLayout() sliderGroupBox = QGroupBox() self.sliderLabel = QLabel(self) self.sliderLabel.setText("Load Slam") sliderGrid.addWidget(self.sliderLabel, 0, 0) self.slamLoadSlider = QSlider(Qt.Horizontal, self) self.slamLoadSlider.setFocusPolicy(Qt.NoFocus) self.slamLoadSlider.setRange(1, 400) self.slamLoadSlider.setValue(50) self.slamLoadSlider.setGeometry(720, 150, 200, 20) self.slamLoadSlider.setEnabled(True) self.slamLoadSlider.valueChanged[int].connect(self.slamLoadChanged) self.slamLoad = QLabel(self) self.slamLoad.setText(str(self.slamLoadSlider.value()) + "amps") sliderGrid.addWidget(self.slamLoad, 0, 1) sliderGrid.addWidget(self.slamLoadSlider, 1, 0) self.onTimeLabel = QLabel(self) self.onTimeLabel.setText("On Time") sliderGrid.addWidget(self.onTimeLabel, 2, 0) self.onTimeSlider = QSlider(Qt.Horizontal, self) self.onTimeSlider.setFocusPolicy(Qt.NoFocus) self.onTimeSlider.setRange(15, 150) self.onTimeSlider.setValue(100) self.onTimeSlider.setGeometry(720, 150, 200, 20) self.onTimeSlider.setEnabled(True) self.onTimeSlider.valueChanged[int].connect(self.onTimeChanged) self.onTime = QLabel(self) self.onTime.setText(str(self.onTimeSlider.value()) + "ns") sliderGrid.addWidget(self.onTime, 2, 1) sliderGrid.addWidget(self.onTimeSlider, 3, 0) self.dutyLabel = QLabel(self) self.dutyLabel.setText("Duty Cycle") sliderGrid.addWidget(self.dutyLabel, 4, 0) self.dutyCycleSlider = QSlider(Qt.Horizontal, self) self.dutyCycleSlider.setFocusPolicy(Qt.NoFocus) self.dutyCycleSlider.setRange(1, 50) self.dutyCycleSlider.setValue(50) self.dutyCycleSlider.setGeometry(720, 150, 200, 20) self.dutyCycleSlider.setEnabled(True) self.dutyCycleSlider.valueChanged[int].connect(self.dutyCycleChanged) self.dutyCycle = QLabel(self) self.dutyCycle.setText(str(self.dutyCycleSlider.value()) + "%") sliderGrid.addWidget(self.dutyCycle, 4, 1) sliderGrid.addWidget(self.dutyCycleSlider, 5, 0) sliderGroupBox.setLayout(sliderGrid) autoTestGroupBox = QGroupBox() autoTestLayout = QHBoxLayout() self.microSlam = QCheckBox("Use Micro Slammer") self.microSlam.setChecked(True) autoTestLayout.addWidget(self.microSlam) self.autoTest = QCheckBox("Automated Test") self.autoTest.setChecked(False) self.autoTest.stateChanged.connect(self.autoTestCheck) autoTestLayout.addWidget(self.autoTest) self.tdcLabel = QLabel(self) self.tdcLabel.setText("TDC") autoTestLayout.addWidget(self.tdcLabel) self.tdcList = QLineEdit(self) self.tdcList.setEnabled(True) autoTestLayout.addWidget(self.tdcList) self.edcLabel = QLabel(self) self.edcLabel.setText("EDC") autoTestLayout.addWidget(self.edcLabel) self.edcList = QLineEdit(self) self.edcList.setEnabled(True) autoTestLayout.addWidget(self.edcList) autoTestGroupBox.setLayout(autoTestLayout) self.vregComboBox = QComboBox(self) self.vregComboBox.addItem("V_3P3_CFX") self.vregComboBox.addItem("V_CPUCORE") self.vregComboBox.addItem("V_DRAM1P8") self.vregComboBox.addItem("V_GFXCORE") self.vregComboBox.addItem("V_MEMIO") self.vregComboBox.addItem("V_MEMPHY") self.vregComboBox.addItem("V_SOC") self.vregComboBox.addItem("V_SOC1P8") startButtonGroupBox = QGroupBox() startButtonLayout = QHBoxLayout() self.startStopButton = QPushButton('Start Slam', self) self.startStopButton.setGeometry(800, 70, 180, 50) self.font = QFont() self.font.setBold(True) self.font.setPointSize(16) self.startStopButton.setFont(self.font) self.startStopButton.setStyleSheet('QPushButton {background-color: #A3C1DA; color: black;}') self.startStopButton.setText("Start Slam") self.startStopButton.clicked[bool].connect(self.startStopTest) startButtonLayout.addWidget(self.startStopButton) startButtonGroupBox.setLayout(startButtonLayout) quitButtonGroupBox = QGroupBox() quitButtonLayout = QHBoxLayout() self.font.setPointSize(12) self.quitButton = QPushButton('Quit', self) self.quitButton.setFont(self.font) self.quitButton.setGeometry(890, 260, 100, 30) self.quitButton.clicked[bool].connect(self.closeEventLocal) quitButtonLayout.addWidget(self.quitButton) quitButtonGroupBox.setLayout(quitButtonLayout) grid = QGridLayout() grid.setColumnStretch(0,5) grid.setColumnStretch(1,5) grid.addWidget(instrumentChoiceGroupBox, 0, 0) grid.addWidget(sliderGroupBox, 0, 1) grid.addWidget(self.vregComboBox, 1, 0) grid.addWidget(autoTestGroupBox, 1, 1) grid.addWidget(startButtonGroupBox, 2, 0) grid.addWidget(quitButtonGroupBox, 2, 1) self.setLayout(grid) self.show()
class ModManager(QMainWindow): def __init__(self, first, conn, cursor, steam, *args, **kwargs): super().__init__(*args, **kwargs) # ------DB connection--------------- self.conn = conn self.cursor = cursor self.steam = steam # ------Lists and disk files-------- self.get_Disk_Links() self.modList = list() self.steamIcon = QPixmap(pth.steam_pic) self.localIcon = QPixmap(pth.local_pic) self.filterList = list() # ------Logging--------------------- if not os.path.exists(pth.logs_folder): os.mkdir(pth.logs_folder) self.logs = logging.getLogger("St-PMMP") handler = logging.FileHandler(filename=pth.logs_mm, mode="a+") formatter = logging.Formatter('%(asctime)s: %(message)s') handler.setFormatter(formatter) self.logs.setLevel(logging.ERROR) self.logs.addHandler(handler) # ------Creating modlist------------ self.getModInfoFromFiles(first) self.getModList() # ------Backup list----------------- self.modListBackup = self.modList # ------UI setup-------------------- self.setupUI() def setupUI(self): # ------Window setup---------------- self.setMinimumSize(QSize(1200, 700)) self.setWindowTitle(l.r.manager) self.setWindowIcon(QIcon(pth.logo)) # ------Central widget-------------- self.centralwidget = QWidget(self) self.horizontalLayout = QHBoxLayout(self.centralwidget) self.additionalLayout = QVBoxLayout() self.filterLayout = QHBoxLayout() self.centralwidget.setMinimumSize(QSize(1200, 700)) self.centralwidget.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) # ------Table widget---------------- self.table = dnd.TableWidgetDragRows() self.table.setColumnCount(4) self.header = self.table.horizontalHeader() self.header.setSectionResizeMode(0, QHeaderView.ResizeToContents) self.header.setSectionResizeMode(1, QHeaderView.Stretch) self.header.setSectionResizeMode(2, QHeaderView.ResizeToContents) self.table.setColumnWidth(3, 20) self.table.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) self.table.setMinimumSize(QSize(800, 300)) self.additionalLayout.addWidget(self.table, 0) self.verticalLayout = QVBoxLayout() self.dataDisplay(self.modList) self.table.cellDoubleClicked.connect(self.modSwitch) self.table.cellClicked.connect(self.displayModData) self.table.setContextMenuPolicy(Qt.CustomContextMenu) self.table.customContextMenuRequested.connect(self.generateMenu) self.table.viewport().installEventFilter(self) self.table.setMouseTracking(True) self.current_hover = [0, 0] # ------Filter---------------------- self.filterLabel = QLabel(l.r.search, self.centralwidget) self.filterLine = QLineEdit('', self.centralwidget) self.filterLine.textChanged.connect(self.on_textChanged) self.filterClean = QPushButton(l.r.clean, self.centralwidget) self.filterClean.clicked.connect(lambda: self.filterLine.setText('')) self.filterClean.setMaximumSize(QSize(75, 30)) self.additionalLayout.addLayout(self.filterLayout) self.filterLayout.addWidget(self.filterLabel, 0) self.filterLayout.addWidget(self.filterLine, 1) self.filterLayout.addWidget(self.filterClean, 2) # ------Mod title label------------- self.modname = QLabel(l.r.modTitle, self.centralwidget) self.modname.setMinimumSize(QSize(320, 70)) newfont = QFont('Times', 18, QFont.Bold) self.modname.setFont(newfont) self.modname.setWordWrap(True) self.modname.setAlignment(Qt.AlignHCenter) self.verticalLayout.addWidget(self.modname, 0, Qt.AlignHCenter | Qt.AlignVCenter) # ------Preview pic----------------- self.pic = QLabel() self.printModPreview(pth.nologo) self.verticalLayout.addWidget(self.pic, 0, Qt.AlignHCenter | Qt.AlignVCenter) self.verticalLayout.addSpacerItem(QSpacerItem(20, 20, QSizePolicy.Fixed, QSizePolicy.Fixed)) # ------Mod description------------- self.textBrowser = QTextBrowser(self.centralwidget) newfont = QFont('Verdana', 13, QFont.Bold) self.textBrowser.setFont(newfont) self.verticalLayout.addWidget(self.textBrowser, 0, Qt.AlignHCenter | Qt.AlignVCenter) # ------Links for buttons----------- self.verticalLayout.addSpacerItem(QSpacerItem(20, 40, QSizePolicy.Minimum, QSizePolicy.Expanding)) self.linkButton = QPushButton(l.r.openBrowser, self.centralwidget) self.linkButton.setFixedSize(QSize(260, 30)) self.verticalLayout.addWidget(self.linkButton, 0, Qt.AlignHCenter | Qt.AlignVCenter) # ------------- self.linkSteamButton = QPushButton(l.r.openSteam, self.centralwidget) self.linkSteamButton.setFixedSize(QSize(260, 30)) self.verticalLayout.addWidget(self.linkSteamButton, 0, Qt.AlignHCenter | Qt.AlignVCenter) self.verticalLayout.addSpacerItem(QSpacerItem(40, 20, QSizePolicy.Fixed, QSizePolicy.Fixed)) # ------------- self.exitButton = QPushButton(l.r.exitLabel, self.centralwidget) self.exitButton.setFixedSize(QSize(260, 30)) self.verticalLayout.addWidget(self.exitButton, 0, Qt.AlignHCenter | Qt.AlignVCenter) self.verticalLayout.addSpacerItem(QSpacerItem(10, 10, QSizePolicy.Fixed, QSizePolicy.Fixed)) # ------Layout stuff---------------- self.horizontalLayout.addLayout(self.additionalLayout) self.horizontalLayout.addLayout(self.verticalLayout) self.setCentralWidget(self.centralwidget) # ------Menu------------------------ self.menu = self.menuBar() prMenu = self.menu.addMenu(l.r.programMenu) orderMenu = self.menu.addMenu(l.r.sortingMenu) self.foldersMenu = self.menu.addMenu(l.r.foldersMenu) backupMenu = self.menu.addMenu(l.r.backupsMenu) # ------Program--------------------- dumpACT = QAction(l.r.saveOrder, self) dumpACT.setShortcut('Ctrl+S') dumpACT.triggered.connect(self.dumpLoadOrder) prMenu.addAction(dumpACT) # ------------- reloadMods = QAction(l.r.reloadMods, self) reloadMods.setShortcut('Ctrl+S') reloadMods.triggered.connect(lambda: self.getModInfoFromFiles(0)) prMenu.addAction(reloadMods) # ------------- helpACT = QAction(l.r.helpLabel, self) helpACT.triggered.connect(self.getHelp) prMenu.addAction(helpACT) # ------------- self.exitACT = QAction(l.r.exitLabel, self) prMenu.addAction(self.exitACT) # ------Sorting--------------------- orderACT = QAction(l.r.sortAsc, self) orderACT.triggered.connect(lambda: self.sortByType(True)) orderMenu.addAction(orderACT) # ------------- order1ACT = QAction(l.r.sortDesc, self) order1ACT.triggered.connect(lambda: self.sortByType(False)) orderMenu.addAction(order1ACT) # ------Folders--------------------- gameFolder = QAction(l.r.openGameFolder, self) gameFolder.triggered.connect(lambda: self.folders_Opener(self.gamepath)) self.foldersMenu.addAction(gameFolder) # ------------- docsFolder = QAction(l.r.openGameDocs, self) docsFolder.triggered.connect(lambda: self.folders_Opener(self.doc_folder)) self.foldersMenu.addAction(docsFolder) # ------------- localModsFolder = QAction(l.r.openLocalMods, self) localModsFolder.triggered.connect(lambda: self.folders_Opener(self.doc_folder + 'mod/')) self.foldersMenu.addAction(localModsFolder) # ------------- if self.steam != '': steamModsFolder = QAction(l.r.openSteamMods, self) steamModsFolder.triggered.connect(lambda: self.folders_Opener(self.steamMM)) self.foldersMenu.addAction(steamModsFolder) # ------Backups--------------------- self.openBackupMenu = QAction(l.r.openBackups, self) backupMenu.addAction(self.openBackupMenu) # ------------- reload = QAction(l.r.reloadModlist, self) reload.triggered.connect(self.reloadOrder) backupMenu.addAction(reload) # ---------------------Setting paths of the game---------------------------------- def get_Disk_Links(self): self.doc_folder = os.path.join(os.path.expanduser('~'), 'Documents', 'Paradox Interactive', 'Stellaris') + '/' self.mod_folder = self.doc_folder + '/mod/' self.dlc_load = self.doc_folder + pth.dlc_load self.url = 'https://steamcommunity.com/sharedfiles/filedetails/?id=' self.steam_url = 'steam://url/CommunityFilePage/' # for future linux/mac releases def folders_Opener(self, path): if platform.system() == "Windows": os.startfile(path) elif platform.system() == "Darwin": Popen(["open", path]) else: Popen(["xdg-open", path]) # ---------------------Get modifications data------------------------------------ def getModInfoFromFiles(self, firstLaunch): try: self.modsToAdd = list() self.modsToCheck = list() self.newValuesForMods = list() allModList = glob(self.mod_folder + '*.mod') if self.steam != '': steamModList = glob(self.mod_folder + 'ugc_*.mod') localModList = [i for i in allModList + steamModList if i not in allModList or i not in steamModList] steamModList = glob(self.steam + '*/descriptor.mod') allModList = steamModList + localModList if firstLaunch == 1: prior = 0 for mod in allModList: self.getModData(mod, prior, 0) prior += 1 else: self.cursor.execute("SELECT COUNT (*) FROM mods") records = self.cursor.fetchall() prior = int(records[0][0]) self.cursor.execute("SELECT * FROM mods") records = self.cursor.fetchall() for mod in records: if mod[9] not in allModList: self.cursor.execute("DELETE FROM mods WHERE modfile = '" + mod[9] + "'") for mod in allModList: self.cursor.execute("SELECT EXISTS(SELECT name FROM mods WHERE modfile = '" + mod + "')") records = self.cursor.fetchall() if records[0][0] == 0: self.getModData(mod, prior, 0) prior += 1 else: self.modsToCheck.append(mod) for mod in self.modsToCheck: self.getModData(mod, prior, 1) self.cursor.executemany("INSERT INTO mods VALUES (?,?,?,?,?,?,?,?,?,?)", self.modsToAdd) self.cursor.executemany("UPDATE mods SET name = ?, version = ?, tags = ?, picture = ? WHERE modID = ?", self.newValuesForMods) self.conn.commit() except Exception as err: self.logs.error(err, exc_info=True) def getModData(self, mod, prior, update): try: with open(mod) as file: data = file.readlines() text = '' for i in range(len(data)): text += data[i] text.replace('replace_path', ' ') name = re.search(r'name=".*"', text) name = name.group(0) name = name[6:-1] path = re.search(r'path=".*"', text) try: path = path.group(0) path = path[6:-1] except AttributeError: path = '' if path == '': path = re.search(r'archive=".*"', text) try: path = path.group(0) path = path[9:-1] except AttributeError: path = '' version = re.search(r'supported_version=".*"', text) if version is None: version = re.search(r'version=".*"', text) try: version = version.group(0) version = version[9:-1] except AttributeError: version = '---' else: version = version.group(0) version = version[19:-1] remote_file_id = re.search(r'remote_file_id=".*"', text) if remote_file_id is None: if mod.find('workshop') != -1: source = 'steam' else: source = 'local' else: source = 'steam' try: remote_file_id = remote_file_id.group(0) remote_file_id = remote_file_id[16:-1] modID = remote_file_id except AttributeError: try: modID = path.split('mod/') modID = modID[1] except Exception: try: modID = mod.split('281990\\') modID = modID[1] modID = modID.split('\\') modID = modID[0] except Exception: modID = '---' picture = re.search(r'picture=".*"', text) try: picture = picture.group(0) picture = picture[9:-1] except AttributeError: picture = '' text = text.replace('\n', '') text = text.replace('\t', '') tags = re.search(r'tags={".*"}', text) try: tags = tags.group(0) tags = tags[7:-2] tags = tags.replace('""', '\n') if 'dependencies' in tags: tmp = tags.find('}') tags = tags[:tmp - 1] except AttributeError: tags = '' mods = [name, path, modID, version, tags, 0, source, prior, picture, mod] if update == 0: self.modsToAdd.append(mods) else: newVal = [name, version, tags, picture, modID] self.newValuesForMods.append(newVal) if (source == 'steam') and not (os.path.exists(self.mod_folder + 'ugc_' + modID + '.mod')): copy2(mod, self.mod_folder + 'ugc_' + modID + '.mod') newpath = mod.split('\\desc')[0] with open(self.mod_folder + 'ugc_' + modID + '.mod', mode='a+') as file2: newline = '\npath="' + newpath + '"' newline = newline.replace('\\', '/') newline = newline.replace('//', '/') file2.write(newline) except Exception as err: self.logs.error(err, exc_info=True) # ----------------------------Get final data------------------------------------- def getModList(self): try: self.cursor.execute("SELECT * FROM mods") records = self.cursor.fetchall() for row in records: mod = Mod(row[0], row[1], row[2], row[3], row[4], row[5], row[6], row[7], row[8], row[9]) self.modList.append(mod) self.modList.sort(key=prior) except Exception as err: self.logs.error(err, exc_info=True) # ----------------------Table and other visual----------------------------------- def dataDisplay(self, modList): self.modList = modList self.table.setRowCount(0) self.table.setRowCount(len(modList)) labels = [l.r.modIDLabel, l.r.name, l.r.version, l.r.modType] self.table.setHorizontalHeaderLabels(labels) for i in range(4): self.table.horizontalHeaderItem(i).setTextAlignment(Qt.AlignHCenter) counter = 0 for mod in modList: mod.prior = counter # ---------------------------------- self.table.setItem(counter, 0, QTableWidgetItem(mod.modID)) # ---------------------------------- self.table.setItem(counter, 1, QTableWidgetItem(mod.name)) # ---------------------------------- vs = QTableWidgetItem(mod.version) vs.setTextAlignment(Qt.AlignHCenter | Qt.AlignVCenter) self.table.setItem(counter, 2, vs) # ---------------------------------- image = QTableWidgetItem() if mod.source == 'steam': image.setData(Qt.DecorationRole, self.steamIcon) else: image.setData(Qt.DecorationRole, self.localIcon) image.setTextAlignment(Qt.AlignHCenter | Qt.AlignVCenter) self.table.setItem(counter, 3, image) # ---------------------------------- if mod.isEnabled == 1: for i in range(4): self.table.item(counter, i).setBackground(QColor.fromRgb(191, 245, 189)) # ---------------------------------- counter += 1 self.table.setEditTriggers(QTableWidget.NoEditTriggers) def printModPreview(self, image): if os.path.isfile(image): tmp = QPixmap(image) else: tmp = QPixmap(pth.nologo) tmp = tmp.scaled(256, 256, Qt.KeepAspectRatio) self.pic.setPixmap(tmp) # ----------------------Switching mods state------------------------------------- def modSwitch(self, row, column): # Single try: clr = self.modList[row].isEnabled if clr == 0: for i in range(4): self.table.item(row, i).setBackground(QColor.fromRgb(191, 245, 189)) self.modList[row].isEnabled = 1 else: for i in range(4): self.table.item(row, i).setBackground(QColor('white')) self.modList[row].isEnabled = 0 except Exception as err: self.logs.error(err, exc_info=True) def modSwitchAll(self, tp): # All try: for i in range(len(self.modList)): self.modList[i].isEnabled = tp if tp == 0: for j in range(4): self.table.item(i, j).setBackground(QColor('white')) else: for j in range(4): self.table.item(i, j).setBackground(QColor.fromRgb(191, 245, 189)) except Exception as err: self.logs.error(err, exc_info=True) # -----------------------------Moving mods--------------------------------------- def moveMod(self, row, column, tp): try: if tp == 0: newpos, okPressed = QInputDialog.getText(self, ' ', l.r.newPos, QLineEdit.Normal, '') try: newpos = int(newpos) if okPressed and newpos >= 0 and newpos < len(self.modList): if newpos > row: self.modList.insert(newpos, self.modList[row]) self.modList.pop(row) else: self.modList.insert(newpos, self.modList[row]) self.modList.pop(row + 1) self.dataDisplay(self.modList) else: QMessageBox.about(self, l.r.error, l.r.errorPos) except Exception: QMessageBox.about(self, l.r.error, l.r.errorPos) elif tp == 1 and row != 0: self.modList.insert(0, self.modList[row]) self.modList.pop(row + 1) self.dataDisplay(self.modList) elif tp == 2 and row != len(self.modList): self.modList.insert(len(self.modList), self.modList[row]) self.modList.pop(row) self.dataDisplay(self.modList) else: pass except Exception as err: self.logs.error(err, exc_info=True) # -----------------------------RMB event----------------------------------------- def eventFilter(self, source, event): try: if(event.type() == QEvent.MouseButtonPress and event.buttons() == Qt.RightButton and source is self.table.viewport()): item = self.table.itemAt(event.pos()) if item is not None: self.rcmenu = QMenu(self) # -------------------move mod------------------ mMod = QAction(l.r.moveTo, self) mMod.triggered.connect(lambda: self.moveMod(item.row(), item.column(), 0)) self.rcmenu.addAction(mMod) # -------------------move mod------------------ mMod = QAction(l.r.moveTop, self) mMod.triggered.connect(lambda: self.moveMod(item.row(), item.column(), 1)) self.rcmenu.addAction(mMod) # -------------------move mod------------------ mMod = QAction(l.r.moveBottom, self) mMod.triggered.connect(lambda: self.moveMod(item.row(), item.column(), 2)) self.rcmenu.addAction(mMod) # -------------------one mod------------------- enableMod = QAction(l.r.switchState, self) enableMod.triggered.connect(lambda: self.modSwitch(item.row(), item.column())) self.rcmenu.addAction(enableMod) # -------------------all mods-enable----------- enableAllMod = QAction(l.r.enableAll, self) enableAllMod.triggered.connect(lambda: self.modSwitchAll(1)) self.rcmenu.addAction(enableAllMod) # -------------------all mods-disable---------- disableAllMod = QAction(l.r.disableAll, self) disableAllMod.triggered.connect(lambda: self.modSwitchAll(0)) self.rcmenu.addAction(disableAllMod) return super(ModManager, self).eventFilter(source, event) except Exception as err: self.logs.error(err, exc_info=True) def generateMenu(self, pos): self.rcmenu.exec_(self.table.mapToGlobal(pos)) # -----------------------------Search method------------------------------------- @pyqtSlot(str) def on_textChanged(self, text): try: for item in range(len(self.modList)): if text in self.modList[item].name and text != '' and len(text) > 1: self.filterList.append(self.modList[item].modID) for i in range(4): self.table.item(item, i).setBackground(QColor('yellow')) else: if self.modList[item].modID in self.filterList: if self.modList[item].isEnabled == 1: for i in range(4): self.table.item(item, i).setBackground(QColor.fromRgb(191, 245, 189)) self.filterList.remove(self.modList[item].modID) else: for i in range(4): self.table.item(item, i).setBackground(QColor('white')) self.filterList.remove(self.modList[item].modID) except Exception as err: self.logs.error(err, exc_info=True) # -----------------------------Additional mod info------------------------------- def displayModData(self, row, column): try: self.modname.setText(self.modList[row].name) texttags = l.r.tagsForField texttags += self.modList[row].tags self.linkButton.disconnect() self.linkSteamButton.disconnect() self.linkButton.clicked.connect(lambda: webbrowser.open(self.url + str(self.modList[row].modID))) self.linkSteamButton.clicked.connect(lambda: webbrowser.open(self.steam_url + str(self.modList[row].modID))) if self.modList[row].source == 'local': self.linkButton.setVisible(0) self.linkSteamButton.setVisible(0) if self.modList[row].picture != '': self.printModPreview(self.doc_folder + self.modList[row].path + '\\' + self.modList[row].picture) else: pngList = glob(self.doc_folder + self.modList[row].path + '\*.png') jpgList = glob(self.doc_folder + self.modList[row].path + '\*.jpg') jpegList = glob(self.doc_folder + self.modList[row].path + '\*.jpeg') previewList = pngList + jpgList + jpegList if len(previewList) != 0: self.printModPreview(previewList[0]) else: self.printModPreview(pth.nologo) else: self.linkButton.setVisible(1) self.linkSteamButton.setVisible(1) if self.modList[row].picture != '': self.printModPreview(self.steam + self.modList[row].modID + '\\' + self.modList[row].picture) else: pngList = glob(self.steam + self.modList[row].modID + '\*.png') jpgList = glob(self.steam + self.modList[row].modID + '\*.jpg') jpegList = glob(self.steam + self.modList[row].modID + '\*.jpeg') previewList = pngList + jpgList + jpegList if len(previewList) != 0: self.printModPreview(previewList[0]) else: self.printModPreview(pth.nologo) self.textBrowser.setText(texttags) self.textBrowser.setMinimumSize(QSize(280, 35 + texttags.count('\n') * 25)) except Exception as err: self.logs.error(err, exc_info=True) # -----------------------------Technical stuff----------------------------------- def reloadOrder(self): try: self.modList = self.modListBackup self.dataDisplay(self.modList) except Exception as err: self.logs.error(err, exc_info=True) def sortByType(self, btype): self.modList.sort(key=sortedKey, reverse=btype) self.dataDisplay(self.modList) def dumpLoadOrder(self): try: self.saveInDB() self.saveInGame() self.writeLoadOrder() except Exception as err: self.logs.error(err, exc_info=True) def Diff(li1, li2): li_dif = [i for i in li1 + li2 if i not in li1 or i not in li2] return li_dif def getHelp(self): QMessageBox.about(self, l.r.helpLabel, l.r.helpContent) # ----------------------Saving modlist to the game and DB------------------------ def saveInDB(self): allFile = list() self.cursor.execute('DELETE FROM mods') for mod in self.modList: md = list() try: md.append(mod.name) md.append(mod.path) md.append(mod.modID) md.append(mod.version) md.append(mod.tags) md.append(mod.isEnabled) md.append(mod.source) md.append(mod.prior) md.append(mod.picture) md.append(mod.modfile) except KeyError: pass allFile.append(md) self.cursor.executemany("INSERT INTO mods VALUES (?,?,?,?,?,?,?,?,?,?)", allFile) self.conn.commit() def saveInGame(self): try: settingsFile = self.doc_folder + 'settings.txt' with open(settingsFile, 'r') as file: settingsList = file.readlines() text = '' for i in range(len(settingsList)): text += settingsList[i] active = re.search(r'last_mods={.*autosave', text, flags=re.DOTALL) newActive = 'last_mods={\n\t' for mod in self.modList: if mod.isEnabled == 1: if mod.source == 'steam': newActive += '"mod/ugc_' + mod.modID + '.mod"\n\t' else: newActive += '"mod/' + mod.modID + '.mod"\n\t' newActive = newActive[:-1] newActive += '}\nautosave' try: active = active.group(0) except AttributeError: active = re.search(r'autosave', text, flags=re.DOTALL) try: active = active.group(0) except AttributeError: pass text = text.replace(active, newActive) with open(settingsFile, 'w+', encoding='utf-8') as file: file.write(text) except Exception as err: self.logs.error(err, exc_info=True) def writeLoadOrder(self): try: data = {} loadFile = self.dlc_load with open(loadFile, 'r+') as json_file: data = json.load(json_file) summary = [] for mod in self.modList: if mod.isEnabled == 1: if mod.source == 'steam': modStr = 'mod/ugc_' + mod.modID + '.mod' else: modStr = 'mod/' + mod.modID + '.mod' summary.append(modStr) data['enabled_mods'] = summary with open(loadFile, 'w') as json_file: json.dump(data, json_file) except Exception as err: self.logs.error(err, exc_info=True)
class ListCellHeader(QLabel): def __init__(self, data: ProblemListCellData, parent=None): super().__init__(parent=parent) self._clicked_command = None self.height = data.height self.width = data.width self.setFixedHeight(self.height) self.setMinimumWidth(self.width) self.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed) self._init_UI() self.set_data(data) def _init_UI(self): self.layout = QHBoxLayout() self.layout.setSpacing(2) self.layout.setContentsMargins(20, 2, 20, 2) self._label_id = ListCellHeaderLabel('Id', self._clicked_command) self._label_R = ListCellHeaderLabel('R', self._clicked_command) self._label_R.setFixedWidth(32) self._label_I = ListCellHeaderLabel('I', self._clicked_command) self._label_I.setFixedWidth(32) self._label_C = ListCellHeaderLabel('C', self._clicked_command) self._label_C.setFixedWidth(32) self._label_grade = ListCellHeaderLabel('Grade', self._clicked_command) self._label_colour = ListCellHeaderLabel('Colour', self._clicked_command) self._label_sector = ListCellHeaderLabel('Sector', self._clicked_command) self._label_style0 = ListCellHeaderLabel('Styles', self._clicked_command) self._label_style1 = QLabel() self._label_style2 = QLabel() self._label_set_by = ListCellHeaderLabel('Setter', self._clicked_command) self._label_set_date = ListCellHeaderLabel('Set on', self._clicked_command) self._label_strip_date = ListCellHeaderLabel('Stripped on', self._clicked_command) self.layout.addWidget(self._label_id) self.layout.addWidget(self._label_R) self.layout.addWidget(self._label_I) self.layout.addWidget(self._label_C) self.layout.addWidget(self._label_grade) self.layout.addWidget(self._label_colour) self.layout.addWidget(self._label_sector) self.layout.addWidget(self._label_style0) self.layout.addWidget(self._label_style1) self.layout.addWidget(self._label_style2) self.layout.addWidget(self._label_set_by) self.layout.addWidget(self._label_set_date) self.layout.addWidget(self._label_strip_date) self.setLayout(self.layout) def set_data(self, data: ProblemListCellData): self._data = data self._set_colours(self._data.bg_colour, self._data.text_colour) self._add_mouse_effect() def _set_colours(self, colour: Colour, text_colour: Colour): self.setAutoFillBackground(True) pal = QPalette() pal.setColor(QPalette.Window, QColor(colour.red, colour.green, colour.blue)) pal.setColor( QPalette.WindowText, QColor(text_colour.red, text_colour.green, text_colour.blue)) self.setPalette(pal) def _add_mouse_effect(self): self.setFocusPolicy(Qt.StrongFocus) self.enterEvent = self._add_hover_effect self.leaveEvent = self._remove_hover_effect def _add_hover_effect(self, event): self._set_colours(self._data.hover_colour, self._data.text_colour) def _remove_hover_effect(self, event): self._set_colours(self._data.bg_colour, self._data.text_colour) def set_clicked_command(self, command): self._clicked_command = command self._label_id.set_clicked_command(command) self._label_R.set_clicked_command(command) self._label_I.set_clicked_command(command) self._label_C.set_clicked_command(command) self._label_grade.set_clicked_command(command) self._label_colour.set_clicked_command(command) self._label_style0.set_clicked_command(command) self._label_set_by.set_clicked_command(command) self._label_set_date.set_clicked_command(command) self._label_strip_date.set_clicked_command(command)
def initUI(self): layout = QHBoxLayout() i = 0 layout.addWidget(self.index, sizes[i]) i += 1 layout.addWidget(self.name, sizes[i]) i += 1 layout.addWidget(self.freq, sizes[i]) i += 1 layout.addWidget(self.amp, sizes[i]) i += 1 layout.addWidget(self.freq2, sizes[i]) i += 1 layout.addWidget(self.amp2, sizes[i]) i += 1 layout.addWidget(self.mode, sizes[i]) i += 1 layout.addWidget(self.wForm, sizes[i]) i += 1 layout.addWidget(self.lower, sizes[i]) i += 1 layout.addWidget(self.upper, sizes[i]) i += 1 layout.addWidget(self.rise, sizes[i]) i += 1 layout.addWidget(self.fall, sizes[i]) i += 1 layout.addWidget(self.length, sizes[i]) i += 1 layout.addWidget(self.delBtn, sizes[i]) i += 1 self.setLayout(layout)
def update_layout(self): disabled_text = None window = self.window() if hasattr(window, "parent_wallet"): wallet = self.get_wallet() if wallet.is_deterministic(): grid = QGridLayout() grid.setColumnStretch(0, 1) grid.setColumnStretch(4, 1) self.intro_label = QLabel("") self.intro_label.setTextFormat(Qt.RichText) self.intro_label.setMinimumWidth(600) self.intro_label.setWordWrap(True) self.split_button = QPushButton(_("Split")) self.split_button.setMaximumWidth(120) self.split_button.clicked.connect( self._on_split_button_clicked) help_content = "".join([ "<ol>", "<li>", _("Frozen coins will not be included in any split you make. You can use the " "Coins tab to freeze or unfreeze selected coins, and by doing so only split " "chosen amounts of your coins at a time. The View menu can be used to toggle " "tabs."), "</li>", "<li>", _("In order to prevent abuse, the faucet will limit how often you can obtain " "dust to split with. But that's okay, you can wait and split more coins. " "Or, if you are not concerned with your coins being linked, you can split " "dust from your already split coins, and use that to split further subsets." ), "</li>", "</ol>", ]) button_row = QHBoxLayout() button_row.addWidget(self.split_button) button_row.addWidget( util.HelpButton(help_content, textFormat=Qt.RichText, title="Additional Information")) grid.addWidget(self.intro_label, 0, 1, 1, 3) # grid.addWidget(balance_widget, 2, 1, 1, 3, Qt.AlignHCenter) grid.addLayout(button_row, 2, 1, 1, 3, Qt.AlignHCenter) vbox = QVBoxLayout() vbox.addStretch(1) vbox.addLayout(grid) vbox.addStretch(1) self.update_balances() else: disabled_text = _( "This is not the type of wallet that generate new addresses, " + "and therefore it cannot be used for <br/>coin-splitting. Create a new " + "standard wallet in ElectrumSV and send your coins there, then<br/>split " + "them.") else: disabled_text = _("Wallet not loaded, change tabs and come back.") if disabled_text is not None: label = QLabel(disabled_text) hbox = QHBoxLayout() hbox.addWidget(label, 0, Qt.AlignHCenter | Qt.AlignVCenter) vbox = QVBoxLayout() vbox.addLayout(hbox) # If the tab is already laid out, it's current layout needs to be # reparented/removed before we can replace it. existingLayout = self.layout() if existingLayout: QWidget().setLayout(existingLayout) self.setLayout(vbox)
def _init_UI(self): layout = QHBoxLayout() layout.setSpacing(2) layout.setContentsMargins(20, 2, 20, 2) self._label_id = QLabel() self._label_id.setAlignment(Qt.AlignLeft | Qt.AlignVCenter) self._label_R = QLabel() self._label_R.setFixedWidth(32) self._label_R.setAlignment(Qt.AlignLeft | Qt.AlignVCenter) self._label_I = QLabel() self._label_I.setFixedWidth(32) self._label_I.setAlignment(Qt.AlignLeft | Qt.AlignVCenter) self._label_C = QLabel() self._label_C.setFixedWidth(32) self._label_C.setAlignment(Qt.AlignLeft | Qt.AlignVCenter) self._label_grade = QLabel() self._label_grade.setAlignment(Qt.AlignLeft | Qt.AlignVCenter) self._label_colour = QLabel() self._label_colour.setAlignment(Qt.AlignLeft | Qt.AlignVCenter) self._label_sector = QLabel() self._label_sector.setAlignment(Qt.AlignLeft | Qt.AlignVCenter) self._label_style0 = QLabel() self._label_style0.setAlignment(Qt.AlignLeft | Qt.AlignVCenter) self._label_style1 = QLabel() self._label_style1.setAlignment(Qt.AlignLeft | Qt.AlignVCenter) self._label_style2 = QLabel() self._label_style2.setAlignment(Qt.AlignLeft | Qt.AlignVCenter) self._label_set_by = QLabel() self._label_set_by.setAlignment(Qt.AlignLeft | Qt.AlignVCenter) self._label_set_date = QLabel() self._label_set_date.setAlignment(Qt.AlignLeft | Qt.AlignVCenter) self._label_strip_date = QLabel() self._label_strip_date.setAlignment(Qt.AlignLeft | Qt.AlignVCenter) layout.addWidget(self._label_id) layout.addWidget(self._label_R) layout.addWidget(self._label_I) layout.addWidget(self._label_C) layout.addWidget(self._label_grade) layout.addWidget(self._label_colour) layout.addWidget(self._label_sector) layout.addWidget(self._label_style0) layout.addWidget(self._label_style1) layout.addWidget(self._label_style2) layout.addWidget(self._label_set_by) layout.addWidget(self._label_set_date) layout.addWidget(self._label_strip_date) self.setLayout(layout)
def initUI(self): self.setGeometry(500, 500, 500, 220) self.setWindowTitle('杀毒测试-打包工具') self.setObjectName("window") ##设置及选择安装包的路径 lbl1 = QLabel("安装包路径:", self) lbl1.setFixedSize(90, 25) self.edit1 = QLineEdit(self) self.edit1.setText(self.fileName) btn1 = QPushButton("选择目录", self) btn1.clicked.connect(self.showFile) ##设置及选择存放压缩包的路径 lbl2 = QLabel("压缩包存放路径:", self) lbl2.setFixedSize(90, 25) self.edit2 = QLineEdit(self) btn2 = QPushButton("选择目录", self) btn2.clicked.connect(self.showDestFile) ##设置需要压缩文件的大小 lbl3 = QLabel("设置大小:", self) lbl3.setFixedSize(90, 25) edit3 = QLineEdit(self) edit3.textEdited[str].connect(self.onFileSizeChanged) lbl31 = QLabel("如1K则输入1024", self) ##设置需要过滤的文件格式 lbl4 = QLabel("设置要过滤的文件格式:", self) lbl4.setFixedSize(140, 30) edit4 = QLineEdit(self) edit4.textEdited[str].connect(self.onChanged) lbl41 = QLabel("如dll、exe", self) ##选择需要压缩的格式 lbl5 = QLabel("选择压缩格式:", self) lbl5.setFixedSize(90, 25) self.combox = QComboBox(self) self.combox.insertItem(0, "zip") self.combox.insertItem(1, "rar") ##设置确定及取消键 btn6 = QPushButton("确定", self) btn6.clicked.connect(self.DoExcute) btn7 = QPushButton("取消", self) btn7.clicked.connect(self.close) ##设置布局格式 hbox1 = QHBoxLayout() # 水平布局 hbox1.addWidget(lbl1) hbox1.addWidget(self.edit1) hbox1.addWidget(btn1) hbox2 = QHBoxLayout() # 水平布局 hbox2.addWidget(lbl2) hbox2.addWidget(self.edit2) hbox2.addWidget(btn2) hbox3 = QHBoxLayout() # 水平布局 hbox3.addWidget(lbl3) hbox3.addWidget(edit3) hbox3.addWidget(lbl31) hbox4 = QHBoxLayout() # 水平布局 hbox4.addWidget(lbl4) hbox4.addWidget(edit4) hbox4.addWidget(lbl41) hbox5 = QHBoxLayout() # 水平布局 hbox5.addWidget(lbl5) hbox5.addWidget(self.combox) hbox6 = QHBoxLayout() # 水平布局 hbox6.addStretch() hbox6.addWidget(btn6) hbox6.addWidget(btn7) vbox = QVBoxLayout() # 垂直布局 vbox.addLayout(hbox1) vbox.addLayout(hbox2) vbox.addLayout(hbox3) vbox.addLayout(hbox4) vbox.addLayout(hbox5) vbox.addLayout(hbox6) self.setLayout(vbox) self.show()
def request_trezor_init_settings(self, wizard, method, model): 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()) gb = QGroupBox() hbox1 = QHBoxLayout() gb.setLayout(hbox1) vbox.addWidget(gb) gb.setTitle(_("Select your seed length:")) bg_numwords = QButtonGroup() for i, count in enumerate([12, 18, 24]): rb = QRadioButton(gb) rb.setText(_("%d words") % count) bg_numwords.addButton(rb) bg_numwords.setId(rb, i) hbox1.addWidget(rb) rb.setChecked(True) cb_pin = QCheckBox(_('Enable PIN protection')) cb_pin.setChecked(True) vbox.addWidget(WWLabel(RECOMMEND_PIN)) vbox.addWidget(cb_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) # ask for recovery type (random word order OR matrix) if method == TIM_RECOVER and not model == 'T': gb_rectype = QGroupBox() hbox_rectype = QHBoxLayout() gb_rectype.setLayout(hbox_rectype) 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, RECOVERY_TYPE_SCRAMBLED_WORDS) hbox_rectype.addWidget(rb1) rb1.setChecked(True) rb2 = QRadioButton(gb_rectype) rb2.setText(_('Matrix')) bg_rectype.addButton(rb2) bg_rectype.setId(rb2, RECOVERY_TYPE_MATRIX) hbox_rectype.addWidget(rb2) else: bg_rectype = None wizard.exec_layout(vbox, next_enabled=next_enabled) item = bg_numwords.checkedId() pin = cb_pin.isChecked() recovery_type = bg_rectype.checkedId() if bg_rectype else None return (item, name.text(), pin, cb_phrase.isChecked(), recovery_type)
class ApplicationWindow(QMainWindow): def __init__(self): super().__init__() self.currentPath = sys.path[0] # 程序运行的路径 self.initUI() self.xTrain = None def initUI(self): self.setWindowIcon(QIcon(r'G:\myRepostory\graduateProject\logo\xjtu.jpg')) #菜单 #Qaction openFileAct = QAction('&打开',self,triggered = self.openFile) openFileAct.setShortcut('Ctrl+O') exitAct = QAction('&退出',self,triggered=self.fileQuit) exitAct.setShortcut('Ctrl+Q') menubar = self.menuBar() #开始菜单 fileMenu = menubar.addMenu('&开始') fileMenu.addAction(openFileAct) fileMenu.addAction(exitAct) #方法 #帮助 helpMenu = menubar.addMenu('&帮助') aboutAction = QAction('&关于',self,triggered = self.about) helpMenu.addAction(aboutAction) #状态栏 self.statusBar().showMessage('准备就绪',2000) #主界面布局 self.main_widget = QWidget(self) # mainFunctionLabel = QLabel('命令') importButton = QPushButton("导入数据") importButton.clicked.connect(self.loadData) startButton = QPushButton('开始') startButton.clicked.connect(self.startSelection) stopButton = QPushButton('停止') stopButton.clicked.connect(self.stopSelection) plotButton = QPushButton('绘图') plotButton.clicked.connect(self.plotPic) exitButton = QPushButton('退出') exitButton.clicked.connect(self.fileQuit) self.drawPic = DynamicDrawMachines(self.main_widget,width=5,height=4,dpi=100) self.hboxButtonBox = QGroupBox('命令') self.hboxButton = QHBoxLayout() self.hboxButton.addWidget(importButton) self.hboxButton.addWidget(startButton) self.hboxButton.addWidget(stopButton) self.hboxButton.addWidget(plotButton) self.hboxButton.addWidget(exitButton) self.hboxButtonBox.setLayout(self.hboxButton) self.gboxAlgo = QGridLayout() experNumLabel = QLabel('训练集比例') self.trainPTxt = QLineEdit() self.trainPTxt.setText('0.8') self.trainPTxt.setFixedWidth(100) algorithmsLable = QLabel('算法') self.availableAlgos = ['PLS','RReliefF','UVE-PLS','SA-PLS','GA-PLS','ACO-PLS','LASSO','Elastic Net','FP-Tree-PLS'] self.algorithmBlock = QComboBox() self.algorithmBlock.insertItems(1,self.availableAlgos) self.algorithmBlock.currentIndexChanged.connect(self.changeAlgorithm) self.changeParameter = QPushButton('修改算法参数') self.changeParameter.clicked.connect(self.changeAlgoParameter) self.gboxAlgoBox = QGroupBox('算法') self.gboxAlgo.addWidget(algorithmsLable, 0, 0) self.gboxAlgo.addWidget(self.algorithmBlock, 0, 1) self.gboxAlgo.addWidget(self.changeParameter,0,2) self.gboxAlgo.addWidget(experNumLabel,0,3) self.gboxAlgo.addWidget(self.trainPTxt,0,4) self.gboxAlgoBox.setLayout(self.gboxAlgo) analysisLabel = QLabel('分析结果') rmsecvLabel = QLabel('RMSECV') rmsetLabel = QLabel('RMSET') rmsepLabel = QLabel('RMSEP') r2cvLabel = QLabel('R2CV') r2pLabel = QLabel('R2P') CRlabel = QLabel('CR') self.numrmsecvLabel = QLabel('0') self.numrmsetLabel = QLabel('0') self.numrmsepLabel = QLabel('0') self.numr2cvLabel = QLabel('1') self.numr2pLabel = QLabel('1') self.numCRlabel = QLabel('1') self.gboxAnalysisBox = QGroupBox('分析结果') self.gboxAnalysis = QGridLayout() # self.gboxAnalysis.addWidget(analysisLabel,0,0) self.gboxAnalysis.addWidget(rmsecvLabel,1,0) self.gboxAnalysis.addWidget(rmsetLabel,1,1) self.gboxAnalysis.addWidget(rmsepLabel,1,2) self.gboxAnalysis.addWidget(r2cvLabel,1,3) self.gboxAnalysis.addWidget(r2pLabel,1,4) self.gboxAnalysis.addWidget(CRlabel,1,5) self.gboxAnalysis.addWidget(self.numrmsecvLabel, 2, 0) self.gboxAnalysis.addWidget(self.numrmsetLabel, 2, 1) self.gboxAnalysis.addWidget(self.numrmsepLabel, 2, 2) self.gboxAnalysis.addWidget(self.numr2cvLabel, 2, 3) self.gboxAnalysis.addWidget(self.numr2pLabel, 2, 4) self.gboxAnalysis.addWidget(self.numCRlabel, 2, 5) self.gboxAnalysisBox.setLayout(self.gboxAnalysis) self.vboxButton = QVBoxLayout(self.main_widget) # self.vboxButton.addWidget(mainFunctionLabel) # self.vboxButton.addLayout(self.hboxButton) self.vboxButton.addWidget(self.hboxButtonBox) # self.vboxButton.addLayout(self.gboxAlgo) self.vboxButton.addWidget(self.gboxAlgoBox) self.vboxButton.addWidget(self.drawPic) # self.vboxButton.addLayout(self.gboxAnalysis) self.vboxButton.addWidget(self.gboxAnalysisBox) self.setLayout(self.vboxButton) self.main_widget.setFocus() self.setCentralWidget(self.main_widget) # 设置分辨率 self.setGeometry(300,300,600,700) self.show() #更改参数窗口 # self.changeParaWindow = changeParaWindow() # self.changeParaWindow.setWindowTitle("修改参数") def about(self): QMessageBox.about(self, "关于", """ sol yang 2018 """ ) def noDataWarning(self): QMessageBox.about(self,"没有数据", """ 请先读取数据 """) def openFile(self): fname = QFileDialog.getOpenFileName(self, '打开文件', self.currentPath,"CSV Files (*.csv);;Excel File (*.xlsx);;所有文件 (*)") if fname[0]: f = open(fname[0], 'r') with f: data = f.read() def fileQuit(self): self.close() def closeEvent(self, ce): self.fileQuit() def loadData(self): self.statusBar().showMessage('正在加载数据', 2000) ''' read data ''' self.CO, self.CO2, self.CH4, self.specData = readData() d = pd.read_excel('./data/NONO2SO2.xlsx') lines = d.shape[0] self.NO = d['NO'].as_matrix().reshape(lines, 1) self.NO2 = d['NO2'].as_matrix().reshape(lines, 1) self.SO2 = d['SO2'].as_matrix().reshape(lines, 1) self.specData2 = d.iloc[:, 4:].as_matrix() self.statusBar().showMessage('加载数据完成', 2000) ''' split the data set If int, random_state is the seed used by the random number generator; If RandomState instance, random_state is the random number generator; If None, the random number generator is the RandomState instance used by np.random. ''' self.xTrainOrigin, self.xTestOrigin, self.yTrainOrigin, self.yTestOrigin = \ train_test_split(self.specData2, self.SO2, test_size=0.2, random_state=42) ''' 数据预处理 ''' # mean removal self.scalerX = preprocessing.StandardScaler().fit(self.xTrainOrigin) self.xTrain = self.scalerX.transform(self.xTrainOrigin) self.xTest = self.scalerX.transform(self.xTestOrigin) self.scalerY = preprocessing.StandardScaler().fit(self.yTrainOrigin) self.yTrain = self.scalerY.transform(self.yTrainOrigin) self.yTest = self.scalerY.transform(self.yTestOrigin) ''' 计算模型评价参数 ''' def modelMerit(self, SelectedIndex): xTrainSelected = self.xTrain[:, SelectedIndex] xTestSelected = self.xTest[:, SelectedIndex] kf = model_selection.KFold(n_splits=5, random_state=10) trans, features = xTrainSelected.shape lvMax = int(min(trans, features) / 3) lvBest = 0 rmsecvBest = np.inf for lvTemp in range(1, lvMax + 1): squareArray = np.array([[]]) for train, test in kf.split(xTrainSelected): xTrainTemp = xTrainSelected[train, :] yTrainTemp = self.yTrain[train] xTestTemp = xTrainSelected[test, :] yTestTemp = self.yTrain[test] yPredictTemp, coefTemp = PLS(xTestTemp, yTestTemp, xTrainTemp, yTrainTemp, lvTemp) yPredictTempTrue = self.scalerY.inverse_transform(yPredictTemp) yTestTempTrue = self.scalerY.inverse_transform(yTestTemp) residual = yPredictTempTrue - yTestTempTrue square = np.dot(residual.T, residual) squareArray = np.append(squareArray, square) # squareArray.append(square) RMSECV = np.sqrt(np.sum(squareArray) / xTrainSelected.shape[0]) if RMSECV < rmsecvBest: rmsecvBest = RMSECV lvBest = lvTemp plsModel = cross_decomposition.PLSRegression(n_components=lvBest) plsModel.fit(xTrainSelected, self.yTrain) yPredict = plsModel.predict(xTestSelected) yTrainPredict = plsModel.predict(xTrainSelected) yTrainPredictTrue = self.scalerY.inverse_transform(yTrainPredict) yPredictTrue = self.scalerY.inverse_transform(yPredict) self.yPredcit = yPredict MEST = sm.mean_squared_error(self.yTrainOrigin, yTrainPredictTrue) RMSET = np.sqrt(MEST) R2T = sm.r2_score(self.yTrainOrigin, yTrainPredictTrue) MSEP = sm.mean_squared_error(self.yTestOrigin, yPredictTrue) RMSEP = np.sqrt(MSEP) R2P = sm.r2_score(self.yTestOrigin, yPredictTrue) # 计算交叉验证误差 yPredictCV = np.array([[]]) yTrueCV = np.array([[]]) for train, test in kf.split(xTrainSelected): xTrainTemp = xTrainSelected[train, :] yTrainTemp = self.yTrain[train] xTestTemp = xTrainSelected[test, :] yTestTemp = self.yTrain[test] yPredictTemp, coefTemp = PLS(xTestTemp, yTestTemp, xTrainTemp, yTrainTemp, lvBest) yPredictTempTrue = self.scalerY.inverse_transform(yPredictTemp) yTestTempTrue = self.scalerY.inverse_transform(yTestTemp) yPredictCV = np.append(yPredictCV, yPredictTempTrue) yTrueCV = np.append(yTrueCV, yTestTempTrue) residual = yPredictTempTrue - yTestTempTrue square = np.dot(residual.T, residual) squareArray = np.append(squareArray, square) # squareArray.append(square) RMSECV = np.sqrt(np.sum(squareArray) / xTrainSelected.shape[0]) R2CV = sm.r2_score(yPredictCV, yTrueCV) CR = 1 - len(SelectedIndex) / self.xTrain.shape[1] return rmsecvBest, RMSET, RMSEP, R2T, R2P, R2CV, CR def startSelection(self): self.selectedAlgorithm = self.algorithmBlock.currentText() if(self.xTrain is None): self.noDataWarning() return xTrain = self.xTrain xTest = self.xTest yTrain = self.yTrain yTest = self.yTest ''' 'PLS','RReliefF','UVE-PLS','SA-PLS','GA-PLS', 'ACO-PLS','LASSO','Elastic Net','FP-Tree-PLS' ''' self.statusBar().showMessage('%s算法开始' % self.selectedAlgorithm, 1000) if self.selectedAlgorithm=='RReliefF': w = RReliefF(self.xTrain, self.yTrain) th = np.percentile(w, 80) # 计算分位数 selectedIndex = np.where(w >= th)[0] elif self.selectedAlgorithm=='PLS': selectedIndex = list(range(self.xTrain.shape[1])) modelMerit = self.modelMerit(selectedIndex) self.displayMerit(modelMerit) self.statusBar().showMessage('%s算法结束' % self.selectedAlgorithm) def displayMerit(self,modelMerit): self.numrmsecvLabel.setText('%.2f' %modelMerit[0]) self.numrmsetLabel.setText('%.2f' %modelMerit[1]) self.numrmsepLabel.setText('%.2f' %modelMerit[2]) self.numr2cvLabel.setText('%.2f' %modelMerit[-2]) self.numr2pLabel.setText('%.2f' %modelMerit[4]) self.numCRlabel.setText('%.2f' %modelMerit[-1]) def stopSelection(self): pass def plotPic(self): if (self.xTrain is None): self.noDataWarning() return yTure = self.scalerY.inverse_transform(self.yTest) yPredict = self.scalerY.inverse_transform(self.yPredcit) self.drawPic.scatter2D(yTure,yPredict) def changeAlgorithm(self): self.selectedAlgorithm = self.algorithmBlock.currentText() self.statusBar().showMessage('选择%s算法' %self.selectedAlgorithm, 1000) def changeAlgoParameter(self): ''' 'PLS','RReliefF','UVE-PLS','SA-PLS','GA-PLS', 'ACO-PLS','LASSO','Elastic Net','FP-Tree-PLS' ''' self.selectedAlgorithm = self.algorithmBlock.currentText() if self.selectedAlgorithm == 'FP-Tree-PLS': self.changeParaWindow = changeFPParaWindow() elif self.selectedAlgorithm == 'SA-PLS': self.changeParaWindow = changeSAParaWindow() else: self.changeParaWindow = classicWindow() self.changeParaWindow.show()
def init_ui(self): """ Initialisation of the user interface (as the function name suggests). This is where i like to write useless comments in case someone ever decides to read this. One might think that this contains some usefull information when in reality its just me typing random stuff to make it look pretty. :return: NoneType """ # define starting size and position of the widget self.setGeometry(256, 256, 320, 260) self.setMinimumSize(320, 260) # define title and icon of the widget self.setWindowTitle("Attach divider") self.setWindowIcon(QtGui.QIcon("img/osciloscope_icon.png")) # Create two separate tabs of this widget, one for adding and one for deleting existing dividers self.tabs = QTabWidget() self.tab1 = QWidget() self.tab2 = QWidget() self.tabs.addTab(self.tab1, "Add") self.tabs.addTab(self.tab2, "Remove") self.tabs.resize(320, 260) self.grid_layout = QGridLayout() self.setLayout(self.grid_layout) self.grid_layout.addWidget(self.tabs) self.tabs.show() """"""""""""""""""""" First tab, adding new dividers """"""""""""""""""""" main_layout_tab1 = QVBoxLayout() self.tab1.setLayout(main_layout_tab1) label = QLabel("Parameter:") main_layout_tab1.addWidget(label) # combo boxes for instrument and parameter horizontal = QHBoxLayout() self.instrument_cb = QComboBox() horizontal.addWidget(self.instrument_cb) self.parameter_cb = QComboBox() horizontal.addWidget(self.parameter_cb) main_layout_tab1.addLayout(horizontal) for name, instrument in self.instruments.items(): display_member = name value_member = instrument self.instrument_cb.addItem(display_member, value_member) self.instrument_cb.currentIndexChanged.connect(self.update_parameters) self.update_parameters() # text box for division value label = QLabel("Division") main_layout_tab1.addWidget(label) self.division_value_textbox = QLineEdit() main_layout_tab1.addWidget(self.division_value_textbox) # button to confirm adding divider self.attach_divider_btn = QPushButton("Add") main_layout_tab1.addWidget(self.attach_divider_btn) self.attach_divider_btn.clicked.connect(self.attach_divider) """"""""""""""""""""" Second tab, removing dividers """"""""""""""""""""" main_layout_tab2 = QVBoxLayout() self.tab2.setLayout(main_layout_tab2) # table containing all dividers created so far self.dividers_table = QTableWidget(0, 3) main_layout_tab2.addWidget(self.dividers_table) self.dividers_table.setHorizontalHeaderLabels(("Parameter", "Division", "Delete")) header = self.dividers_table.horizontalHeader() header.setSectionResizeMode(0, QHeaderView.Stretch) header.setSectionResizeMode(1, QHeaderView.Stretch) header.setSectionResizeMode(2, QHeaderView.ResizeToContents) self.dividers_table.setSelectionBehavior(QTableView.SelectRows) # add all dividers to the table for name, parameter in self.dividers.items(): rows = self.dividers_table.rowCount() self.dividers_table.insertRow(rows) item = QTableWidgetItem(name) item.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEnabled) self.dividers_table.setItem(rows, 0, item) item = QTableWidgetItem(str(parameter.division_value)) item.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEnabled) self.dividers_table.setItem(rows, 1, item) item = QTableWidgetItem(name) item.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEnabled) self.dividers_table.setItem(rows, 0, item) # add a delete button for every divider in the table current_parameter_btn = QPushButton("Delete") current_parameter_btn.resize(35, 20) current_parameter_btn.clicked.connect(self.make_remove_divider(name=name, item=item)) self.dividers_table.setCellWidget(rows, 2, current_parameter_btn)
def initWindow(self): QToolTip.setFont(QFont('SansSerif', 10)) # main layout frameWidget = QWidget() mainWidget = QSplitter(Qt.Horizontal) frameLayout = QVBoxLayout() self.settingWidget = QWidget() self.settingWidget.setProperty("class", "settingWidget") self.receiveSendWidget = QSplitter(Qt.Vertical) self.functionalWiget = QWidget() settingLayout = QVBoxLayout() sendReceiveLayout = QVBoxLayout() sendFunctionalLayout = QVBoxLayout() mainLayout = QHBoxLayout() self.settingWidget.setLayout(settingLayout) self.receiveSendWidget.setLayout(sendReceiveLayout) self.functionalWiget.setLayout(sendFunctionalLayout) mainLayout.addWidget(self.settingWidget) mainLayout.addWidget(self.receiveSendWidget) mainLayout.addWidget(self.functionalWiget) mainLayout.setStretch(0, 2) mainLayout.setStretch(1, 6) mainLayout.setStretch(2, 2) menuLayout = QHBoxLayout() mainWidget.setLayout(mainLayout) frameLayout.addLayout(menuLayout) frameLayout.addWidget(mainWidget) frameWidget.setLayout(frameLayout) self.setCentralWidget(frameWidget) # option layout self.settingsButton = QPushButton() self.skinButton = QPushButton("") # self.waveButton = QPushButton("") self.aboutButton = QPushButton() self.functionalButton = QPushButton() self.encodingCombobox = ComboBox() self.encodingCombobox.addItem("ASCII") self.encodingCombobox.addItem("UTF-8") self.encodingCombobox.addItem("UTF-16") self.encodingCombobox.addItem("GBK") self.encodingCombobox.addItem("GB2312") self.encodingCombobox.addItem("GB18030") self.settingsButton.setProperty("class", "menuItem1") self.skinButton.setProperty("class", "menuItem2") self.aboutButton.setProperty("class", "menuItem3") self.functionalButton.setProperty("class", "menuItem4") # self.waveButton.setProperty("class", "menuItem5") self.settingsButton.setObjectName("menuItem") self.skinButton.setObjectName("menuItem") self.aboutButton.setObjectName("menuItem") self.functionalButton.setObjectName("menuItem") # self.waveButton.setObjectName("menuItem") menuLayout.addWidget(self.settingsButton) menuLayout.addWidget(self.skinButton) # menuLayout.addWidget(self.waveButton) menuLayout.addWidget(self.aboutButton) menuLayout.addStretch(0) menuLayout.addWidget(self.encodingCombobox) menuLayout.addWidget(self.functionalButton) # widgets receive and send area self.receiveArea = QTextEdit() self.sendArea = QTextEdit() self.clearReceiveButtion = QPushButton(parameters.strClearReceive) self.sendButtion = QPushButton(parameters.strSend) self.sendHistory = ComboBox() sendWidget = QWidget() sendAreaWidgetsLayout = QHBoxLayout() sendWidget.setLayout(sendAreaWidgetsLayout) buttonLayout = QVBoxLayout() buttonLayout.addWidget(self.clearReceiveButtion) buttonLayout.addStretch(1) buttonLayout.addWidget(self.sendButtion) sendAreaWidgetsLayout.addWidget(self.sendArea) sendAreaWidgetsLayout.addLayout(buttonLayout) sendReceiveLayout.addWidget(self.receiveArea) sendReceiveLayout.addWidget(sendWidget) sendReceiveLayout.addWidget(self.sendHistory) sendReceiveLayout.setStretch(0, 7) sendReceiveLayout.setStretch(1, 2) sendReceiveLayout.setStretch(2, 1) # widgets serial settings serialSettingsGroupBox = QGroupBox(parameters.strSerialSettings) serialSettingsLayout = QGridLayout() serialReceiveSettingsLayout = QGridLayout() serialSendSettingsLayout = QGridLayout() serialPortLabek = QLabel(parameters.strSerialPort) serailBaudrateLabel = QLabel(parameters.strSerialBaudrate) serailBytesLabel = QLabel(parameters.strSerialBytes) serailParityLabel = QLabel(parameters.strSerialParity) serailStopbitsLabel = QLabel(parameters.strSerialStopbits) self.serialPortCombobox = ComboBox() self.serailBaudrateCombobox = ComboBox() self.serailBaudrateCombobox.addItem("9600") self.serailBaudrateCombobox.addItem("19200") self.serailBaudrateCombobox.addItem("38400") self.serailBaudrateCombobox.addItem("57600") self.serailBaudrateCombobox.addItem("115200") self.serailBaudrateCombobox.setCurrentIndex(4) self.serailBaudrateCombobox.setEditable(True) self.serailBytesCombobox = ComboBox() self.serailBytesCombobox.addItem("5") self.serailBytesCombobox.addItem("6") self.serailBytesCombobox.addItem("7") self.serailBytesCombobox.addItem("8") self.serailBytesCombobox.setCurrentIndex(3) self.serailParityCombobox = ComboBox() self.serailParityCombobox.addItem("None") self.serailParityCombobox.addItem("Odd") self.serailParityCombobox.addItem("Even") self.serailParityCombobox.addItem("Mark") self.serailParityCombobox.addItem("Space") self.serailParityCombobox.setCurrentIndex(0) self.serailStopbitsCombobox = ComboBox() self.serailStopbitsCombobox.addItem("1") self.serailStopbitsCombobox.addItem("1.5") self.serailStopbitsCombobox.addItem("2") self.serailStopbitsCombobox.setCurrentIndex(0) self.checkBoxRts = QCheckBox("rts") self.checkBoxDtr = QCheckBox("dtr") self.serialOpenCloseButton = QPushButton(parameters.strOpen) serialSettingsLayout.addWidget(serialPortLabek, 0, 0) serialSettingsLayout.addWidget(serailBaudrateLabel, 1, 0) serialSettingsLayout.addWidget(serailBytesLabel, 2, 0) serialSettingsLayout.addWidget(serailParityLabel, 3, 0) serialSettingsLayout.addWidget(serailStopbitsLabel, 4, 0) serialSettingsLayout.addWidget(self.serialPortCombobox, 0, 1) serialSettingsLayout.addWidget(self.serailBaudrateCombobox, 1, 1) serialSettingsLayout.addWidget(self.serailBytesCombobox, 2, 1) serialSettingsLayout.addWidget(self.serailParityCombobox, 3, 1) serialSettingsLayout.addWidget(self.serailStopbitsCombobox, 4, 1) serialSettingsLayout.addWidget(self.checkBoxRts, 5, 0, 1, 1) serialSettingsLayout.addWidget(self.checkBoxDtr, 5, 1, 1, 1) serialSettingsLayout.addWidget(self.serialOpenCloseButton, 6, 0, 1, 2) serialSettingsGroupBox.setLayout(serialSettingsLayout) settingLayout.addWidget(serialSettingsGroupBox) # serial receive settings serialReceiveSettingsGroupBox = QGroupBox( parameters.strSerialReceiveSettings) self.receiveSettingsAscii = QRadioButton(parameters.strAscii) self.receiveSettingsHex = QRadioButton(parameters.strHex) self.receiveSettingsAscii.setChecked(True) self.receiveSettingsAutoLinefeed = QCheckBox( parameters.strAutoLinefeed) self.receiveSettingsAutoLinefeedTime = QLineEdit( parameters.strAutoLinefeedTime) self.receiveSettingsAutoLinefeed.setMaximumWidth(75) self.receiveSettingsAutoLinefeedTime.setMaximumWidth(75) serialReceiveSettingsLayout.addWidget(self.receiveSettingsAscii, 1, 0, 1, 1) serialReceiveSettingsLayout.addWidget(self.receiveSettingsHex, 1, 1, 1, 1) serialReceiveSettingsLayout.addWidget(self.receiveSettingsAutoLinefeed, 2, 0, 1, 1) serialReceiveSettingsLayout.addWidget( self.receiveSettingsAutoLinefeedTime, 2, 1, 1, 1) serialReceiveSettingsGroupBox.setLayout(serialReceiveSettingsLayout) settingLayout.addWidget(serialReceiveSettingsGroupBox) # serial send settings serialSendSettingsGroupBox = QGroupBox( parameters.strSerialSendSettings) self.sendSettingsAscii = QRadioButton(parameters.strAscii) self.sendSettingsHex = QRadioButton(parameters.strHex) self.sendSettingsAscii.setChecked(True) self.sendSettingsScheduledCheckBox = QCheckBox(parameters.strScheduled) self.sendSettingsScheduled = QLineEdit(parameters.strScheduledTime) self.sendSettingsScheduledCheckBox.setMaximumWidth(75) self.sendSettingsScheduled.setMaximumWidth(75) self.sendSettingsCFLF = QCheckBox(parameters.strCRLF) self.sendSettingsCFLF.setChecked(False) serialSendSettingsLayout.addWidget(self.sendSettingsAscii, 1, 0, 1, 1) serialSendSettingsLayout.addWidget(self.sendSettingsHex, 1, 1, 1, 1) serialSendSettingsLayout.addWidget(self.sendSettingsScheduledCheckBox, 2, 0, 1, 1) serialSendSettingsLayout.addWidget(self.sendSettingsScheduled, 2, 1, 1, 1) serialSendSettingsLayout.addWidget(self.sendSettingsCFLF, 3, 0, 1, 2) serialSendSettingsGroupBox.setLayout(serialSendSettingsLayout) settingLayout.addWidget(serialSendSettingsGroupBox) settingLayout.setStretch(0, 5) settingLayout.setStretch(1, 2.5) settingLayout.setStretch(2, 2.5) # right functional layout self.filePathWidget = QLineEdit() self.openFileButton = QPushButton("Open File") self.sendFileButton = QPushButton("Send File") self.clearHistoryButton = QPushButton("Clear History") self.addButton = QPushButton(parameters.strAdd) fileSendGroupBox = QGroupBox(parameters.strSendFile) fileSendGridLayout = QGridLayout() fileSendGridLayout.addWidget(self.filePathWidget, 0, 0, 1, 1) fileSendGridLayout.addWidget(self.openFileButton, 0, 1, 1, 1) fileSendGridLayout.addWidget(self.sendFileButton, 1, 0, 1, 2) fileSendGroupBox.setLayout(fileSendGridLayout) sendFunctionalLayout.addWidget(fileSendGroupBox) sendFunctionalLayout.addWidget(self.clearHistoryButton) sendFunctionalLayout.addWidget(self.addButton) sendFunctionalLayout.addStretch(1) self.isHideFunctinal = True self.hideFunctional() # main window self.statusBarStauts = QLabel() self.statusBarStauts.setMinimumWidth(80) self.statusBarStauts.setText("<font color=%s>%s</font>" % ("#008200", parameters.strReady)) self.statusBarSendCount = QLabel(parameters.strSend + "(bytes): " + "0") self.statusBarReceiveCount = QLabel(parameters.strReceive + "(bytes): " + "0") self.statusBar().addWidget(self.statusBarStauts) self.statusBar().addWidget(self.statusBarSendCount, 2) self.statusBar().addWidget(self.statusBarReceiveCount, 3) # self.statusBar() self.resize(800, 500) self.MoveToCenter() self.setWindowTitle(parameters.appName + " V" + str(helpAbout.versionMajor) + "." + str(helpAbout.versionMinor)) icon = QIcon() print("icon path:" + self.DataPath + "/" + parameters.appIcon) icon.addPixmap(QPixmap(self.DataPath + "/" + parameters.appIcon), QIcon.Normal, QIcon.Off) self.setWindowIcon(icon) if sys.platform == "win32": ctypes.windll.shell32.SetCurrentProcessExplicitAppUserModelID( "comtool") self.show() print("config file path:", os.getcwd() + "/comtool.settings.config")
class MainWindow(QMainWindow): def __init__(self): super().__init__() # Proyecto self.project = None # Título self.setWindowTitle("3D Cell Reconstruction") # Inicializa el menú self.initMenubar() # Visor de las imágenes (imagen y control van en el mismo layout) # NOTA: Es el objeto central del objeto QMainWindow, que tiene eso, una barra de estado, etc. Podemos volver al QWidget si es fuese mejor. self.imageViewer = QWidget(self) self.imageViewer.setLayout(QGridLayout()) # Fija márgenes para centrar la imagen self.imageViewer.layout().setColumnStretch(0, 0) self.imageViewer.layout().setColumnStretch(2, 0) self.imageViewer.layout().setRowStretch(1, 0) self.imageViewer.layout().setRowStretch(3, 0) # Crea un campo de texto para mostrar el nombre de la imagen self.imageName = QLineEdit("No project loaded") self.imageName.setReadOnly(True) self.imageViewer.layout().addWidget(self.imageName, 0, 1) # Crea un objeto de la clase ImageView para mostrar la imagen y dibujar self.imageView = ImageView() self.imageViewer.layout().addWidget(self.imageView, 2, 1) # Inicializa los botones de control self.initControlLayout() self.imageViewer.layout().addLayout(self.control_layout, 3, 0, 1, 3) # Lo situa como objeto pricipal de la aplicación. self.setCentralWidget(self.imageViewer) # NOTA: Como inicialmente no hay proyecto abierto, deshabilita los botones. self.enableControls(False) def initMenubar(self): ''' Crea el menú de la aplicación y lo almacena en self.menuBar ''' self.menuBar = QMenuBar() self.setMenuBar(self.menuBar) self.menuBar.setNativeMenuBar( False) # Necesario para que funcione en MacOS # Menu File fileMenu = self.menuBar.addMenu("File") openAction = QAction('Open image sequence', self) fileMenu.addAction(openAction) openAction.triggered.connect(self.open) exitAction = QAction('Exit', self) fileMenu.addAction(exitAction) exitAction.triggered.connect(self.close) # Menu Display displayMenu = self.menuBar.addMenu("Display") gen3DAction = QAction('Generate 3D structure', self) displayMenu.addAction(gen3DAction) gen3DAction.triggered.connect(self.gen3D) # Help Display helpMenu = self.menuBar.addMenu("Help") aboutAction = QAction("About", self) helpMenu.addAction(aboutAction) # aboutAction.triggered.connect(self.about) # Una ventana que muestre tu nombre, y eso. def initControlLayout(self): ''' Añade los botones para navegar sobre las imágenes en un imgViewerLayout denominado self.control_layout. ''' # Alante y atrás self.btn_next = QPushButton() self.btn_next.setIcon(QIcon('resources/next.png')) self.btn_next.setFixedWidth(50) self.btn_prev = QPushButton() self.btn_prev.setIcon(QIcon('resources/back.png')) self.btn_prev.setFixedWidth(50) # Borrar y deshacer self.btn_clear = QPushButton("Clear") self.btn_clear.setFixedWidth(80) self.btn_undo = QPushButton("Undo") self.btn_undo.setFixedWidth(80) # Mostrar o no información de las imágenes anteriores. self.check_showC = QCheckBox("Previous Image Curves") self.check_showP = QCheckBox("Previous Image Particles") self.check_showC.setChecked(False) self.check_showP.setChecked(False) # Panel para colocar los controles. self.control_layout = QHBoxLayout() # Coloca los controles en el imgViewerLayout self.control_layout.addWidget(self.btn_prev) self.control_layout.addWidget(self.btn_next) self.control_layout.addStretch() self.control_layout.addWidget(self.check_showC) self.control_layout.addWidget(self.check_showP) self.control_layout.addWidget(self.btn_undo) self.control_layout.addWidget(self.btn_clear) # Conecta los componentes con las acciones correspondientes. self.btn_next.clicked.connect(self.next) self.btn_prev.clicked.connect(self.prev) self.btn_clear.clicked.connect(self.clear) self.btn_undo.clicked.connect(self.undo) #self.check_showC.clicked.connect(self.showC) #self.check_showP.clicked.connect(self.showP) def enableControls(self, state): ''' Habilita o deshabilita los controles y la vista de la imagen. ''' self.imageName.setEnabled(state) self.imageView.setEnabled(state) self.btn_next.setEnabled(state) self.btn_prev.setEnabled(state) self.btn_clear.setEnabled(state) self.btn_undo.setEnabled(state) self.check_showC.setEnabled(state) self.check_showP.setEnabled(state) def updateWindowSize(self): ''' Aujsta el tamaño de la ventana y la centra ''' # Calcula el tamaño ideal para la vista y la ventana. Para ello determina, el ratio # en función la máxima altura o anchura que puede tener la imagen. if not self.project is None: ratioWidth = (screenSize.getCoords()[2] - 100) / (self.project.imgShape[1]) ratioHeight = (screenSize.getCoords()[3] - 150) / (self.project.imgShape[0]) ratio = ratioWidth if ratioWidth < ratioHeight else ratioHeight self.imageView.setFixedWidth(int(self.project.imgShape[1] * ratio)) self.imageView.setFixedHeight(int(self.project.imgShape[0] * ratio)) # Ajusta el tamaño de la ventana. self.adjustSize() # Centra la ventana windowPosition = self.geometry() windowPosition.moveCenter(screenSize.center()) self.move(windowPosition.topLeft()) def updateImageView(self): ''' Actualiza la imagen ''' # Actualiza el texto y la imagen (recortada). self.imageName.setText( self.project.imgSequence[self.project.currentImgId]) utils.cropImageBorders( self.project.folder + '/' + self.project.imgSequence[self.project.currentImgId]) self.imageView.loadImage( self.project.folder + '/' + self.project.imgSequence[self.project.currentImgId]) def open(self): ''' Abre un proyecto. ''' # Selecciona un directorio de trabajo para cargarlo en un proyecto. selectedDirectory = str( QFileDialog.getExistingDirectory(self, "Select directory")) # Vuelve si se ha cancelado la apertura. if len(selectedDirectory) == 0: # NOTA: Fíjate que lo que hacemos es dejarlo como estaba. Si había cargado un proyecto, se queda # abierto y los botones y eso habilitados. Si no había nada abierto, sigue sin abrirse. return # NOTA: Solamente llega aquí si se ha seleccionado un directorio. # Se crea el proyecto self.project = Project(selectedDirectory) # Si en la carpeta seleccionada no hay ninguna imagen, deshabilitamos if len(self.project.imgSequence) == 0: #self.imageView.scene.clear() self.enableControls(False) return # NOTA: Solamente llega aquí si el proyecto tiene imágenes # Actualiza el tamaño de la ventana. self.updateWindowSize() # Muestra la información actual del proyecto. self.updateImageView() # Habilita los controles. self.enableControls(True) def next(self): ''' Pasa a la siguiente imagen. ''' self.project.next() self.updateImageView() def prev(self): ''' Pasa a la imagen anterior. ''' self.project.prev() self.updateImageView() def undo(self): self.imageView.removeLastCurve() def clear(self): self.imageView.clear() def gen3D(self): ''' Genera la reconstrucción 3D ''' pass
def __init__(self, parent=None): QMainWindow.__init__(self, parent) self.central = QWidget(self) self.player = QMediaPlayer() self.playlist = QMediaPlaylist() self.inference = Inference() self.folder_chosen = False self.textbox = QTextEdit(self.central) self.textbox.setFont(TEXT_FONT) self.textbox.setMinimumSize(300, 100) self.text_update.connect(self.append_text) sys.stdout = self print("Camera number %u" % camera_num) print("Image size %u x %u" % IMG_SIZE) if DISP_SCALE > 1: print("Display scale %u:1" % DISP_SCALE) self.vlayout = QVBoxLayout() # Window layout self.displays = QHBoxLayout() self.disp = ImageWidget(self) self.displays.addWidget(self.disp) self.vlayout.addLayout(self.displays) self.label = QLabel(self) self.vlayout.addWidget(self.label) self.vlayout.addWidget(self.textbox) # TODO provision for allowing song to play # DONE self.current_song_start_time = datetime.now() volumeslider = QSlider(Qt.Horizontal, self) volumeslider.setFocusPolicy(Qt.NoFocus) volumeslider.valueChanged[int].connect(self.changeVolume) volumeslider.setValue(100) playBtn = QPushButton('Play') # play button pauseBtn = QPushButton('Pause') # pause button stopBtn = QPushButton('Stop') # stop button # Add playlist controls prevBtn = QPushButton('Prev') shuffleBtn = QPushButton('Shuffle') nextBtn = QPushButton('Next') # Add button layouts #controlArea = QVBoxLayout() # centralWidget controls = QHBoxLayout() playlistCtrlLayout = QHBoxLayout() # Add buttons to song controls layout controls.addWidget(playBtn) controls.addWidget(pauseBtn) controls.addWidget(stopBtn) # Add buttons to playlist controls layout playlistCtrlLayout.addWidget(prevBtn) playlistCtrlLayout.addWidget(shuffleBtn) playlistCtrlLayout.addWidget(nextBtn) # Add to vertical layout self.vlayout.addWidget(volumeslider) self.vlayout.addLayout(controls) self.vlayout.addLayout(playlistCtrlLayout) self.central.setLayout(self.vlayout) #self.central.setLayout(controlArea) self.setCentralWidget(self.central) # Connect each signal to their appropriate function playBtn.clicked.connect(self.playhandler) pauseBtn.clicked.connect(self.pausehandler) stopBtn.clicked.connect(self.stophandler) prevBtn.clicked.connect(self.prevSong) shuffleBtn.clicked.connect(self.shufflelist) nextBtn.clicked.connect(self.nextSong) self.statusBar() self.playlist.currentMediaChanged.connect(self.songChanged) self.mainMenu = self.menuBar() # Menu bar exitAction = QAction('&Exit', self) exitAction.setShortcut('Ctrl+Q') exitAction.triggered.connect(self.close) self.fileMenu = self.mainMenu.addMenu('&File') fileAct = QAction('Open File', self) folderAct = QAction('Open Folder', self) fileAct.setShortcut('Ctrl+O') folderAct.setShortcut('Ctrl+D') self.fileMenu.addAction(fileAct) self.fileMenu.addAction(folderAct) fileAct.triggered.connect(self.openFile) folderAct.triggered.connect(self.addFiles) self.fileMenu.addAction(exitAction)
class MainWindowGUI(QMainWindow): def __init__(self, refresh_time=30): super().__init__() uic.loadUi(os.path.join(os.path.dirname(os.path.abspath(__file__)), 'designer', 'MainWindow.ui'), self) self.logger = get_logger(name=__name__) self.central_layout = QHBoxLayout(self.centralwidget) self.widget_splitter = QSplitter() self.camera_viewer_widget = CameraViewerWidget() self.histogram_tracks_widget = HistogramTracksWidget(self) self.widget_splitter.addWidget(self.camera_viewer_widget) self.widget_splitter.addWidget(self.histogram_tracks_widget) self.widget_splitter.setSizes((750, 750)) self.central_layout.addWidget(self.widget_splitter) self.config_widget = ConfigWidget() self.config_tracking_widget = ConfigTrackingWidget() self.refresh_timer = QTimer() self.refresh_timer.timeout.connect(self.update_gui) self.refresh_timer.start(refresh_time) self.showMaximized() self.connect_actions() self.connect_buttons() self.connect_signals() def update_gui(self): self.logger.error('Update gui not defined') def connect_signals(self): self.config_tracking_widget.apply_config.connect(self.update_tracking_config) self.config_widget.apply_config.connect(self.update_config) def connect_buttons(self): self.histogram_tracks_widget.button_histogram.clicked.connect(self.calculate_histogram) self.histogram_tracks_widget.button_tracks.clicked.connect(self.update_tracks) def connect_actions(self): self.actionClose.triggered.connect(self.safe_close) self.actionLoad_Config.triggered.connect(self.load_config) self.actionSave_Image.triggered.connect(self.save_image) self.actionLoad_Data.triggered.connect(self.load_data) self.actionSnap_Photo.triggered.connect(self.snap) self.actionStart_Movie.triggered.connect(self.start_movie) self.actionStop_Movie.triggered.connect(self.stop_movie) self.actionStart_Continuous_Saves.triggered.connect(self.start_continuous_saves) self.actionStop_Continuous_Saves.triggered.connect(self.stop_continuous_saves) self.actionSet_ROI.triggered.connect(self.set_roi) self.actionClear_ROI.triggered.connect(self.clear_roi) self.actionConfiguration.triggered.connect(self.configure) self.actionToggle_bg_reduction.triggered.connect(self.background_reduction) self.actionStart_Tracking.triggered.connect(self.start_tracking) self.actionStop_Tracking.triggered.connect(self.stop_tracking) self.actionStart_Linking.triggered.connect(self.start_linking) self.actionStop_Linking.triggered.connect(self.stop_linking) self.actionSave_Tracks.triggered.connect(self.start_saving_tracks) self.actionShow_Cheatsheet.triggered.connect(self.show_cheat_sheet) self.actionAbout.triggered.connect(self.show_about) self.actionInitialize_Camera.triggered.connect(self.initialize_camera) self.actionUpdate_Histogram.triggered.connect(self.calculate_histogram) self.actionTracking_Config.triggered.connect(self.config_tracking_widget.show) self.actionConfiguration.triggered.connect(self.config_widget.show) def initialize_camera(self): self.logger.debug('Initialize Camera') def show_about(self): self.logger.debug('Showing About') def load_config(self): self.logger.debug('Loading config') def snap(self): self.logger.debug('Snapped a photo') def save_image(self): self.logger.debug('Saved an image') def start_movie(self): self.logger.debug('Start a movie') def stop_movie(self): self.logger.error('Stop movie not defined') def start_continuous_saves(self): self.logger.debug('Started continuous saves') def stop_continuous_saves(self): self.logger.error('Stop continuous Saves not implemented') def start_tracking(self): self.logger.debug('Started tracking particles') def stop_tracking(self): self.logger.debug('Stopped tracking particles') def start_saving_tracks(self): self.logger.debug('Started saving tracks') def stop_saving_tracks(self): self.logger.debug('Stopped saving tracks') def start_linking(self): self.logger.debug('Started linking particles') def stop_linking(self): self.logger.debug('Stopped linking') def configure(self): self.logger.debug('Showed the config window') def set_roi(self): self.logger.debug('Setting the ROI') def clear_roi(self): self.logger.debug('Resetting the ROI') def background_reduction(self): self.logger.debug('Setting background reduction') def show_cheat_sheet(self): self.logger.debug('Showing the cheat sheet') def load_data(self): self.logger.debug('Loading data') def safe_close(self): self.logger.debug('Closing the program') self.close() def calculate_histogram(self): self.logger.error('Update Histogram method not defiend') def update_tracks(self): self.logger.error('Update tracks method not defined') def update_tracking_config(self, config): self.logger.error('Update Tracking config method not defined') def update_config(self, config): self.logger.error('Update Config method not defined') def closeEvent(self, *args, **kwargs): self.config_widget.close() self.config_tracking_widget.close() super(MainWindowGUI, self).closeEvent(*args, **kwargs)
class MyWindow(QMainWindow): text_update = pyqtSignal(str) # Create main window def __init__(self, parent=None): QMainWindow.__init__(self, parent) self.central = QWidget(self) self.player = QMediaPlayer() self.playlist = QMediaPlaylist() self.inference = Inference() self.folder_chosen = False self.textbox = QTextEdit(self.central) self.textbox.setFont(TEXT_FONT) self.textbox.setMinimumSize(300, 100) self.text_update.connect(self.append_text) sys.stdout = self print("Camera number %u" % camera_num) print("Image size %u x %u" % IMG_SIZE) if DISP_SCALE > 1: print("Display scale %u:1" % DISP_SCALE) self.vlayout = QVBoxLayout() # Window layout self.displays = QHBoxLayout() self.disp = ImageWidget(self) self.displays.addWidget(self.disp) self.vlayout.addLayout(self.displays) self.label = QLabel(self) self.vlayout.addWidget(self.label) self.vlayout.addWidget(self.textbox) # TODO provision for allowing song to play # DONE self.current_song_start_time = datetime.now() volumeslider = QSlider(Qt.Horizontal, self) volumeslider.setFocusPolicy(Qt.NoFocus) volumeslider.valueChanged[int].connect(self.changeVolume) volumeslider.setValue(100) playBtn = QPushButton('Play') # play button pauseBtn = QPushButton('Pause') # pause button stopBtn = QPushButton('Stop') # stop button # Add playlist controls prevBtn = QPushButton('Prev') shuffleBtn = QPushButton('Shuffle') nextBtn = QPushButton('Next') # Add button layouts #controlArea = QVBoxLayout() # centralWidget controls = QHBoxLayout() playlistCtrlLayout = QHBoxLayout() # Add buttons to song controls layout controls.addWidget(playBtn) controls.addWidget(pauseBtn) controls.addWidget(stopBtn) # Add buttons to playlist controls layout playlistCtrlLayout.addWidget(prevBtn) playlistCtrlLayout.addWidget(shuffleBtn) playlistCtrlLayout.addWidget(nextBtn) # Add to vertical layout self.vlayout.addWidget(volumeslider) self.vlayout.addLayout(controls) self.vlayout.addLayout(playlistCtrlLayout) self.central.setLayout(self.vlayout) #self.central.setLayout(controlArea) self.setCentralWidget(self.central) # Connect each signal to their appropriate function playBtn.clicked.connect(self.playhandler) pauseBtn.clicked.connect(self.pausehandler) stopBtn.clicked.connect(self.stophandler) prevBtn.clicked.connect(self.prevSong) shuffleBtn.clicked.connect(self.shufflelist) nextBtn.clicked.connect(self.nextSong) self.statusBar() self.playlist.currentMediaChanged.connect(self.songChanged) self.mainMenu = self.menuBar() # Menu bar exitAction = QAction('&Exit', self) exitAction.setShortcut('Ctrl+Q') exitAction.triggered.connect(self.close) self.fileMenu = self.mainMenu.addMenu('&File') fileAct = QAction('Open File', self) folderAct = QAction('Open Folder', self) fileAct.setShortcut('Ctrl+O') folderAct.setShortcut('Ctrl+D') self.fileMenu.addAction(fileAct) self.fileMenu.addAction(folderAct) fileAct.triggered.connect(self.openFile) folderAct.triggered.connect(self.addFiles) self.fileMenu.addAction(exitAction) #self.addControls() # Start image capture & display def start(self): self.timer = QTimer(self) # Timer to trigger display self.timer.timeout.connect(lambda: self.show_image(image_queue, self.disp, DISP_SCALE)) self.timer.start(DISP_MSEC) self.capture_thread = threading.Thread(target=grab_images, args=(camera_num, image_queue)) self.capture_thread.start() # Thread to grab images # Fetch camera image from queue, and display it def show_image(self, imageq, display, scale): if not imageq.empty(): image = imageq.get() if image is not None and len(image) > 0: img = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) self.display_image(img, display, scale) # Display an image, reduce size if required def display_image(self, img, display, scale=1): disp_size = img.shape[1]//scale, img.shape[0]//scale disp_bpl = disp_size[0] * 3 if scale > 1: img = cv2.resize(img, disp_size, interpolation=cv2.INTER_CUBIC) global PREDICTION_STATUS if PREDICTION_STATUS != -1: # print(PREDICTION_STATUS) self.handle_inference(PREDICTION_STATUS) # img_try = cv2.imread('test_image.jpg') # img_try = cv2.cvtColor(img , cv2.COLOR_BGR2RGB) # self.inference.perform_inference(img) # if self.inference.network.wait() == 0 : # result = self.inference.network.extract_output() # pred = np.argmax(result[0, :]) # print(pred) # self.handle_inference( pred ) qimg = QImage(img.data, disp_size[0], disp_size[1], disp_bpl, IMG_FORMAT) display.setImage(qimg) # Handle sys.stdout.write: update text display def write(self, text): self.text_update.emit(str(text)) def flush(self): pass def check_song_is_playing(self): if (datetime.now() - self.current_song_start_time ).seconds >= 4: return False else: return True def handle_inference(self, result): if self.folder_chosen == True and self.check_song_is_playing() == False: global PREDICTION_STATUS if result == 1: #self.pausehandler() PREDICTION_STATUS = -1 pass elif result == 5: self.playhandler() elif result == 0: #self.stophandler() PREDICTION_STATUS = -1 pass elif result == 4: PREDICTION_STATUS = -1 elif result == 2: self.prevSong() elif result == 3: self.nextSong() # Append to text display def append_text(self, text): cur = self.textbox.textCursor() # Move cursor to end of text cur.movePosition(QTextCursor.End) s = str(text) while s: head,sep,s = s.partition("\n") # Split line at LF cur.insertText(head) # Insert text at cursor if sep: # New line if LF cur.insertBlock() self.textbox.setTextCursor(cur) # Update visible cursor # Window is closing: stop video capture def closeEvent(self, event): global capturing capturing = False self.capture_thread.join() def openFile(self): song = QFileDialog.getOpenFileName(self, "Open Song", "~", "Sound Files (*.mp3 *.ogg *.wav *.m4a)") if song[0] != '': url = QUrl.fromLocalFile(song[0]) if self.playlist.mediaCount() == 0: self.playlist.addMedia(QMediaContent(url)) self.player.setPlaylist(self.playlist) self.player.play() else: self.playlist.addMedia(QMediaContent(url)) def addFiles(self): if self.playlist.mediaCount() != 0: self.folderIterator() else: self.folderIterator() self.player.setPlaylist(self.playlist) self.player.playlist().setCurrentIndex(0) self.player.play() def folderIterator(self): folderChosen = QFileDialog.getExistingDirectory(self, 'Open Music Folder', '~') if folderChosen != None: it = QDirIterator(folderChosen) it.next() while it.hasNext(): if it.fileInfo().isDir() == False and it.filePath() != '.': fInfo = it.fileInfo() if fInfo.suffix() in ('mp3', 'ogg', 'wav', 'm4a'): self.playlist.addMedia(QMediaContent(QUrl.fromLocalFile(it.filePath()))) self.folder_chosen = True it.next() self.playlist.setPlaybackMode(QMediaPlaylist.Loop) if it.fileInfo().isDir() == False and it.filePath() != '.': fInfo = it.fileInfo() if fInfo.suffix() in ('mp3', 'ogg', 'wav', 'm4a'): self.playlist.addMedia(QMediaContent(QUrl.fromLocalFile(it.filePath()))) self.folder_chosen = True def playhandler(self): if self.playlist.mediaCount() == 0: self.folder_chosen = False self.addFiles() elif self.playlist.mediaCount() != 0: self.player.play() self.current_song_start_time = datetime.now() global PREDICTION_STATUS PREDICTION_STATUS = -1 def pausehandler(self): print('Stopped and cleared playlist') self.player.pause() global PREDICTION_STATUS PREDICTION_STATUS = -1 def stophandler(self): self.folder_chosen = False self.player.stop() self.playlist.clear() print('Stopped and cleared playlist') self.statusBar().showMessage("Stopped and cleared playlist") global PREDICTION_STATUS PREDICTION_STATUS = -1 def changeVolume(self, value): self.player.setVolume(value) def prevSong(self): print('playing previous song') if self.playlist.mediaCount() == 0: self.folder_chosen = False self.addFiles() elif self.playlist.mediaCount() != 0: self.player.playlist().previous() self.current_song_start_time = datetime.now() global PREDICTION_STATUS PREDICTION_STATUS = -1 def shufflelist(self): self.playlist.shuffle() def nextSong(self): print('playing next song') if self.playlist.mediaCount() == 0: self.folder_chosen = False self.addFiles() elif self.playlist.mediaCount() != 0: self.player.playlist().next() self.current_song_start_time = datetime.now() global PREDICTION_STATUS PREDICTION_STATUS = -1 def songChanged(self, media): if not media.isNull(): url = media.canonicalUrl() print('Now playing ' +url.fileName()) self.statusBar().showMessage(url.fileName())
class UI(QWidget): def __init__(self): super().__init__() self.width: any = None self.height: any = None self.input_open_button: QPushButton = None self.input_clear_button: QPushButton = None self.input_list: QListWidget = None self.input_input_label: QLabel = None self.method_calculate_button: QPushButton = None self.method_reset_button: QPushButton = None self.method_combobox: QComboBox = None self.method_method_used_label: QLabel = None self.method_intial_interval_textbox: QPlainTextEdit = None self.output_save_button: QPushButton = None self.output_clear_button: QPushButton = None self.output_textbox: QPlainTextEdit = None self.output_output_label: QLabel = None # 3d self.figure1 = plt.figure() self.canvas1 = FigureCanvas(self.figure1) # 2d self.figure2 = plt.figure() self.canvas2 = FigureCanvas(self.figure2) # graph error message box self.graph_error_texbox: QPlainTextEdit = None self.grid_layout: QGridLayout = None self.hbox1: QHBoxLayout = None self.hbox2: QHBoxLayout = None self.hbox: QHBoxLayout = None self.vbox: QVBoxLayout = None self.open_file_location: str = os.path.dirname( os.path.abspath(__file__)) self.save_file_location: str = os.path.dirname( os.path.abspath(__file__)) self.methods = list(Methods.keys()) self.initUI() def initUI(self): self.grid_layout = QGridLayout() self.setLayout(self.grid_layout) self.grid_layout.setHorizontalSpacing(50) # create 5 blocks self.create_input_block() self.create_method_used_block() self.create_output_block() self.create_graph_block() self.setGeometry(170, 100, 1600, 75E0) #self.setMinimumSize(1600, 500) self.setWindowTitle('Project2-Optimization') self.width = self.frameGeometry().width() self.height = self.frameGeometry().height() self.show() def create_input_block(self): self.input_open_button = QPushButton("open") self.input_open_button.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed) self.input_open_button.clicked.connect(self.open_file_dialog) self.input_clear_button = QPushButton("clear") self.input_clear_button.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed) self.input_clear_button.clicked.connect(self.input_clear) self.input_input_label = QLabel('Input:') input_h_box = QHBoxLayout() input_h_box.addWidget(self.input_open_button) input_h_box.addSpacing(50) input_h_box.addWidget(self.input_clear_button) self.input_list = QListWidget() input_v_box = QVBoxLayout() input_v_box.addWidget(self.input_input_label) input_v_box.addWidget(self.input_list) input_v_box.addLayout(input_h_box) self.grid_layout.addLayout(input_v_box, 0, 0) def create_method_used_block(self): # Combo Box to be used self.method_combobox = QComboBox(self) self.method_combobox.addItems(self.methods) # Buttons to be used self.method_reset_button = QPushButton("reset") self.method_reset_button.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed) self.method_reset_button.clicked.connect(self.method_reset) self.method_calculate_button = QPushButton("calculate") self.method_calculate_button.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed) self.method_calculate_button.clicked.connect(self.method_calculate) # Qlabel to be used self.method_method_used_label = QLabel('Method Used:') self.method_intial_interval_textbox = QPlainTextEdit() method_h2_box = QHBoxLayout() method_h2_box.addWidget(self.method_reset_button) method_h2_box.addWidget(self.method_calculate_button) method_v_box = QVBoxLayout() method_v_box.addWidget(self.method_method_used_label) method_v_box.addWidget(self.method_combobox) method_v_box.addWidget(self.method_intial_interval_textbox) method_v_box.addLayout(method_h2_box) self.grid_layout.addLayout(method_v_box, 0, 1) def create_output_block(self): self.output_textbox = QPlainTextEdit(QWidget().resize(640, 480)) self.output_textbox.setReadOnly(True) self.output_save_button = QPushButton("save") self.output_save_button.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed) self.output_save_button.clicked.connect(self.save_file_dialog) self.output_clear_button = QPushButton("clear") self.output_clear_button.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed) self.output_clear_button.clicked.connect(self.output_clear) self.output_output_label = QLabel('Output:') output_h_box = QHBoxLayout() output_h_box.addWidget(self.output_save_button) output_h_box.addWidget(self.output_clear_button) output_v_box = QVBoxLayout() output_v_box.addWidget(self.output_output_label) output_v_box.addWidget(self.output_textbox) output_v_box.addLayout(output_h_box) self.grid_layout.addLayout(output_v_box, 1, 0, 1, 2) def create_graph_block(self): ''' plot some random stuff ''' self.figure1.suptitle('3d') self.figure2.suptitle('2d') self.canvas1.draw() self.canvas2.draw() # self.figure2.legend() self.graph_error_texbox = QPlainTextEdit('Default graph(NULL)') self.graph_error_texbox.setReadOnly(True) self.graph_error_texbox.setMinimumSize(640, 110) self.hbox1 = QHBoxLayout() self.hbox2 = QHBoxLayout() self.hbox = QHBoxLayout() self.vbox = QVBoxLayout() self.hbox1.addWidget(self.canvas1) self.hbox2.addWidget(self.canvas2) self.hbox.addLayout(self.hbox1) self.hbox.addLayout(self.hbox2) self.vbox.addLayout(self.hbox) self.vbox.addWidget(self.graph_error_texbox) self.grid_layout.addLayout(self.vbox, 0, 2, 2, 2) def open_file_dialog(self): filename, _ = QFileDialog.getOpenFileName(self, "Open file", self.open_file_location, "Text Files (*.txt)") temp_pos = filename.rfind('/') if temp_pos: self.open_file_location = filename[:temp_pos + 1] if filename: with open(filename, 'rb') as file: read_data = file.read() udatabtype = read_data.decode("utf-8") asciidatabtype = udatabtype.encode("ascii", "ignore") asciidata = asciidatabtype.decode("ascii") read_data_list = asciidata.splitlines() self.input_list.addItems(read_data_list) def save_file_dialog(self): filename, _ = QFileDialog.getSaveFileName(self, "Save File", self.save_file_location, "Text Files (*.txt)") temp_pos = filename.rfind('/') self.save_file_location = filename[:temp_pos + 1] if filename: with open(filename, 'w') as file: file.write(self.output_textbox.toPlainText()) self.output_clear() def input_clear(self): self.input_list.clear() def output_clear(self): # clear textbox self.output_textbox.clear() # clear graph ''' clear windows ''' plt.figure(1) plt.clf() plt.figure(2) plt.clf() plt.close('all') ''' plot some random stuff ''' self.figure1 = plt.figure() self.figure2 = plt.figure() self.canvas1 = FigureCanvas(self.figure1) self.canvas2 = FigureCanvas(self.figure2) self.figure1.suptitle('3d') self.figure2.suptitle('2d') self.canvas1.draw() self.canvas2.draw() self.grid_layout.removeItem(self.hbox1) self.grid_layout.removeItem(self.hbox2) self.grid_layout.removeItem(self.hbox) self.grid_layout.removeItem(self.vbox) self.graph_error_texbox.setPlainText('Default graph(NULL)') self.hbox1 = QHBoxLayout() self.hbox2 = QHBoxLayout() self.hbox = QHBoxLayout() self.vbox = QVBoxLayout() self.hbox1.addWidget(self.canvas1) self.hbox2.addWidget(self.canvas2) self.hbox.addLayout(self.hbox1) self.hbox.addLayout(self.hbox2) self.vbox.addLayout(self.hbox) self.vbox.addWidget(self.graph_error_texbox) self.grid_layout.addLayout(self.vbox, 0, 2, 2, 2) def method_reset(self): self.method_intial_interval_textbox.setPlainText('') self.method_combobox.setCurrentIndex(0) def method_calculate(self): initial_interval = self.method_intial_interval_textbox.toPlainText() method = self.method_combobox.currentText() equation_item = self.input_list.currentItem() if equation_item is None: self.output_textbox.setPlainText('No equation string detected!\n') return elif method == 'None----': self.output_textbox.setPlainText('Method couldnt be None\n') return elif initial_interval == '': self.output_textbox.setPlainText('No initial point\n') return # global variables equation_str: str = None initial_point: List[float] = None intervals: List[List[float]] = None answer: str = None Xs: List[Arrai] = None vars_form: List[str] = None # exception added try: equation_str = equation_item.text() # get initial point and intervals initial_point, vars_form, intervals = get_ip_intervals( initial_interval) # manager = Manager(equation_str, vars_form, method, initial_point, intervals) manager = Manager(equation_str=equation_str, vars_form=vars_form, method_name=method, initial_point=initial_point, intervals=intervals) answer, Xs = manager.run() # write answer to output self.output_textbox.setPlainText(answer) except Exception as explosion: answer = explosion.args[0] self.output_textbox.setPlainText(answer) try: # draw out graph draw_graph(self, equation_str, vars_form, Xs, intervals) # catch graph drawing exception except: self.graph_error_texbox.setPlainText( 'Error while building graph!\n Current Equation: %s' % equation_str) def resizeEvent(self, a0: QResizeEvent) -> None: HeightIncreasement = self.frameGeometry().height() - self.height temp_size = 30 if abs(HeightIncreasement) - temp_size >= 0: # no pointer could be used in python self.change_font(self.input_input_label, HeightIncreasement / temp_size) self.change_font(self.method_method_used_label, HeightIncreasement / temp_size) self.change_font(self.output_output_label, HeightIncreasement / temp_size) self.change_font(self.input_open_button, HeightIncreasement / temp_size) self.change_font(self.input_clear_button, HeightIncreasement / temp_size) self.change_font(self.method_calculate_button, HeightIncreasement / temp_size) self.change_font(self.method_reset_button, HeightIncreasement / temp_size) self.change_font(self.output_save_button, HeightIncreasement / temp_size) self.change_font(self.output_clear_button, HeightIncreasement / temp_size) self.change_font(self.method_combobox, HeightIncreasement / temp_size) self.width = self.frameGeometry().width() self.height = self.frameGeometry().height() @staticmethod def change_font(label: QLabel, increasement: int): font = label.font() font.setPointSize(font.pointSize() + increasement) if font.pointSize() > 8: label.setFont(font)