def CreateFunctionTabs(self): self.functionTabWidget = QTabWidget() tab1 = QWidget() layout1 = QGridLayout() layout1.addWidget(self.ExpansionBox, 0, 0) layout1.setRowStretch(0, 0) tab1.setLayout(layout1) tab2 = QWidget() layout2 = QGridLayout() self.fixedorientcheckbox = QCheckBox(self.sliceTabWidget) self.fixedorientcheckbox.setText( "Fix orientation but allow zoom and translation") self.fixedorientcheckbox.clicked.connect(self.onFixedorient) layout2.addWidget(self.fixedorientcheckbox, 0, 0) layout2.addWidget(self.sliceTabWidget, 1, 0) tab2.setLayout(layout2) tab3 = QWidget() layout3 = QGridLayout() layout3.addWidget(self.RadiiScaleGroupBox, 0, 0) tab3.setLayout(layout3) tab4 = QWidget() layout4 = QGridLayout() layout4.addWidget(self.BinsGroupBox, 0, 0) tab4.setLayout(layout4) self.functionTabWidget.addTab(tab1, "Expand") self.functionTabWidget.addTab(tab2, "Slice") self.functionTabWidget.addTab(tab3, "Size") self.functionTabWidget.addTab(tab4, "Bins") self.functionTabWidget.setDisabled(True)
def createBottomRightGroupBox(self): self.bottomRightGroupBox = QGroupBox("Group 3") self.bottomRightGroupBox.setCheckable(True) self.bottomRightGroupBox.setChecked(True) lineEdit = QLineEdit('s3cRe7') lineEdit.setEchoMode(QLineEdit.Password) spinBox = QSpinBox(self.bottomRightGroupBox) spinBox.setValue(50) dateTimeEdit = QDateTimeEdit(self.bottomRightGroupBox) dateTimeEdit.setDateTime(QDateTime.currentDateTime()) slider = QSlider(Qt.Horizontal, self.bottomRightGroupBox) slider.setValue(40) scrollBar = QScrollBar(Qt.Horizontal, self.bottomRightGroupBox) scrollBar.setValue(60) dial = QDial(self.bottomRightGroupBox) dial.setValue(30) dial.setNotchesVisible(True) layout = QGridLayout() layout.addWidget(lineEdit, 0, 0, 1, 2) layout.addWidget(spinBox, 1, 0, 1, 2) layout.addWidget(dateTimeEdit, 2, 0, 1, 2) layout.addWidget(slider, 3, 0) layout.addWidget(scrollBar, 4, 0) layout.addWidget(dial, 3, 1, 2, 1) layout.setRowStretch(5, 1) self.bottomRightGroupBox.setLayout(layout)
def createMessageGroupBox(self): self.messageGroupBox = QGroupBox("Balloon Message") self.typeLabel = QLabel("Type:") self.typeComboBox = QComboBox() self.typeComboBox.addItem("None", QSystemTrayIcon.NoIcon) self.typeComboBox.addItem( self.style().standardIcon(QStyle.SP_MessageBoxInformation), "Information", QSystemTrayIcon.Information, ) self.typeComboBox.addItem( self.style().standardIcon(QStyle.SP_MessageBoxWarning), "Warning", QSystemTrayIcon.Warning, ) self.typeComboBox.addItem( self.style().standardIcon(QStyle.SP_MessageBoxCritical), "Critical", QSystemTrayIcon.Critical, ) self.typeComboBox.addItem(QIcon(), "Custom icon", -1) self.typeComboBox.setCurrentIndex(1) self.durationLabel = QLabel("Duration:") self.durationSpinBox = QSpinBox() self.durationSpinBox.setRange(5, 60) self.durationSpinBox.setSuffix(" s") self.durationSpinBox.setValue(15) self.durationWarningLabel = QLabel("(some systems might ignore this hint)") self.durationWarningLabel.setIndent(10) self.titleLabel = QLabel("Title:") self.titleEdit = QLineEdit("Cannot connect to network") self.bodyLabel = QLabel("Body:") self.bodyEdit = QTextEdit() self.bodyEdit.setPlainText("Don't believe me. Honestly, I don't have a clue." "\nClick this balloon for details.") self.showMessageButton = QPushButton("Show Message") self.showMessageButton.setDefault(True) messageLayout = QGridLayout() messageLayout.addWidget(self.typeLabel, 0, 0) messageLayout.addWidget(self.typeComboBox, 0, 1, 1, 2) messageLayout.addWidget(self.durationLabel, 1, 0) messageLayout.addWidget(self.durationSpinBox, 1, 1) messageLayout.addWidget(self.durationWarningLabel, 1, 2, 1, 3) messageLayout.addWidget(self.titleLabel, 2, 0) messageLayout.addWidget(self.titleEdit, 2, 1, 1, 4) messageLayout.addWidget(self.bodyLabel, 3, 0) messageLayout.addWidget(self.bodyEdit, 3, 1, 2, 4) messageLayout.addWidget(self.showMessageButton, 5, 4) messageLayout.setColumnStretch(3, 1) messageLayout.setRowStretch(4, 1) self.messageGroupBox.setLayout(messageLayout)
def build(self): self.setStyleSheet('QLabel {color: white}') layout = QGridLayout() self.setLayout(layout) layout.setRowStretch(0, 10) layout.setColumnStretch(3, 1) key_lbl = QLabel('{} Hotkeys:'.format(self.mode.title())) layout.addWidget(key_lbl, 1, 0, 1, 2) position = 2 for key, op in self.mapping.iteritems(): key_lbl = QLabel(key) layout.addWidget(key_lbl, position, 0, 1, 1) op_lbl = QLabel(op) layout.addWidget(op_lbl, position, 1, 1, 1) position += 1 # help_key_lbl = QLabel('h') # layout.addWidget(help_key_lbl, position, 0, 1, 1) # # help_lbl = QLabel('Toggle Help') # layout.addWidget(help_lbl, position, 1, 1, 1) layout.setRowStretch(position, 1)
def __init__(self, parent=None): super(WidgetGallery, self).__init__(parent) self.originalPalette = QApplication.palette() styleComboBox = QComboBox() styleComboBox.addItems(QStyleFactory.keys()) styleLabel = QLabel("&Style:") styleLabel.setBuddy(styleComboBox) self.useStylePaletteCheckBox = QCheckBox( "&Use style's standard palette") self.useStylePaletteCheckBox.setChecked(True) disableWidgetsCheckBox = QCheckBox("&Disable widgets") self.createTopLeftGroupBox() self.createTopRightGroupBox() self.createBottomLeftTabWidget() self.createBottomRightGroupBox() self.createProgressBar() styleComboBox.activated[str].connect(self.changeStyle) self.useStylePaletteCheckBox.toggled.connect(self.changePalette) disableWidgetsCheckBox.toggled.connect( self.topLeftGroupBox.setDisabled) disableWidgetsCheckBox.toggled.connect( self.topRightGroupBox.setDisabled) disableWidgetsCheckBox.toggled.connect( self.bottomLeftTabWidget.setDisabled) disableWidgetsCheckBox.toggled.connect( self.bottomRightGroupBox.setDisabled) topLayout = QHBoxLayout() topLayout.addWidget(styleLabel) topLayout.addWidget(styleComboBox) topLayout.addStretch(1) topLayout.addWidget(self.useStylePaletteCheckBox) topLayout.addWidget(disableWidgetsCheckBox) mainLayout = QGridLayout() mainLayout.addLayout(topLayout, 0, 0, 1, 2) mainLayout.addWidget(self.topLeftGroupBox, 1, 0) mainLayout.addWidget(self.topRightGroupBox, 1, 1) mainLayout.addWidget(self.bottomLeftTabWidget, 2, 0) mainLayout.addWidget(self.bottomRightGroupBox, 2, 1) mainLayout.addWidget(self.progressBar, 3, 0, 1, 2) mainLayout.setRowStretch(1, 1) mainLayout.setRowStretch(2, 1) mainLayout.setColumnStretch(0, 1) mainLayout.setColumnStretch(1, 1) self.setLayout(mainLayout) self.setWindowTitle("Common Qt Widgets") self.changeStyle('Fusion')
def __init__(self, parent=None): super(StyleWidget, self).__init__(parent) self.label_line_length = QLabel(u'Длина линии') self.spinbox_line_length = QSpinBox() self.spinbox_line_length.setMinimum(10) self.spinbox_line_length.setMaximum(250) self.spinbox_line_length.setSingleStep(10) self.spinbox_line_length.setValue(200) self.label_line_width = QLabel(u'Толщина линии') self.spinbox_line_width = QSpinBox() self.spinbox_line_width.setMinimum(1) self.spinbox_line_width.setMaximum(10) self.spinbox_line_width.setSingleStep(1) self.spinbox_line_width.setValue(2) self.label_circle_rad = QLabel(u'Радиус круга') self.spinbox_circle_rad = QSpinBox() self.spinbox_circle_rad.setMinimum(1) self.spinbox_circle_rad.setMaximum(30) self.spinbox_circle_rad.setSingleStep(1) self.spinbox_circle_rad.setValue(10) self.label_line_color = QLabel(u'Цвет линии') self.combobox_line_color = QComboBox() self.combobox_line_color.addItem(u'черный', 'black') self.combobox_line_color.addItem(u'красный', 'red') self.combobox_line_color.addItem(u'зеленый', 'green') self.combobox_line_color.addItem(u'синий', 'blue') self.checkbox_normalize_circle_rad = QCheckBox(u'Круги одинакового размера') layout = QGridLayout() layout.addWidget(self.label_line_length, 0, 0, Qt.AlignRight) layout.addWidget(self.spinbox_line_length, 0, 1) layout.addWidget(self.label_line_width, 1, 0, Qt.AlignRight) layout.addWidget(self.spinbox_line_width, 1, 1) layout.addWidget(self.label_circle_rad, 2, 0, Qt.AlignRight) layout.addWidget(self.spinbox_circle_rad, 2, 1) layout.addWidget(self.label_line_color, 3, 0, Qt.AlignRight) layout.addWidget(self.combobox_line_color, 3, 1) layout.addWidget(self.checkbox_normalize_circle_rad, 4, 0, 1, 2) layout.setRowStretch(5, 1) self.setLayout(layout) self.spinbox_line_length.valueChanged.connect(self.on_change) self.spinbox_line_width.valueChanged.connect(self.on_change) self.spinbox_circle_rad.valueChanged.connect(self.on_change) self.combobox_line_color.activated.connect(self.on_change) self.checkbox_normalize_circle_rad.stateChanged.connect(self.on_change) self.on_change()
def __init__(self, model, parent=None): super(BarChartWidget, self).__init__(parent) self.model = model grid = QGridLayout(self) # https://stackoverflow.com/questions/35946289/qt-qgridlayout-setrowstretch-not-working settingsGrid = QGridLayout(self) settingsGrid.addWidget(QLabel("Dataset"), 0, 0) self.datasetLabel = QLabel("no dataset") settingsGrid.addWidget(self.datasetLabel, 1, 0, 1, 2) settingsGrid.addWidget(QLabel("X Axis"), 2, 0) settingsGrid.addWidget(QLabel("Y Axis"), 3, 0) dataSetButton = QPushButton("Choose dataset", self) dataSetButton.clicked.connect(self.chooseDataset) self.xAxisComboBox = QComboBox(self) self.yAxisComboBox = QComboBox(self) settingsGrid.addWidget(dataSetButton, 0, 1) settingsGrid.addWidget(self.xAxisComboBox, 2, 1) settingsGrid.addWidget(self.yAxisComboBox, 3, 1) # settingsGrid.addWidget(QLabel("4"), 4, 1) createChartButton = QPushButton("Create Chart", self) createChartButton.clicked.connect(self.createChart) settingsGrid.addWidget(createChartButton, 4, 1) settingsGrid.setRowStretch(5, 10) grid.addLayout(settingsGrid, 0, 0) self.chart = QStackedWidget() grid.addWidget(self.chart, 0, 1) # self.chart.addWidget(QLabel("skka")) grid.setColumnStretch(0, 1) grid.setColumnStretch(1, 1) self.setLayout(grid) self.loadDataset("all_hour.csv")
def __init__(self): QMainWindow.__init__(self) icon = QIcon(ICON_IMAGE) self.setMinimumSize(300, 50) self.setWindowTitle("Echo VR Tray Tool") self.setWindowIcon(icon) main_widget = QWidget(self) self.setCentralWidget(main_widget) main_layout = QGridLayout(main_widget) discord_status_header = QLabel("Discord status:") discord_status_header.setFont(_HEADER_FONT) main_layout.addWidget(discord_status_header, 0, 0, Qt.AlignRight) self._discord_status_label = QLabel("Unknown") main_layout.addWidget(self._discord_status_label, 0, 1, Qt.AlignLeft) echo_vr_status_header = QLabel("Echo VR client status:") echo_vr_status_header.setFont(_HEADER_FONT) main_layout.addWidget(echo_vr_status_header, 1, 0, Qt.AlignRight) self._echo_vr_client_status_label = QLabel("Unknown") main_layout.addWidget(self._echo_vr_client_status_label, 1, 1, Qt.AlignLeft) main_layout.setRowStretch(2, 1) self.tray_icon = QSystemTrayIcon(icon, self) tray_menu = QMenu() show_action = QAction("Show", self) show_action.triggered.connect(self.show) tray_menu.addAction(show_action) quit_action = QAction("Exit", self) quit_action.triggered.connect(self._quit) tray_menu.addAction(quit_action) self.tray_icon.setContextMenu(tray_menu) self.tray_icon.show() self._discord_presence_thread = None self._start_discord_presence_thread()
def createExpansionBox(self): self.SpaceGroupComboBox = QComboBox() self.SpaceGroupComboBox.activated.connect(self.SpacegroupSelchange) self.SpacegroupLabel = QLabel() self.SpacegroupLabel.setText("Space Subgroups") self.mergecheckbox = QCheckBox() self.mergecheckbox.setText("Merge data") #self.mergecheckbox.setTristate (True) self.mergecheckbox.clicked.connect(self.MergeData) self.expandP1checkbox = QCheckBox() self.expandP1checkbox.setText("Expand to P1") self.expandP1checkbox.clicked.connect(self.ExpandToP1) self.expandAnomalouscheckbox = QCheckBox() self.expandAnomalouscheckbox.setText("Show Friedel pairs") self.expandAnomalouscheckbox.clicked.connect(self.ExpandAnomalous) self.sysabsentcheckbox = QCheckBox() self.sysabsentcheckbox.setText("Show Systematic Absences") self.sysabsentcheckbox.clicked.connect(self.showSysAbsent) self.missingcheckbox = QCheckBox() self.missingcheckbox.setText("Show Missing") self.missingcheckbox.clicked.connect(self.showMissing) self.onlymissingcheckbox = QCheckBox() self.onlymissingcheckbox.setText("Only Show Missing") self.onlymissingcheckbox.clicked.connect(self.showOnlyMissing) self.ExpansionBox = QGroupBox("Expansions") layout = QGridLayout() layout.addWidget(self.SpacegroupLabel, 0, 0) layout.addWidget(self.SpaceGroupComboBox, 0, 1) #layout.addWidget(self.mergecheckbox, 1, 0) layout.addWidget(self.expandP1checkbox, 1, 0) layout.addWidget(self.expandAnomalouscheckbox, 1, 1) layout.addWidget(self.sysabsentcheckbox, 2, 0) layout.addWidget(self.missingcheckbox, 3, 0) layout.addWidget(self.onlymissingcheckbox, 3, 1) layout.setRowStretch(0, 0) layout.setRowStretch(1, 0) layout.setRowStretch(2, 0) layout.setRowStretch(3, 1) self.ExpansionBox.setLayout(layout)
def make_ui(self): """Create and lay out UI elements.""" filter = QSpinBox() filter.setRange(1, 6) self.widgets['filter'] = filter btn_start = QPushButton() btn_start.setText('Start') btn_start.clicked.connect(self.run) self.widgets['btn_start'] = btn_start side_panel = QGridLayout() side_panel.setColumnStretch(0, 0) side_panel.setColumnStretch(1, 1) side_panel.setColumnStretch(2, 1) side_panel.setRowStretch(6, 1) # shove everything to the top side_panel.addWidget(QLabel('<h2>Controls</h2>'), 0, 0, 1, 2) side_panel.addWidget(QLabel('Filter:'), 1, 0) side_panel.addWidget(filter, 1, 1) side_panel.addWidget(btn_start, 2, 0, 1, 2) graph = FigureCanvas(Figure(tight_layout=True)) graph_toolbar = NavigationToolBar(graph, None) graph_toolbar.setObjectName('GraphToolBar') self.widgets['graph'] = graph axis = graph.figure.subplots() axis.grid() axis.set_xlim(0, 100) axis.set_ylim(0, 10) self.widgets['axis'] = axis vbox = QVBoxLayout() vbox.addWidget(graph) vbox.addWidget(graph_toolbar) hbox = QHBoxLayout() hbox.addLayout(side_panel) hbox.addLayout(vbox, 1) main_widget = QFrame() main_widget.setLayout(hbox) return main_widget
def __init__(self, close_event_callback: Event): super(MainWindow, self).__init__() self.close_event_callback = close_event_callback self.resize(700, 900) # main_wgt main_wgt = QWidget() self.setCentralWidget(main_wgt) self.setWindowTitle("RS Companion") # main_window/main_wgt <- main_grid grid = QGridLayout() main_wgt.setLayout(grid) # mdi self.mdi_win = mdi_win.MDIWidget() mdi = QMdiArea() # slider slider = QSlider() slider.setOrientation(Qt.Horizontal) # main_window/main_wgt-main_grid <- gb_control_bar grid.addWidget(self.set_controls(), 0, 0) grid.addWidget(self.set_key_flag(), 0, 1) grid.addWidget(self.set_notes(), 0, 2) grid.addWidget(self.set_information(), 0, 4) grid.addItem( QSpacerItem(300, 0, QSizePolicy.Minimum, QSizePolicy.Expanding), 0, 3) grid.addWidget(mdi, 1, 0, 1, 5) grid.addWidget(slider, 2, 0, 1, 5) grid.setRowStretch(1, 1) # menu self.set_menu() # QMDI subwindow # sub = QMdiSubWindow() # sub.resize(655, 515) # self.mid_text = QLabel("Nothing yet...") # self.mid_text.setText("what??") # sub.setWidget(self.mid_text) # sub.setWindowTitle("VOG COM32") # sub.setWindowIcon(self.create_icon_by_color(QColor("transparent"))) mdi.addSubWindow(self.mdi_win)
def __init__(self, parent=None): super(SettingsForm, self).__init__(parent) self.setWindowTitle("Settings") myGroupBox = QGroupBox("Stuff") layout = QGridLayout() layout.addWidget(parent.mousemoveslider, 0, 0, 1, 1) layout.addWidget(parent.mousesensitxtbox, 0, 3, 1, 3) layout.addWidget(parent.Fontsize_labeltxt, 1, 0, 1, 1) layout.addWidget(parent.fontspinBox, 1, 3, 1, 3) layout.addWidget(parent.cameraPerspectCheckBox, 2, 0, 1, 1) layout.setRowStretch(0, 1) layout.setRowStretch(1, 0) myGroupBox.setLayout(layout) mainLayout = QGridLayout() mainLayout.addWidget(myGroupBox, 0, 0) self.setLayout(mainLayout) self.setFixedSize(self.sizeHint())
class Widget(Layout): def __init__(self): super().__init__() # If needed, creates the base folders where data is stored self.create_base_folders() # Inits the ui self.initUI() def initUI(self): # Initialize main layout and add children self.grid = QGridLayout() self.grid.addLayout(self.stored_location_layout(), 0, 0, 1, 4) self.grid.addWidget(self.push_to_group_layout(), 1, 0, 1, 4) # Set the stretch of the rows self.grid.setRowStretch(1, 1) self.grid.setRowStretch(2, 1) self.grid.setContentsMargins(32, 32, 32, 32) self.setLayout(self.grid)
def __init__(self): super().__init__() self.setTitle("Dernière détection") self._image_label = QLabel() self._image_label.setAlignment(Qt.AlignCenter) self._image_label.setObjectName("image") self._filename_label = QLabel() self._filename_label.setAlignment(Qt.AlignCenter) main_layout = QGridLayout(self) main_layout.addWidget(self._image_label, 0, 0) main_layout.addWidget(self._filename_label, 1, 0) main_layout.setRowStretch(0, 1) main_layout.setVerticalSpacing(10) self.setLayout(main_layout) self._highlight_detections_thread = DrawDetectionsThread() self._highlight_detections_thread.imageLoadedSignal.connect( self._highlightedImageReceived)
def create_project_section(self): gbox_active_project = QGroupBox('Project') lbl_project_name = QLabel('Name:') self.lbl_project_name_value = QLabel('') lbl_elapsed_time = QLabel('Elapsed Time:') self.lbl_elapsed_time_value = QLabel('') lbl_remaining_time = QLabel('Remaining time:') self.lbl_remaining_time_value = QLabel('') lbl_step = QLabel('Current Step:') self.lbl_step_value = QLabel('') self.pbar_completion = QProgressBar() self.pbar_completion.setValue(0) # organise the fields in a grid layout = QGridLayout() layout.addWidget(lbl_project_name, 0, 0, Qt.AlignRight) layout.addWidget(self.lbl_project_name_value, 0, 1, 1, 3, Qt.AlignLeft) layout.addWidget(lbl_elapsed_time, 1, 0, Qt.AlignRight) layout.addWidget(self.lbl_elapsed_time_value, 1, 1, 1, 3, Qt.AlignLeft) layout.addWidget(lbl_remaining_time, 2, 0, Qt.AlignRight) layout.addWidget(self.lbl_remaining_time_value, 2, 1, 1, 3, Qt.AlignLeft) layout.addWidget(lbl_step, 3, 0,Qt.AlignRight) layout.addWidget(self.lbl_step_value, 3, 1, 1, 3, Qt.AlignLeft) layout.setRowStretch(5, 40) layout.addWidget(self.pbar_completion, 6, 0, 1, 4, Qt.AlignCenter) self.pbar_completion.setMinimumWidth(gbox_active_project.width() - 200) gbox_active_project.setLayout(layout) return gbox_active_project
class PageAllegroOptions(QWidget): def __init__(self, parent=None): QWidget.__init__(self) self.parent = parent self.parent.addWidget(self) self.auto_login, self.auto_pwd, self.auto_email, self.auto_time = data.get_autofill() self.gridLayout = QGridLayout(self) self.gridLayout.setContentsMargins(0, 0, 0, 0) self.gridLayout.setSpacing(0) self.gridLayout.setColumnStretch(0, 3) self.gridLayout.setColumnStretch(1, 7) self.pushButton_auto = QPushButton(self) self.pushButton_auto.setText("Autofill") self.pushButton_auto.setStyleSheet(styles.btn_allegro_ops_auto) self.pushButton_auto.setCheckable(True) self.pushButton_auto.setChecked(True) self.pushButton_auto.clicked.connect(lambda: self.on_auto()) self.gridLayout.addWidget(self.pushButton_auto, 0, 0, 1, 1) self.pushButton_help = QPushButton(self) self.pushButton_help.setText("Help") self.pushButton_help.setStyleSheet(styles.btn_allegro_ops_auto) self.pushButton_help.setCheckable(True) self.pushButton_help.setChecked(False) self.pushButton_help.clicked.connect(lambda: self.on_help()) self.gridLayout.addWidget(self.pushButton_help, 1, 0, 1, 1) self.spacer_btn_d = QSpacerItem(40, 20, QSizePolicy.Expanding) self.gridLayout.addItem(self.spacer_btn_d, 2, 0, 1, 1) self.stackedWidget = QStackedWidget(self) self.stackedWidget.setStyleSheet("""QStackedWidget{background-color: #fff;}""") self.gridLayout.addWidget(self.stackedWidget, 0, 1, 3, 1) self.widget_auto = QWidget(self.stackedWidget) self.widget_auto.setStyleSheet("""QWidget{background-color: #fff;}""") self.stackedWidget.addWidget(self.widget_auto) self.widget_help = QWidget(self.stackedWidget) self.widget_help.setStyleSheet("""QWidget{background-color: #fff;}""") self.stackedWidget.addWidget(self.widget_help) self.gridLayout_help = QVBoxLayout(self.widget_help) self.gridLayout_help.setContentsMargins(50, 50, 50, 50) self.gridLayout_help.setSpacing(50) self.label_help = QLabel(self.widget_help) self.label_help.setStyleSheet(styles.label_lineEdit) self.label_help.setWordWrap(True) self.label_help.setText(styles.help_text) self.gridLayout_help.addWidget(self.label_help) self.spacer_help = QSpacerItem(40, 20, QSizePolicy.Expanding) self.gridLayout_help.addItem(self.spacer_help) self.gridLayout_auto = QGridLayout(self.widget_auto) self.gridLayout_auto.setContentsMargins(0, 0, 0, 0) self.gridLayout_auto.setSpacing(20) self.gridLayout_auto.setColumnStretch(0, 1) self.gridLayout_auto.setColumnStretch(1, 1) self.gridLayout_auto.setColumnStretch(2, 1) self.gridLayout_auto.setColumnStretch(3, 1) self.gridLayout_auto.setRowStretch(0, 3) self.gridLayout_auto.setRowStretch(1, 1) self.gridLayout_auto.setRowStretch(2, 1) self.gridLayout_auto.setRowStretch(3, 1) self.gridLayout_auto.setRowStretch(4, 1) self.gridLayout_auto.setRowStretch(5, 1) self.gridLayout_auto.setRowStretch(6, 3) self.lineEdit_login = QLineEdit(self.widget_auto) self.lineEdit_login.setMinimumSize(QSize(0, 60)) self.lineEdit_login.setSizeIncrement(QSize(40, 40)) self.lineEdit_login.setStyleSheet(styles.lineEdit_opt) self.gridLayout_auto.addWidget(self.lineEdit_login, 1, 2, 1, 1) self.lineEdit_login.setPlaceholderText("login or email of your account") self.lineEdit_login.setText(self.auto_login) self.lineEdit_password = QLineEdit(self.widget_auto) self.lineEdit_password.setMinimumSize(QSize(20, 60)) self.lineEdit_password.setStyleSheet(styles.lineEdit_opt) self.lineEdit_password.setEchoMode(QLineEdit.Password) self.lineEdit_password.setReadOnly(False) self.gridLayout_auto.addWidget(self.lineEdit_password, 2, 2, 1, 1) self.lineEdit_password.setPlaceholderText("password of your account") self.lineEdit_password.setText(self.auto_pwd) self.lineEdit_email = QLineEdit(self.widget_auto) self.lineEdit_email.setMinimumSize(QSize(0, 60)) self.lineEdit_email.setStyleSheet(styles.lineEdit_opt) self.lineEdit_email.setFrame(True) self.lineEdit_email.setEchoMode(QLineEdit.Normal) self.gridLayout_auto.addWidget(self.lineEdit_email, 3, 2, 1, 1) self.lineEdit_email.setPlaceholderText("email to which the notification will be sent") self.lineEdit_email.setText(self.auto_email) self.lineEdit_time = QLineEdit(self.widget_auto) self.lineEdit_time.setMinimumSize(QSize(0, 60)) self.lineEdit_time.setStyleSheet(styles.lineEdit) self.gridLayout_auto.addWidget(self.lineEdit_time, 4, 2, 1, 1) self.lineEdit_time.setPlaceholderText("interval between refreshes") self.lineEdit_time.setText(str(self.auto_time)) self.label_login = QLabel("Allegro login", self) self.label_login.setStyleSheet(styles.label_lineEdit) self.gridLayout_auto.addWidget(self.label_login, 1, 1, 1, 1) self.label_password = QLabel("Allegro password", self) self.label_password.setStyleSheet(styles.label_lineEdit) self.gridLayout_auto.addWidget(self.label_password, 2, 1, 1, 1) self.label_email = QLabel("Email to notificate", self) self.label_email.setStyleSheet(styles.label_lineEdit) self.gridLayout_auto.addWidget(self.label_email, 3, 1, 1, 1) self.label_time = QLabel("Refresh time[s]", self) self.label_time.setStyleSheet(styles.label_lineEdit) self.gridLayout_auto.addWidget(self.label_time, 4, 1, 1, 1) self.pushButton_set = QPushButton("Set", self.widget_auto) self.pushButton_set.clicked.connect(lambda: self.on_set()) self.pushButton_set.setMinimumSize(QSize(0, 40)) self.pushButton_set.setStyleSheet(styles.btn_dark) self.gridLayout_auto.addWidget(self.pushButton_set, 5, 2, 1, 1) self.spacer_auto_l = QSpacerItem(40, 20, QSizePolicy.Expanding, QSizePolicy.Minimum) self.gridLayout_auto.addItem(self.spacer_auto_l, 1, 1, 1, 1) self.spacer_auto_r = QSpacerItem(40, 20, QSizePolicy.Expanding, QSizePolicy.Minimum) self.gridLayout_auto.addItem(self.spacer_auto_r, 1, 3, 1, 1) self.spacer_auto_t = QSpacerItem(40, 20, QSizePolicy.Expanding, QSizePolicy.Minimum) self.gridLayout_auto.addItem(self.spacer_auto_t, 0, 0, 1, 1) self.spacer_auto_b = QSpacerItem(40, 20, QSizePolicy.Expanding, QSizePolicy.Minimum) self.gridLayout_auto.addItem(self.spacer_auto_b, 6, 0, 1, 1) def on_set(self): data.add_autofill(self.lineEdit_login.text(), self.lineEdit_password.text(), self.lineEdit_email.text(), int(self.lineEdit_time.text())) auto_login, auto_pwd, auto_email, auto_time = data.get_autofill() self.parent.pageAllegroAdd.lineEdit_login.setText(auto_login) self.parent.pageAllegroAdd.lineEdit_password.setText(auto_pwd) self.parent.pageAllegroAdd.lineEdit_email.setText(auto_email) self.parent.pageAllegroAdd.lineEdit_time.setText(str(auto_time)) def on_auto(self): self.pushButton_auto.setChecked(True) self.pushButton_help.setChecked(False) self.stackedWidget.setCurrentIndex(0) def on_help(self): self.pushButton_auto.setChecked(False) self.pushButton_help.setChecked(True) self.stackedWidget.setCurrentIndex(1)
def __init__(self, controller, volt_max_limit, pwr_max_limit, heater_type=None, parent=None): super(HeaterSettings, self).__init__(controller.label, parent) self.heater_type = heater_type # Edits self.controller = controller self.volt_limit = ValueEdit('Max Voltage', '[V]', 'double') self.volt_limit.set_range_decimals(0., volt_max_limit, 3) self.volt_limit.set_single_step_size(.001) self.volt_limit.setValue(volt_max_limit) self.power_limit = ValueEdit('Max Power', '[mW]', 'double') self.power_limit.set_range_decimals(0., pwr_max_limit, 3) self.power_limit.set_single_step_size(.001) self.power_limit.setValue(pwr_max_limit) self.hr0 = ValueEdit('R\u2080', '[\u03A9]', 'double') self.hr0.set_range_decimals(0., 300, 3) # self.hr0.set_single_step_size(.001) self.hr0.edit.setReadOnly(True) self.hr0.setValue( self.controller.board.res_coeff[self.controller.channel][0]) self.hr1 = ValueEdit('R\u2081', '[\u03A9]', 'double') self.hr1.set_range_decimals(0., 300, 3) # self.hr1.set_single_step_size(.001) self.hr1.edit.setReadOnly(True) self.hr1.setValue( self.controller.board.res_coeff[self.controller.channel][1]) separator = QFrame() separator.setFrameShape(QFrame.HLine) separator.setFrameShadow(QFrame.Sunken) if self.heater_type == HeaterTypes.MRR: self.power_2pi = ValueEdit('Power for 2\u03C0', '[mW]', 'double') self.power_2pi.set_range_decimals(0., 900., 3) self.rt_length = ValueEdit('Roundtrip length', '[\u00B5m]', 'double') self.rt_length.set_range_decimals(500., 1000., 6) self.rt_length.setValue( self.controller.board.rtlenghts[self.controller.channel]) self.rt_length.edit.valueChanged.connect(self.update_fsr) self.pwr_coupling = ValueEdit('Power coupling', '', 'double') self.pwr_coupling.set_range_decimals(0., 1., 3) self.pwr_coupling.set_single_step_size(.01) self.pwr_coupling.setValue( self.controller.board.coupling_coeff[self.controller.channel]) self.fsr = ValueEdit('Ring FSR', '[nm]', 'double') self.fsr.edit.setReadOnly(True) self.fsr.set_range_decimals(0., 100., 3) self.update_fsr(self.rt_length.value()) edits1 = [ self.volt_limit, self.power_limit, self.power_2pi, separator, self.rt_length, self.pwr_coupling, self.fsr, self.hr0, self.hr1, ] elif self.heater_type == HeaterTypes.PHASE: self.power_2pi = ValueEdit('Power for 1\u03C0', '[mW]', 'double') self.power_2pi.set_range_decimals(0., 900., 3) self.fsr = ValueEdit('Cavity FSR', '[pm]', 'double') self.fsr.edit.setReadOnly(True) self.fsr.set_range_decimals(0., 200., 3) edits1 = [ self.volt_limit, self.power_limit, self.power_2pi, separator, self.fsr, self.hr0, self.hr1, ] elif self.heater_type == HeaterTypes.TC: self.power_2pi = ValueEdit('Power for 2\u03C0', '[mW]', 'double') self.power_2pi.set_range_decimals(0., 900., 3) edits1 = [ self.volt_limit, self.power_limit, self.power_2pi, self.hr0, self.hr1, ] # Layout layout = QGridLayout() for row, widget in enumerate(edits1): if widget != separator: layout.addWidget(widget.title, row, 0) layout.addWidget(widget.edit, row, 1) layout.addWidget(widget.unit, row, 2) else: layout.addWidget(separator, row, 0, 1, 3) layout.setRowStretch(row + 1, 1) self.setLayout(layout) # Signals and slots self.power_2pi.setValue( self.controller.board.pwr_2pi[self.controller.channel]) self.volt_limit.edit.valueChanged.connect(self.update_pwr) self.power_limit.edit.valueChanged.connect(self.update_voltage)
class Application(QMainWindow): def __init__(self, filename): super().__init__() self.resize(1200, 900) self.setWindowTitle('PandasVIS') # Initialize GUI elements self.init_gui() self.max_fig = False # Opens file (if argument was passed) if filename is not None: self.open_file() # Creates temp folder for temporary files self.temp_dir = os.path.join(os.getcwd(), 'temp') if not os.path.exists(self.temp_dir): os.makedirs(self.temp_dir, exist_ok=True) self.init_console() self.console.push_vars({'self': self}) self.load_modules() self.show() def init_gui(self): """Initiates GUI elements.""" mainMenu = self.menuBar() # File menu fileMenu = mainMenu.addMenu('File') # Adding actions to file menu action_open_file = QAction('Open File', self) fileMenu.addAction(action_open_file) action_open_file.triggered.connect(lambda: self.open_file(None)) self.toolsMenu = mainMenu.addMenu('Tools') self.tabularMenu = self.toolsMenu.addMenu('Tabular') self.timeseriesMenu = self.toolsMenu.addMenu('Time Series') helpMenu = mainMenu.addMenu('Help') action_about = QAction('About', self) helpMenu.addAction(action_about) action_about.triggered.connect(self.about) # Left panels ---------------------------------------------------------- self.bt_markall = QPushButton('Mark all') self.bt_markall.clicked.connect(self.mark_all) self.bt_unmarkall = QPushButton('Unmark all') self.bt_unmarkall.clicked.connect(self.unmark_all) self.bt_test = QPushButton(' ') self.bt_test.clicked.connect(self.test) self.tree_primary = QTreeCustomPrimary(parent=self) self.tree_primary.setAlternatingRowColors(True) self.tree_primary.setHeaderLabels(['Primary Variables', 'type']) self.tree_primary.setToolTip( "Columns of the Dataframe. Can be accessed\n" "in the console with the variable 'df'") self.tree_primary.itemClicked.connect(self.update_selected_primary) self.bt_toprimary = QPushButton('To primary') self.bt_toprimary.clicked.connect(self.to_primary) self.bt_tosecondary = QPushButton('To secondary') self.bt_tosecondary.clicked.connect(self.to_secondary) self.hbox_l1 = QHBoxLayout() self.hbox_l1.addWidget(self.bt_toprimary) self.hbox_l1.addWidget(self.bt_tosecondary) self.tree_secondary = QTreeCustomSecondary(parent=self) self.tree_secondary.setAlternatingRowColors(True) self.tree_secondary.setHeaderLabels(['Secondary Variables', 'type']) self.tree_secondary.setToolTip( "Secondary variables, can be added to the Dataframe.\n" "Can be accessed in the console with the variable \n" "'secondary_vars'") self.tree_secondary.itemClicked.connect(self.update_selected_secondary) self.df = pd.DataFrame(np.random.rand(100, 5), columns=['a', 'b', 'c', 'd', 'e']) names = ['aa', 'bb', 'cc'] nm = [names[ind % 3] for ind in np.arange(100)] self.df['name'] = nm names_2 = ['abcd', 'ab789', 'another_class', 'yet_another', 'dfg65'] nm_2 = [names_2[ind % 5] for ind in np.arange(100)] self.df['name_2'] = nm_2 self.primary_names = list(self.df.keys()) self.secondary_vars = {'var 3': np.zeros(100), 'var 4': np.zeros(100)} self.secondary_names = list(self.secondary_vars.keys()) self.init_trees() self.vbox1 = QVBoxLayout() self.vbox1.addLayout(self.hbox_l1) self.vbox1.addWidget(self.tree_secondary) self.wbox1 = QWidget() self.wbox1.setLayout(self.vbox1) self.vsplit1 = QSplitter(Qt.Vertical) self.vsplit1.addWidget(self.tree_primary) self.vsplit1.addWidget(self.wbox1) self.grid_left1 = QGridLayout() self.grid_left1.setColumnStretch(5, 1) self.grid_left1.addWidget(self.bt_markall, 0, 0, 1, 2) self.grid_left1.addWidget(self.bt_unmarkall, 0, 2, 1, 2) self.grid_left1.addWidget(self.bt_test, 0, 4, 1, 1) self.grid_left1.addWidget(self.vsplit1, 1, 0, 1, 6) self.left_widget = QWidget() self.left_widget.setLayout(self.grid_left1) # Center panels ------------------------------------------------------- # Top tabs self.tabs_top = QTabWidget() self.tab0 = QWidget() self.tabs_top.addTab(self.tab0, "Tools") # Bottom tabs self.tabs_bottom = QTabWidget() self.console = ConsoleWidget(par=self) self.console.setToolTip( "df --> Dataframe with Primary variables\n" "secondary_vars --> Dictionary with Secondary variables") self.logger = QTextEdit() self.logger.setReadOnly(True) self.tabs_bottom.addTab(self.console, "Console") self.tabs_bottom.addTab(self.logger, "Logger") self.righ_widget = QSplitter(Qt.Vertical) self.righ_widget.addWidget(self.tabs_top) self.righ_widget.addWidget(self.tabs_bottom) # Window layout -------------------------------------------------------- self.hbox = QSplitter(Qt.Horizontal) self.hbox.addWidget(self.left_widget) # add left panel self.hbox.addWidget(self.righ_widget) # add centre panel self.setCentralWidget(self.hbox) def test(self): pass def load_modules(self): # Main tools tab buttons layout self.tools_grid = QGridLayout() self.tools_grid.setColumnStretch(3, 1) self.lbl_tabular = QLabel("Tabular") self.tools_grid.addWidget(self.lbl_tabular, 0, 0, 1, 2) # modules and lambdas lists self.instances_list = [] self.modules_list = load_all_modules() self.lambdas_list = [(lambda a: lambda: self.instantiate_module(a))(o) for o in self.modules_list] for i, module in enumerate(self.modules_list): # Populates Menu bar action = QAction(module.menu_name, self) action.triggered.connect(self.lambdas_list[i]) if module.menu_parent == 'None': self.toolsMenu.addAction(action) if module.menu_parent == 'Tabular': self.tabularMenu.addAction(action) elif module.menu_parent == 'Time Series': self.timeseriesMenu.addAction(action) # Populates buttons tab btn = QPushButton(module.menu_name) btn.clicked.connect(self.lambdas_list[i]) self.tools_grid.addWidget(btn, 1, i, 1, 1) self.tools_grid.addWidget(QWidget(), 1, i + 1, 1, 1) self.tools_grid.addWidget(QWidget(), 2, 0, 1, 1) self.tools_grid.setRowStretch(3, 1) self.tab0.setLayout(self.tools_grid) def instantiate_module(self, module): """Instantiates a chosen module class.""" obj = module(self) # Check how many instances of same class already exist nInst = sum( [item.menu_name == obj.menu_name for item in self.instances_list]) obj.name += '_' + str(nInst) obj.run() self.instances_list.append(obj) def open_file(self, filename): ''' Open file and store it as a Pandas Dataframe.''' if filename is None: filename, ftype = QFileDialog.getOpenFileName( None, 'Open file', '', "(*.csv)") if ftype == '(*.csv)': self.file_path = filename self.setWindowTitle( 'PandasVIS - ' + os.path.split(os.path.abspath(self.file_path))[1]) # Load primary variables self.df = pd.read_csv(self.file_path) self.primary_names = self.df.keys().tolist() # Reset secondary variables self.secondary_vars = { 'var 3': np.zeros(100), 'var 4': np.zeros(100) } self.secondary_names = list(self.secondary_vars.keys()) # Reset GUI self.init_trees() self.init_console() def init_trees(self): ''' Draw hierarchical tree of fields in NWB file ''' self.tree_primary.clear() self.tree_secondary.clear() for var1 in self.primary_names: # primary variables list parent = QTreeWidgetItem(self.tree_primary, [var1, str(self.df[var1].dtype)]) parent.setFlags(parent.flags() | QtCore.Qt.ItemIsTristate | QtCore.Qt.ItemIsUserCheckable) parent.setCheckState(0, QtCore.Qt.Checked) for var2 in self.secondary_names: # secondary variables list parent = QTreeWidgetItem( self.tree_secondary, [var2, str(self.secondary_vars[var2].dtype)]) parent.setFlags(parent.flags() | QtCore.Qt.ItemIsTristate | QtCore.Qt.ItemIsUserCheckable) parent.setCheckState(0, QtCore.Qt.Checked) def init_console(self): ''' Initialize commands on console ''' self.console._execute("import pandas as pd", True) self.console._execute("import numpy as np", True) self.console._execute("import matplotlib.pyplot as plt", True) self.console.push_vars({'df': self.df}) self.console.push_vars({'secondary_vars': self.secondary_vars}) self.console.clear() self.console.print_text('df --> Dataframe with Primary variables\n') self.console.print_text( 'secondary_vars --> Dictionary with Secondary variables\n\n') def new_tab_top(self, object, title): """Opens new tab.""" self.tabs_top.addTab(object, title) nTabs = self.tabs_top.children()[0].count() self.tabs_top.setCurrentIndex(nTabs - 1) def new_tab_bottom(self, tab_object, title): """Opens new tab.""" self.tabs_bottom.addTab(tab_object, title) def close_tab_top(self, object): """Closes tab and removes associated objects""" name = object.name # Closes all child Threads object.close_threads() # Removes tab curr_ind = self.tabs_top.children()[0].currentIndex() self.tabs_top.removeTab(curr_ind) # Removes specific object instance from list self.instances_list.remove(object) # Deletes object form memory object.deleteLater() self.write_to_logger(name + ' deleted!') def write_to_logger(self, txt): time = datetime.datetime.now().time().strftime("%H:%M:%S") full_txt = "[" + time + "] " + txt self.logger.append(full_txt) def toggle_max_figure(self): if self.max_fig: self.left_widget.setMaximumWidth(1000) self.left_widget.resize(self.left_widget.sizeHint()) self.tabs_bottom.setMaximumHeight(1000) self.tabs_bottom.resize(self.tabs_bottom.sizeHint()) self.max_fig = False else: self.left_widget.setMaximumWidth(0) self.tabs_bottom.setMaximumHeight(0) self.max_fig = True def mark_all(self): """Iterate over all nodes of the tree and marks them.""" self.iterator = QTreeWidgetItemIterator(self.tree_primary, QTreeWidgetItemIterator.All) while self.iterator.value(): item = self.iterator.value() item.setCheckState(0, QtCore.Qt.Checked) self.iterator += 1 def unmark_all(self): """Iterate over all nodes of the tree and unmarks them.""" self.iterator = QTreeWidgetItemIterator(self.tree_primary, QTreeWidgetItemIterator.All) while self.iterator.value(): item = self.iterator.value() item.setCheckState(0, QtCore.Qt.Unchecked) self.iterator += 1 def update_selected_primary(self): """Iterate over all nodes of the tree and save selected items names to list""" self.selected_primary = [] self.iterator = QTreeWidgetItemIterator(self.tree_primary, QTreeWidgetItemIterator.All) while self.iterator.value(): item = self.iterator.value() if item.checkState( 0) == 2: # full-box checked, add item to dictionary self.selected_primary.append(item.text(0)) self.iterator += 1 def update_selected_secondary(self): """Iterate over all nodes of the tree and save selected items names to list""" self.selected_secondary = [] self.iterator = QTreeWidgetItemIterator(self.tree_secondary, QTreeWidgetItemIterator.All) while self.iterator.value(): item = self.iterator.value() if item.checkState( 0) == 2: # full-box checked, add item to dictionary self.selected_secondary.append(item.text(0)) self.iterator += 1 def to_primary(self): self.iterator = QTreeWidgetItemIterator(self.tree_secondary, QTreeWidgetItemIterator.All) selected = [] while self.iterator.value(): item = self.iterator.value() if item.checkState(0) == 2: # full-box checked selected.append(item.text(0)) self.iterator += 1 for var in selected: move_to_primary(self, var) def to_secondary(self): self.iterator = QTreeWidgetItemIterator(self.tree_primary, QTreeWidgetItemIterator.All) selected = [] while self.iterator.value(): item = self.iterator.value() if item.checkState(0) == 2: # full-box checked selected.append(item.text(0)) self.iterator += 1 for var in selected: move_to_secondary(self, var) def insert_from_file(): filename, ftype = QFileDialog.getOpenFileName(None, 'Open file', '', "(*.csv)") if ftype == '(*.csv)': self.file_path = filename # Load primary variables df_new = pd.read_csv(self.file_path) self.primary_names = self.df.keys().tolist() def closeEvent(self, event): """Before exiting, deletes temporary files.""" shutil.rmtree(self.temp_dir, ignore_errors=False, onerror=None) event.accept() def about(self): """About dialog.""" msg = QMessageBox() msg.setWindowTitle("About PandasVIS") msg.setIcon(QMessageBox.Information) msg.setText( "Version: 1.0.0 \n" "Data exploration GUI, with Data Science and Machine Learning embedded tools.\n " ) msg.setInformativeText( "<a href='https://github.com/luiztauffer/pandasVIS'>PandasVIS Github page</a>" ) msg.setStandardButtons(QMessageBox.Ok) msg.exec_()
class AboutDialog(QDialog): SOFTWARE_HEADER_NAMES = ['Software', 'License'] def __init__(self, parent=None): super().__init__(parent) self.setFixedSize(500, 420) self.setWindowModality(Qt.ApplicationModal) self.setWindowTitle('About HwMonitorAlignment') self._layout = QGridLayout() self._read_libraries() self.header_label = QLabel(self) self.header_label.setPixmap( load_pixmap('icon.ico').scaled(125, 125, Qt.KeepAspectRatio)) # self.header_label.setPixmap(QPixmap('doc/hma_logo_left.png').scaledToWidth(480)) self._layout.addWidget(self.header_label, 0, 0) self.short_info = QLabel() self.short_info.setAlignment(Qt.AlignCenter) self.short_info.setText('<h2>{0} {1}</h2>' '<p>{2}</p>' '<a href="{3}">Project website</a>'.format( str(hwmonitor.__name__), str(hwmonitor.__version__), str(hwmonitor.__description__), str(hwmonitor.__website__))) self.short_info.setWordWrap(True) self.short_info.setOpenExternalLinks(True) self._layout.addWidget(self.short_info, 0, 1) # spacer self._layout.addWidget(QWidget(), 0, 2, 1, 1) # Info tabs self.tab_widget = QTabWidget(self) self._layout.addWidget(self.tab_widget, 2, 0, 1, 3) # Software Licenses Widget self.library_table = QTableWidget(len(self._libraries), 2, self.tab_widget) self.library_table.setHorizontalHeaderLabels( self.SOFTWARE_HEADER_NAMES) self.library_table.horizontalHeader().setStretchLastSection(True) self.library_table.setEditTriggers(QTableWidget.NoEditTriggers) self.library_table.setSelectionMode(QTableWidget.NoSelection) self.library_table.verticalHeader().hide() self.library_table.setColumnWidth(0, int(self.width() / 3 * 1.8)) self.library_table.setShowGrid(False) self.tab_widget.addTab(self.library_table, 'Third-party software components') # Buttons self.dialog_buttons = QDialogButtonBox(Qt.Horizontal, self) self.dialog_buttons.setStyleSheet('* { button-layout: 2 }') self.close_button = self.dialog_buttons.addButton( "Close", QDialogButtonBox.AcceptRole) self.about_button = self.dialog_buttons.addButton( "About Qt", QDialogButtonBox.HelpRole) self.close_button.clicked.connect(self.accept) self.about_button.clicked.connect(qApp.aboutQt) self._layout.addWidget(self.dialog_buttons, 3, 0, 1, 3) self._layout.setColumnStretch(0, 1) self._layout.setColumnStretch(1, 3) self._layout.setRowStretch(0, 6) self._layout.setRowStretch(1, 1) self._layout.setRowStretch(2, 16) self._layout.setRowStretch(3, 3) self.setLayout(self._layout) self._populate_library_tree() def _read_libraries(self): """Reads all libraries and licenses from included 'licenses' . +--library_name | +--version: 0.1 | +--license: MIT | +--library_url: http://library.org | +--license_url: http://license.com . . """ import sys import PySide2 self._libraries = { 'python': { 'version': '{0}.{1}.{2}-{3}'.format(*sys.version_info), 'license': 'PSF', 'library_url': 'http://www.python.org', 'license_url': 'http://docs.python.org/3/license.html' }, 'PySide2': { 'version': PySide2.__version__, 'license': 'GNU LGPL v3', 'library_url': 'http://www.qt.io/qt-for-python', 'license_url': 'https://doc.qt.io/qt-5/lgpl.html' }, 'Components of linux-show-player': { 'version': '', 'license': 'GNU GPL v3', 'library_url': 'https://github.com/FrancescoCeruti/linux-show-player', 'license_url': 'https://github.com/FrancescoCeruti/linux-show-player/blob/master/LICENSE' } } def _populate_library_tree(self): """Puts every library name and license into model for library view """ for i, library in enumerate(self._libraries): library_info = self._libraries[library] library_text = '<a href="{0}">{1}</a> <font color="#777">{2}</font>'.format( library_info['library_url'], library, library_info['version']) license_text = '<a href="{0}">{1}</a>'.format( library_info['license_url'], library_info['license']) name_label, license_label = self._library_item_widgets( library_text, license_text) self.library_table.setCellWidget(i, 0, name_label) self.library_table.setCellWidget(i, 1, license_label) @staticmethod def _library_item_widgets(library_text, license_text): name_label = QLabel() name_label.setText(library_text) name_label.setTextFormat(Qt.RichText) name_label.setTextInteractionFlags(Qt.TextBrowserInteraction) name_label.setOpenExternalLinks(True) name_label.setMargin(5) license_label = QLabel() license_label.setText(license_text) license_label.setTextFormat(Qt.RichText) license_label.setTextInteractionFlags(Qt.TextBrowserInteraction) license_label.setOpenExternalLinks(True) return name_label, license_label
class PropertiesWidget(QWidget): def __init__(self, parent, obj): super(PropertiesWidget, self).__init__() self.obj = obj self.parent = parent self.grid = QGridLayout() self.grid.setSizeConstraint(self.grid.SetMinAndMaxSize) title = Label("Propriété : " + self.obj.type_, 16) title.setMaximumHeight(80) title.setMinimumHeight(80) title.setAlignment(Qt.AlignHCenter) self.grid.addWidget(title, 0, 0, 1, 2) self.grid.setRowStretch(0, 1) nb = 1 for p in get_properties(self.obj.type_): label = Label(p[0], 12) label.setMaximumHeight(50) label.setMinimumHeight(50) self.grid.addWidget(label, nb, 0) if p[1] == "str": widget = QLineEdit() if p[0] == "Nom": widget.setText(self.obj.name) else: widget.setText(self.obj.properties.get(p[0], "")) widget.textChanged.connect( lambda text="", prop=p[0]: self.set_text_for(text, prop)) elif p[1] == "bool": widget = QCheckBox() if self.obj.properties.get(p[0], False): widget.setChecked(True) widget.stateChanged.connect( lambda state=0, prop=p[0]: self.set_bool_for(state, prop)) elif p[1] == "int": widget = QSpinBox() widget.setMaximum(3000) widget.setMinimum(-3000) widget.setValue(self.obj.properties.get(p[0], 0)) widget.valueChanged.connect( lambda value=0, prop=p[0]: self.set_int_for(value, prop)) elif "|" in p[1] and p[1].split("|")[0] == "list": widget = QComboBox() for i in p[1].split("|")[1].split(", "): widget.addItem(i) widget.setCurrentText( self.obj.properties.get(p[0], p[1].split("|")[1].split(", ")[0])) widget.currentTextChanged.connect( lambda value="", prop=p[0]: self.set_text_for(value, prop)) elif p[1] == "color": widget = QPushButton("Sélectionner") widget.clicked.connect( lambda checked=False, prop=p[0]: self.set_color_for(prop)) elif p[1] == "colorNone": widget = QWidget() layout = QGridLayout() select = QPushButton("Sélectionner") select.clicked.connect( lambda checked=False, prop=p[0]: self.set_color_for(prop)) delete = QPushButton("Supprimer") delete.clicked.connect( lambda checked=False, prop=p[0]: self.set_none_for(prop)) layout.addWidget(select, 0, 0) layout.addWidget(delete, 0, 1) widget.setLayout(layout) elif p[1] == "file": widget = QPushButton("Sélectionner") widget.clicked.connect( lambda checked=False, prop=p[0]: self.set_file_for(prop)) elif p[1] == "fileNone": widget = QWidget() layout = QGridLayout() select = QPushButton("Sélectionner") select.clicked.connect( lambda checked=False, prop=p[0]: self.set_file_for(prop)) delete = QPushButton("Supprimer") delete.clicked.connect( lambda checked=False, prop=p[0]: self.set_none_for(prop)) layout.addWidget(select, 0, 0) layout.addWidget(delete, 0, 1) widget.setLayout(layout) elif p[1] == "files": widget = QPushButton("Sélectionner") widget.clicked.connect( lambda checked=False, prop=p[0]: self.set_files_for(prop)) else: raise TypeError("Unknown type for properties : " + p[1]) self.grid.addWidget(widget, nb, 1) self.grid.setRowStretch(nb, 1) nb += 1 scripting = QPushButton("Modifier Script") scripting.clicked.connect(self.edit_script) self.grid.addWidget(scripting, nb, 0, 1, 2) end_spacer = QSpacerItem(20, 20, QSizePolicy.Preferred, QSizePolicy.Expanding) self.grid.addItem(end_spacer, nb + 1, 0) for i in range(0, 2): self.grid.setColumnStretch(i, 1) self.setLayout(self.grid) def edit_script(self): if self.obj.type_ != "None": self.parent.editor = Editor(self.parent, self.obj) self.parent.editor.showMaximized() self.parent.affichage.update_screen() def set_text_for(self, text, prop): self.obj.set_property(prop, text) if prop == "Nom": if self.parent.project.objects[0].properties[ "Monde Actuel"] == self.obj.name: self.parent.project.objects[0].properties[ "Monde Actuel"] = text element = self.parent.elements.get_item(self.obj.name) if element is not None: element.setText(0, text) self.obj.name = text self.parent.affichage.update_screen() def set_bool_for(self, state, prop): self.obj.set_property(prop, bool(state)) self.parent.affichage.update_screen() def set_int_for(self, value, prop): self.obj.set_property(prop, value) self.parent.affichage.update_screen() def set_none_for(self, prop): self.obj.set_property(prop, None) self.parent.affichage.update_screen() def set_file_for(self, prop): directory = os.environ.get( 'HOME', os.environ.get('USERPROFILE', os.path.dirname(__file__))) self.obj.set_property( prop, QFileDialog.getOpenFileName(self, "Fichier : " + prop, directory)[0]) self.parent.affichage.update_screen() def set_files_for(self, prop): directory = os.environ.get( 'HOME', os.environ.get('USERPROFILE', os.path.dirname(__file__))) self.obj.set_property( prop, QFileDialog.getOpenFileNames(self, "Fichiers : " + prop, directory)[0]) self.parent.affichage.update_screen() def set_color_for(self, prop): if self.obj.properties[prop] is not None: qcolor = QColorDialog.getColor(QColor(*self.obj.properties[prop])) else: qcolor = QColorDialog.getColor() self.obj.set_property( prop, [qcolor.red(), qcolor.green(), qcolor.blue()]) self.parent.affichage.update_screen()
def __init__(self, parent=None): super(NGL_HKLViewer, self).__init__(parent) self.verbose = 0 self.UseOSbrowser = False self.jscriptfname = "" self.devmode = False for e in sys.argv: if "verbose" in e: self.verbose = e.split("verbose=")[1] if "UseOSbrowser" in e: self.UseOSbrowser = e.split("UseOSbrowser=")[1] if "jscriptfname" in e: self.jscriptfname = e.split("jscriptfname=")[1] if "devmode" in e: self.devmode = True self.zmq_context = None self.bufsize = 20000 self.originalPalette = QApplication.palette() self.openFileNameButton = QPushButton("Load reflection file") self.openFileNameButton.setDefault(True) self.openFileNameButton.clicked.connect(self.OpenReflectionsFile) self.debugbutton = QPushButton("Debug") self.debugbutton.clicked.connect(self.DebugInteractively) self.settingsbtn = QPushButton("Settings") self.settingsbtn.clicked.connect(self.SettingsDialog) self.mousemoveslider = QSlider(Qt.Horizontal) self.mousemoveslider.setMinimum(0) self.mousemoveslider.setMaximum(300) self.mousemoveslider.setValue(0) self.mousemoveslider.sliderReleased.connect( self.onFinalMouseSensitivity) self.mousemoveslider.valueChanged.connect(self.onMouseSensitivity) self.mousesensitxtbox = QLineEdit('') self.mousesensitxtbox.setReadOnly(True) self.fontspinBox = QDoubleSpinBox() self.fontspinBox.setSingleStep(1) self.fontspinBox.setRange(4, 50) self.font = QFont() self.font.setFamily(self.font.defaultFamily()) self.fontspinBox.setValue(self.font.pointSize()) #self.fontspinBox.setValue(self.font.pixelSize()) self.fontspinBox.valueChanged.connect(self.onFontsizeChanged) self.Fontsize_labeltxt = QLabel() self.Fontsize_labeltxt.setText("Font size:") self.cameraPerspectCheckBox = QCheckBox() self.cameraPerspectCheckBox.setText("Perspective camera") self.cameraPerspectCheckBox.clicked.connect(self.onCameraPerspect) self.cameraPerspectCheckBox.setCheckState(Qt.Unchecked) self.settingsform = SettingsForm(self) self.MillerComboBox = QComboBox() self.MillerComboBox.activated.connect(self.onMillerComboSelchange) #self.MillerComboBox.setSizeAdjustPolicy(QComboBox.AdjustToContents) self.MillerLabel = QLabel() self.MillerLabel.setText("Selected HKL Scene") self.HKLnameedit = QLineEdit('') self.HKLnameedit.setReadOnly(True) self.textInfo = QTextEdit() self.textInfo.setLineWrapMode(QTextEdit.NoWrap) self.textInfo.setReadOnly(True) labels = [ "Label", "Type", "no. of HKLs", "Span of HKLs", "Min Max data", "Min Max sigmas", "d_min, d_max", "Symmetry unique", "Anomalous" ] self.millertable = QTableWidget(0, len(labels)) self.millertable.setHorizontalHeaderLabels(labels) self.millertable.horizontalHeader().setDefaultAlignment(Qt.AlignLeft) # don't allow editing this table self.millertable.setEditTriggers(QTableWidget.NoEditTriggers) self.createExpansionBox() self.createFileInfoBox() self.CreateSliceTabs() self.createRadiiScaleGroupBox() self.createBinsBox() self.CreateFunctionTabs() mainLayout = QGridLayout() mainLayout.addWidget(self.FileInfoBox, 0, 0) mainLayout.addWidget(self.MillerLabel, 1, 0) mainLayout.addWidget(self.MillerComboBox, 2, 0) mainLayout.addWidget(self.functionTabWidget, 3, 0) mainLayout.addWidget(self.settingsbtn, 4, 0, 1, 1) #import code, traceback; code.interact(local=locals(), banner="".join( traceback.format_stack(limit=10) ) ) if self.UseOSbrowser == False: self.BrowserBox = QWebEngineView() mainLayout.addWidget(self.BrowserBox, 0, 1, 5, 3) self.BrowserBox.setUrl("https://cctbx.github.io/") #self.BrowserBox.setUrl("https://webglreport.com/") #self.BrowserBox.loadFinished.connect(self.onLoadFinished) mainLayout.setColumnStretch(2, 1) mainLayout.setRowStretch(0, 1) mainLayout.setRowStretch(1, 0) mainLayout.setRowStretch(2, 1) mainLayout.setRowStretch(3, 1) mainLayout.setColumnStretch(4, 0) self.setLayout(mainLayout) self.setWindowTitle("HKL-Viewer") self.cctbxproc = None self.LaunchCCTBXPython() self.out = None self.err = None self.comboviewwidth = 0 self.hklscenes_arrays = [] self.array_infotpls = [] self.matching_arrays = [] self.bin_infotpls = None self.bin_opacities = None self.html_url = "" self.spacegroups = [] self.info = [] self.infostr = "" self.fileisvalid = False self.NewFileLoaded = False self.NewHKLscenes = False self.updatingNbins = False self.binstableitemchanges = False self.show()
def __init__(self, parent=None): super(WidgetGallery, self).__init__(parent) # System State self.adc_scale = 1 self.adc_decimation = 1 self.offset = 0 self.samples = None self.serial_state = None self.serial_state_timeout = time.time() self.originalPalette = QApplication.palette() QApplication.setStyle(QStyleFactory.create("Fusion")) serial_label = QLabel() serial_label.setText("Serial Port:") self.Serial_Handel = serial.Serial() self.Serial_Handel.timeout = 0 self.Serial_Handel.baudrate = 115200 self.serial_lock = QtCore.QMutex() self.serial_thread = SerialThread(self.Serial_Handel, self.serial_lock, self.command_callback) self.serial_thread.start() self.Serial_Port_Box = SelfPopulatingComboBox() self.Serial_Port_Box.view().setMinimumWidth(30) self.update_ports() self.Serial_Port_Box.setCurrentIndex(0) self.port_list = dict() self.Serial_Port_Box.popupAboutToBeShown.connect(self.update_ports) self.Serial_Port_Box.currentIndexChanged.connect(self.selected_port) # create plot self.main_plot = pyqtgraph.PlotWidget() self.curve = self.main_plot.plot() self.curve.setPen((200, 200, 100)) self.main_plot.getAxis('left').setGrid(255) self.main_plot.getAxis('bottom').setGrid(255) self.curve.getViewBox().setMouseMode(pyqtgraph.ViewBox.RectMode) self.ControlGroupBox = QGroupBox("Controls") self.create_control_group_box() topLayout = QHBoxLayout() topLayout.addStretch(1) topLayout.addWidget(serial_label) topLayout.addWidget(self.Serial_Port_Box, 2) self.label_font = QtGui.QFont("Times", 600, QtGui.QFont.Bold) self.bottom_layout = QHBoxLayout() self.bottom_layout.addStretch(1) measurement_label = QLabel() measurement_label.setText("Measurements:") measurement_label.setFont(self.label_font) self.measurements_list = list() self.measurements_functions = [ measurements.meas_pk_pk, measurements.meas_rms, measurements.meas_average, None ] for i in range(4): print("{}: N/A".format(i + 1)) meas_n = QLabel() meas_n.setText("{}: N/A".format(i + 1)) meas_n.setAlignment(QtCore.Qt.AlignLeft) self.measurements_list.append(meas_n) self.bottom_layout.addWidget(meas_n, alignment=QtCore.Qt.AlignLeft) mainLayout = QGridLayout() mainLayout.addLayout(topLayout, 0, 0, 1, 2) mainLayout.addWidget(self.main_plot, 1, 0, 2, 1) mainLayout.addWidget(self.ControlGroupBox, 1, 1, 2, 1) mainLayout.addLayout(self.bottom_layout, 3, 0, 1, 2, alignment=QtCore.Qt.AlignLeft) mainLayout.setRowMinimumHeight(3, 20) mainLayout.setRowStretch(1, 1) mainLayout.setRowStretch(2, 1) mainLayout.setColumnStretch(0, 10) mainLayout.setColumnStretch(1, 1) self.cent_widget = QWidget(self) self.setCentralWidget(self.cent_widget) self.cent_widget.setLayout(mainLayout) self.setWindowTitle("Probe-Scope Acquisition")
def __init__(self, config): assertMainThread() super().__init__(config) # state self.preventSeek = False self.beginTime = None self.timeRatio = 1.0 # gui srv = Services.getService("MainWindow") config.configLoaded.connect(self.restoreState) config.configAboutToSave.connect(self.saveState) self.config = config playbackMenu = srv.menuBar().addMenu("&Playback") style = QApplication.style() self.actStart = QAction(QIcon.fromTheme("media-playback-start", style.standardIcon(QStyle.SP_MediaPlay)), "Start Playback", self) self.actPause = QAction(QIcon.fromTheme("media-playback-pause", style.standardIcon(QStyle.SP_MediaPause)), "Pause Playback", self) self.actPause.setEnabled(False) self.actStepFwd = QAction(QIcon.fromTheme("media-seek-forward", style.standardIcon(QStyle.SP_MediaSeekForward)), "Step Forward", self) self.actStepBwd = QAction(QIcon.fromTheme("media-seek-backward", style.standardIcon(QStyle.SP_MediaSeekBackward)), "Step Backward", self) self.actSeekEnd = QAction(QIcon.fromTheme("media-skip-forward", style.standardIcon(QStyle.SP_MediaSkipForward)), "Seek End", self) self.actSeekBegin = QAction(QIcon.fromTheme("media-skip-backward", style.standardIcon(QStyle.SP_MediaSkipBackward)), "Seek Begin", self) self.actSetTimeFactor = {r : QAction("x 1/%d" % (1/r), self) if r < 1 else QAction("x %d" % r, self) for r in (1/8, 1/4, 1/2, 1, 2, 4, 8)} # pylint: disable=unnecessary-lambda # let's stay on the safe side and do not use emit as a slot... self.actStart.triggered.connect(lambda: self._startPlayback.emit()) self.actPause.triggered.connect(lambda: self._pausePlayback.emit()) self.actStepFwd.triggered.connect(lambda: self._stepForward.emit(self.selectedStream())) self.actStepBwd.triggered.connect(lambda: self._stepBackward.emit(self.selectedStream())) self.actSeekEnd.triggered.connect(lambda: self._seekEnd.emit()) self.actSeekBegin.triggered.connect(lambda: self._seekBeginning.emit()) # pylint: enable=unnecessary-lambda def setTimeFactor(newFactor): logger.debug("new time factor %f", newFactor) self._setTimeFactor.emit(newFactor) for r in self.actSetTimeFactor: logger.debug("adding action for time factor %f", r) self.actSetTimeFactor[r].triggered.connect(functools.partial(setTimeFactor, r)) self.dockWidget = srv.newDockWidget("PlaybackControl", None, Qt.LeftDockWidgetArea) self.dockWidgetContents = QWidget(self.dockWidget) self.dockWidget.setWidget(self.dockWidgetContents) toolLayout = QBoxLayout(QBoxLayout.TopToBottom, self.dockWidgetContents) toolLayout.setContentsMargins(0, 0, 0, 0) toolBar = QToolBar() toolLayout.addWidget(toolBar) toolBar.addAction(self.actSeekBegin) toolBar.addAction(self.actStepBwd) toolBar.addAction(self.actStart) toolBar.addAction(self.actPause) toolBar.addAction(self.actStepFwd) toolBar.addAction(self.actSeekEnd) playbackMenu.addAction(self.actSeekBegin) playbackMenu.addAction(self.actStepBwd) playbackMenu.addAction(self.actStart) playbackMenu.addAction(self.actPause) playbackMenu.addAction(self.actStepFwd) playbackMenu.addAction(self.actSeekEnd) playbackMenu.addSeparator() for r in self.actSetTimeFactor: playbackMenu.addAction(self.actSetTimeFactor[r]) self.timeRatioLabel = QLabel("x 1") self.timeRatioLabel.addActions(list(self.actSetTimeFactor.values())) self.timeRatioLabel.setContextMenuPolicy(Qt.ActionsContextMenu) toolBar.addSeparator() toolBar.addWidget(self.timeRatioLabel) contentsLayout = QGridLayout() toolLayout.addLayout(contentsLayout, 10) # now we add a position view self.positionSlider = QSlider(Qt.Horizontal, self.dockWidgetContents) self.beginLabel = QLabel(parent=self.dockWidgetContents) self.beginLabel.setAlignment(Qt.AlignLeft|Qt.AlignCenter) self.currentLabel = QLabel(parent=self.dockWidgetContents) self.currentLabel.setAlignment(Qt.AlignHCenter|Qt.AlignCenter) self.endLabel = QLabel(parent=self.dockWidgetContents) self.endLabel.setAlignment(Qt.AlignRight|Qt.AlignCenter) contentsLayout.addWidget(self.beginLabel, 0, 0, alignment=Qt.AlignLeft) contentsLayout.addWidget(self.currentLabel, 0, 1, alignment=Qt.AlignHCenter) contentsLayout.addWidget(self.endLabel, 0, 2, alignment=Qt.AlignRight) contentsLayout.addWidget(self.positionSlider, 1, 0, 1, 3) self.positionSlider.setTracking(False) self.positionSlider.valueChanged.connect(self.onSliderValueChanged, Qt.DirectConnection) self.positionSlider.sliderMoved.connect(self.displayPosition) # file browser self.browser = BrowserWidget(self.dockWidget) self.nameFiltersChanged.connect(self._onNameFiltersChanged, Qt.QueuedConnection) contentsLayout.addWidget(self.browser, 3, 0, 1, 3) contentsLayout.setRowStretch(3, 100) self.browser.activated.connect(self.browserActivated) self.actShowAllFiles = QAction("Show all files") self.actShowAllFiles.setCheckable(True) self.actShowAllFiles.setChecked(False) self.actShowAllFiles.toggled.connect(self._onShowAllFiles) playbackMenu.addSeparator() playbackMenu.addAction(self.actShowAllFiles) self.actGroupStream = QActionGroup(self) self.actGroupStream.setExclusionPolicy(QActionGroup.ExclusionPolicy.ExclusiveOptional) playbackMenu.addSeparator() self.actGroupStreamMenu = playbackMenu.addMenu("Step Stream") self._selectedStream = None self.recentSeqs = [QAction() for i in range(10)] playbackMenu.addSeparator() recentMenu = playbackMenu.addMenu("Recent") for a in self.recentSeqs: a.setVisible(False) a.triggered.connect(self.openRecent) recentMenu.addAction(a) self._supportedFeaturesChanged(set(), set())
class App(QMainWindow): def __init__(self): super().__init__() self.init_ui() self.attach_event() self.setAcceptDrops(True) def init_ui(self): # Define & Configure Components normal_button_size = QSize(80, 24) icon_button_size = QSize(24, 24) icon_size = QSize(18, 18) self.central_widget = QWidget() self.central_layout = QGridLayout() self.central_widget.setLayout(self.central_layout) self.tab_group_widget = QTabWidget() self.tab_group_widget.setMinimumSize(400, 0) self.tab_group_widget.setFixedHeight(150) self.tab1_name = '스폰서 변환' self.tab2_name = '싱크 조절(초)' self.tab3_name = '싱크 조절(%)' self.tab_page_1 = QWidget() self.tab_grid_1 = QGridLayout() self.tab1_search_label = QLabel('검색 텍스트') self.tab1_search = QLineEdit() self.tab1_sponsor = QWidget() self.tab1_sponsor_layout = QHBoxLayout() self.tab1_sponsor_layout.setContentsMargins(0, 0, 0, 0) self.tab1_sponsor_label = QLabel('스폰서 영상 길이') self.tab1_sponsor_value = QDoubleSpinBox() self.tab1_sponsor_value.setFixedWidth(60) self.tab1_sponsor_value.setMinimum(-1000000000) self.tab1_sponsor_value.setValue(10) self.tab1_offset = QWidget() self.tab1_offset_layout = QHBoxLayout() self.tab1_offset_layout.setContentsMargins(0, 0, 0, 0) self.tab1_offset_label = QLabel('라인 오프셋') self.tab1_offset_value = QSpinBox() self.tab1_offset_value.setMinimum(-1000000000) self.tab1_offset_value.setValue(2) self.tab1_offset_value.setFixedWidth(50) self.tab1_ignore = QWidget() self.tab1_ignore_layout = QHBoxLayout() self.tab1_ignore_layout.setContentsMargins(0, 0, 0, 0) self.tab1_ignore_label1 = QLabel('시작부터') self.tab1_ignore_value = QSpinBox() self.tab1_ignore_value.setFixedWidth(50) self.tab1_ignore_value.setValue(5) self.tab1_ignore_label2 = QLabel('줄 ') self.tab1_ignore_sec = QSpinBox() self.tab1_ignore_sec.setFixedWidth(60) self.tab1_ignore_sec.setMaximum(1000) self.tab1_ignore_sec.setValue(90) self.tab1_ignore_label3 = QLabel('초 무시하기') self.tab1_add_button = QPushButton('추가하기') self.tab_page_2 = QWidget() self.tab_grid_2 = QGridLayout() self.tab2_shift = QWidget() self.tab2_shift_layout = QHBoxLayout() self.tab2_shift_layout.setContentsMargins(0, 0, 0, 0) self.tab2_shift_label1 = QLabel('자막 싱크') self.tab2_shift_value = QDoubleSpinBox() self.tab2_shift_value.setFixedWidth(60) self.tab2_shift_label2 = QLabel('초 ') self.tab2_slow_radio = QRadioButton('느리게') self.tab2_slow_radio.setChecked(True) self.tab2_fast_radio = QRadioButton('빠르게') self.tab2_add_button = QPushButton('추가하기') self.tab_page_3 = QWidget() self.tab_grid_3 = QGridLayout() self.tab3_speed_label1 = QLabel('자막 싱크') self.tab3_speed_value = QSpinBox() self.tab3_speed_value.setFixedWidth(70) self.tab3_speed_value.setRange(1, 1000) self.tab3_speed_value.setValue(100) self.tab3_speed_label2 = QLabel('%') self.tab3_add_button = QPushButton('추가하기') self.que_label = QLabel('작업 목록') self.que_label.setFixedHeight(24) self.que_widget = QWidget() self.que_widget.setFixedHeight(114) self.que_layout = QGridLayout() self.que_layout.setContentsMargins(0, 0, 0, 0) self.que_list = QTreeWidget() self.que_list.setHeaderLabels(['작업', '옵션']) self.que_delete_button = QPushButton(QIcon(':/remove.png'), '') self.que_delete_button.setFixedSize(icon_button_size) self.que_delete_button.setIconSize(icon_size) self.que_delete_button.setToolTip('목록 삭제') self.que_up_button = QPushButton(QIcon(':/up.png'), '') self.que_up_button.setIconSize(icon_size) self.que_up_button.setFixedSize(icon_button_size) self.que_up_button.setToolTip('위로') self.que_down_button = QPushButton(QIcon(':/down.png'), '') self.que_down_button.setIconSize(icon_size) self.que_down_button.setFixedSize(icon_button_size) self.que_down_button.setToolTip('아래로') self.que_clear_button = QPushButton(QIcon(':/clear.png'), '') self.que_clear_button.setIconSize(icon_size) self.que_clear_button.setFixedSize(icon_button_size) self.que_clear_button.setToolTip('비우기') self.file_label = QLabel('파일 목록') self.file_label.setFixedHeight(24) self.file_widget = QWidget() self.file_layout = QGridLayout() self.file_layout.setContentsMargins(0, 0, 0, 0) self.file_list = QTreeWidget() self.file_list.setAcceptDrops(True) self.file_list.setHeaderLabels(['이름', '경로']) self.file_file_open = QPushButton(QIcon(':/file.png'), '') self.file_file_open.setFixedSize(icon_button_size) self.file_file_open.setIconSize(icon_size) self.file_file_open.setToolTip('파일 열기') self.file_dir_open = QPushButton(QIcon(':/folder.png'), '') self.file_dir_open.setFixedSize(icon_button_size) self.file_dir_open.setIconSize(icon_size) self.file_dir_open.setToolTip('폴더 열기') self.file_delete = QPushButton(QIcon(':/remove.png'), '') self.file_delete.setFixedSize(icon_button_size) self.file_delete.setIconSize(icon_size) self.file_delete.setToolTip('목록 삭제') self.file_clear = QPushButton(QIcon(':/clear.png'), '') self.file_clear.setFixedSize(icon_button_size) self.file_clear.setIconSize(icon_size) self.file_clear.setToolTip('비우기') self.file_encode = QPushButton(QIcon(':/encode.png'), '') self.file_encode.setFixedSize(icon_button_size) self.file_encode.setIconSize(icon_size) self.file_encode.setToolTip('인코딩 설정') self.save_widget = QGroupBox('저장 옵션') self.save_widget.setMinimumSize(400, 0) self.save_widget.setFixedHeight(82) self.save_layout = QGridLayout() self.save_orig_radio = QRadioButton('원본 위치에 저장') self.save_orig_radio.setChecked(True) self.save_strip = QCheckBox('싱크 꼬임 무시') self.save_strip.setToolTip('싱크 꼬임을 무시하고 모든 자막을 보존합니다.') self.save_dir_radio = QRadioButton('다른 위치에 저장') self.save_dir_line = QLineEdit() self.save_dir_find = QPushButton('...') self.save_dir_find.setFixedWidth(40) self.ok_button = QPushButton('적용') self.ok_button.setFixedSize(normal_button_size) self.cancel_button = QPushButton('취소') self.cancel_button.setFixedSize(normal_button_size) # Display GUI Components self.central_layout.addWidget(self.tab_group_widget, 0, 0, 1, 3) self.central_layout.addWidget(self.que_label, 1, 0, 1, 3) self.central_layout.addWidget(self.que_widget, 2, 0, 1, 3) self.central_layout.addWidget(self.file_label, 3, 0, 1, 3) self.central_layout.addWidget(self.file_widget, 4, 0, 1, 3) self.central_layout.addWidget(self.save_widget, 5, 0, 1, 3) self.central_layout.addWidget(self.ok_button, 6, 1, 1, 1) self.central_layout.addWidget(self.cancel_button, 6, 2, 1, 1) self.tab_group_widget.addTab(self.tab_page_1, QIcon(), self.tab1_name) self.tab_group_widget.addTab(self.tab_page_2, QIcon(), self.tab2_name) self.tab_group_widget.addTab(self.tab_page_3, QIcon(), self.tab3_name) self.tab_page_1.setLayout(self.tab_grid_1) self.tab_grid_1.addWidget(self.tab1_search_label, 0, 0, 1, 1) self.tab_grid_1.addWidget(self.tab1_search, 0, 1, 1, 2) self.tab_grid_1.addWidget(self.tab1_sponsor, 1, 1, 1, 1) self.tab_grid_1.addWidget(self.tab1_offset, 1, 2, 1, 1) self.tab_grid_1.addWidget(self.tab1_ignore, 2, 1, 1, 2) self.tab_grid_1.addWidget(self.tab1_add_button, 3, 0, 1, 3) self.tab1_sponsor.setLayout(self.tab1_sponsor_layout) self.tab1_sponsor_layout.addWidget(self.tab1_sponsor_label) self.tab1_sponsor_layout.addWidget(self.tab1_sponsor_value) self.tab1_sponsor_layout.addStretch(1) self.tab1_offset.setLayout(self.tab1_offset_layout) self.tab1_offset_layout.addWidget(self.tab1_offset_label) self.tab1_offset_layout.addWidget(self.tab1_offset_value) self.tab1_offset_layout.addStretch(1) self.tab1_ignore.setLayout(self.tab1_ignore_layout) self.tab1_ignore_layout.addWidget(self.tab1_ignore_label1) self.tab1_ignore_layout.addWidget(self.tab1_ignore_value) self.tab1_ignore_layout.addWidget(self.tab1_ignore_label2) self.tab1_ignore_layout.addWidget(self.tab1_ignore_sec) self.tab1_ignore_layout.addWidget(self.tab1_ignore_label3) self.tab1_ignore_layout.addStretch(1) self.tab_page_2.setLayout(self.tab_grid_2) self.tab_grid_2.setRowStretch(0, 1) self.tab_grid_2.addWidget(self.tab2_shift, 1, 0, 2, 1) self.tab_grid_2.addWidget(self.tab2_slow_radio, 1, 1, 1, 1) self.tab_grid_2.addWidget(self.tab2_fast_radio, 2, 1, 1, 1) self.tab_grid_2.setColumnStretch(2, 1) self.tab_grid_2.setRowStretch(3, 1) self.tab_grid_2.addWidget(self.tab2_add_button, 4, 0, 1, 3) self.tab2_shift.setLayout(self.tab2_shift_layout) self.tab2_shift_layout.addWidget(self.tab2_shift_label1) self.tab2_shift_layout.addWidget(self.tab2_shift_value) self.tab2_shift_layout.addWidget(self.tab2_shift_label2) self.tab_page_3.setLayout(self.tab_grid_3) self.tab_grid_3.setRowStretch(0, 1) self.tab_grid_3.addWidget(self.tab3_speed_label1, 1, 0, 1, 1) self.tab_grid_3.addWidget(self.tab3_speed_value, 1, 1, 1, 1) self.tab_grid_3.addWidget(self.tab3_speed_label2, 1, 2, 1, 1) self.tab_grid_3.setColumnStretch(3, 1) self.tab_grid_3.setRowStretch(2, 1) self.tab_grid_3.addWidget(self.tab3_add_button, 3, 0, 1, 4) self.que_widget.setLayout(self.que_layout) self.que_layout.addWidget(self.que_list, 0, 0, 4, 1) self.que_layout.addWidget(self.que_delete_button, 0, 1, 1, 1) self.que_layout.addWidget(self.que_up_button, 1, 1, 1, 1) self.que_layout.addWidget(self.que_down_button, 2, 1, 1, 1) self.que_layout.addWidget(self.que_clear_button, 3, 1, 1, 1) self.file_widget.setLayout(self.file_layout) self.file_layout.addWidget(self.file_list, 0, 0, 6, 1) self.file_layout.addWidget(self.file_file_open, 0, 1, 1, 1) self.file_layout.addWidget(self.file_dir_open, 1, 1, 1, 1) self.file_layout.addWidget(self.file_delete, 2, 1, 1, 1) self.file_layout.addWidget(self.file_clear, 3, 1, 1, 1) self.file_layout.addWidget(self.file_encode, 5, 1, 1, 1) self.save_widget.setLayout(self.save_layout) self.save_layout.addWidget(self.save_orig_radio, 0, 0, 1, 1) self.save_layout.setColumnStretch(1, 1) self.save_layout.addWidget(self.save_strip, 0, 2, 1, 2) self.save_layout.addWidget(self.save_dir_radio, 1, 0, 1, 1) self.save_layout.addWidget(self.save_dir_line, 1, 1, 1, 2) self.save_layout.addWidget(self.save_dir_find, 1, 3, 1, 1) self.setWindowTitle('Batch SAMI Sync v0.2') self.setCentralWidget(self.central_widget) self.adjustSize() def attach_event(self): # Default encoding hack self.encoding = '자동' # Define and Connect event handlers def tab1_add(): sponsor_text = self.tab1_search.text() sponsor_time = self.tab1_sponsor_value.value() line_offset = self.tab1_offset_value.value() line_ignore = self.tab1_ignore_value.value() time_ignore = self.tab1_ignore_sec.value() data = [1, sponsor_time, sponsor_text, line_offset, line_ignore, time_ignore] item = QTreeWidgetItem(self.que_list, [self.tab1_name, '스폰서 영상 시간 : ' + str(sponsor_time) + '초, 오프셋 : ' + str(line_offset) + '줄, 시작부터 ' + str(line_ignore) + '번째 줄, ' + str(time_ignore) + '초 무시 - 검색어 : ' + sponsor_text]) item.setData(2, 2, data) def tab2_add(): shift_time = self.tab2_shift_value.value() shift_direction = self.tab2_fast_radio.isChecked() direction_text = '빠르게' if shift_direction else '느리게' data = [2, shift_time, shift_direction] item = QTreeWidgetItem(self.que_list, [self.tab2_name, '자막 싱크 ' + str(shift_time) + '초 ' + direction_text]) item.setData(2, 2, data) def tab3_add(): speed_rate = self.tab3_speed_value.value() data = [3, speed_rate] item = QTreeWidgetItem(self.que_list, [self.tab3_name, '자막 속도 ' + str(speed_rate) + '%']) item.setData(2, 2, data) def file_open(): selected = QFileDialog.getOpenFileNames(self, "자막 파일 선택", "", "SAMI Files (*.smi);;All Files (*)") for file in selected[0]: name = ntpath.basename(file) Utils.insert_list(self.file_list, name, file) def dir_open(): selected = QFileDialog.getExistingDirectory(self, "자막 폴더 선택") for paths, subdirs, files in os.walk(selected): for file in files: if fnmatch(file, '*.smi'): name = ntpath.basename(file) Utils.insert_list(self.file_list, name, file) def open_encode_dialog(): self.dialog = QInputDialog(self) self.dialog.setWindowTitle('인코딩 설정') self.dialog.setLabelText('텍스트 인코딩 설정') self.dialog.setComboBoxItems(['자동', 'EUC-KR', 'UTF-8', 'UTF-16LE', 'UTF-16BE', '직접 입력']) self.dialog.show() self.dialog.textValueChanged.connect(type_encode) self.dialog.textValueSelected.connect(set_encode) def type_encode(text): if text == '직접 입력': self.dialog.setComboBoxItems([]) self.dialog.setComboBoxEditable(True) def set_encode(text): self.encoding = text def save_dir(): selected = QFileDialog.getExistingDirectory(self, "저장 위치 선택") self.save_dir_line.setText(selected) def apply(): self.ok_button.setEnabled(False) ques = Utils.read_list(self.que_list, False) files = Utils.read_list(self.file_list, False) strip = False if self.save_strip.isChecked() else True log = [] for file in files: try: text = Utils.launch_que(file[1], ques, self.encoding, strip) if len(text): if self.save_orig_radio.isChecked(): savepath = file[1] else: savepath = self.save_dir_line.text() + '/' + file[0] Utils.save_file(savepath, text) except Exception as e: log.append(file[0] + ' 처리 오류 : ' + str(e)) if log: ScrollMessageBox(QMessageBox.Warning, 'Batch SAMI Sync', "\n".join(log)) else: QMessageBox.information(self, 'Batch SAMI Sync', '변환 완료!') self.ok_button.setEnabled(True) self.tab1_add_button.clicked.connect(tab1_add) self.tab2_add_button.clicked.connect(tab2_add) self.tab3_add_button.clicked.connect(tab3_add) self.que_delete_button.clicked.connect(lambda: Utils.delete_list(self.que_list)) self.que_clear_button.clicked.connect(lambda: Utils.clear_list(self.que_list)) self.que_up_button.clicked.connect(lambda: Utils.up_list(self.que_list)) self.que_down_button.clicked.connect(lambda: Utils.down_list(self.que_list)) self.file_file_open.clicked.connect(file_open) self.file_dir_open.clicked.connect(dir_open) self.file_delete.clicked.connect(lambda: Utils.delete_list(self.file_list)) self.file_clear.clicked.connect(lambda: Utils.clear_list(self.file_list)) self.file_encode.clicked.connect(open_encode_dialog) self.save_dir_find.clicked.connect(save_dir) self.ok_button.clicked.connect(apply) self.cancel_button.clicked.connect(sys.exit) def dragEnterEvent(self, event): if event.mimeData().hasUrls: event.accept() else: event.ignore() def dragMoveEvent(self, event): if event.mimeData().hasUrls(): event.setDropAction(Qt.CopyAction) event.accept() else: event.ignore() def dropEvent(self, event): if event.mimeData().hasUrls(): event.setDropAction(Qt.CopyAction) event.accept() for url in event.mimeData().urls(): if url.isLocalFile(): file = str(url.toLocalFile()) if fnmatch(file, '*.smi'): name = ntpath.basename(file) Utils.insert_list(self.file_list, name, file) elif not fnmatch(file, '*.*'): for paths, subdirs, files in os.walk(file): for file in files: if fnmatch(file, '*.smi'): name = ntpath.basename(file) Utils.insert_list(self.file_list, name, file) else: event.ignore()
def __init__(self, app, parent=None): print("Window init") super().__init__(parent) # self.win_event_filter = WinEventFilter("window") # self.installNativeEventFilter(self.win_event_filter) self.app = app self.window_size = QtCore.QSize(400, 250) self.window_size_offset = QtCore.QSize(0, 150) self.window_position = QtCore.QPoint(0, 0) self.window_position_offset = QtCore.QPoint(0, 0) # self.setWindowFlags( # QtCore.Qt.Window | # QtCore.Qt.CustomizeWindowHint | # QtCore.Qt.WindowTitleHint | # QtCore.Qt.WindowCloseButtonHint | # QtCore.Qt.WindowStaysOnTopHint # ) self.setWindowFlags(self.windowFlags() | QtCore.Qt.FramelessWindowHint) self.setWindowFlags(self.windowFlags() | QtCore.Qt.WindowStaysOnTopHint) self.setWindowFlags( QtCore.Qt.FramelessWindowHint | QtCore.Qt.WindowStaysOnTopHint | QtCore.Qt.Tool) # hlayout = QHBoxLayout() # hlayout.setMargin(0) # hlayout.setContentsMargins(0, 0, 0, 0) # hlayout.setSpacing(0) # buttonslayout = QVBoxLayout() self.labels = [] self.menuButton = QPushButton(u"\U00002261") self.menuLabel = QLabel("Menu") myFontBold = self.menuLabel.font() myFontBold.setBold(True) # buttons myFont = self.menuButton.font() myFont2 = self.menuButton.font() if (myFont.pointSize() > 0): myFont.setPointSizeF(1.25 * myFont.pointSizeF()) myFont2.setPointSizeF(1.4 * myFont.pointSizeF()) else: myFont.setPixelSize(1.25 * myFont.pixelSize()) myFont2.setPixelSize(1.4 * myFont.pixelSize()) self.menuLabel.setFont(myFontBold) width = self.menuButton.fontMetrics().boundingRect("OO").width() + 7 height = width # okButton.height() self.menuButton.setFont(myFont2) self.menuButton.setMaximumWidth(width) self.menuButton.setMinimumWidth(width) self.menuButton.setFlat(True) self.menuButton.clicked.connect(self.menuPressed) mainButton = QPushButton(u"\U0000239A") mainLabel = QLabel("Main") width = mainButton.fontMetrics().boundingRect("OO").width() + 7 height = width # okButton.height() mainButton.setFont(myFont2) mainButton.setMaximumWidth(width) mainButton.setMinimumWidth(width) mainButton.clicked.connect(self.main) mainButton.setFlat(True) setupButton = QPushButton(u"\U0001F527") setupLabel = QLabel("Setup") setupButton.setFont(myFont) setupButton.setFlat(True) setupButton.setMaximumWidth(width) setupButton.setMinimumWidth(width) setupButton.clicked.connect(self.setup) identifyButton = QPushButton(u"\U00002755") identifyLabel = QLabel("Identify") identifyButton.setFont(myFont) identifyButton.setFlat(True) identifyButton.setMaximumWidth(width) identifyButton.setMinimumWidth(width) identifyButton.clicked.connect(self.identify) self.refreshButton = QPushButton(u"\U000021BB") self.refreshLabel = QLabel("Detect") self.refreshButton.setFont(myFont) self.refreshButton.setFlat(True) self.refreshButton.setMaximumWidth(width) self.refreshButton.setMinimumWidth(width) self.refreshButton.clicked.connect(self.refreshPressed) aboutButton = QPushButton(u"\U00002754") aboutLabel = QLabel("About") aboutButton.setFont(myFont) aboutButton.setFlat(True) aboutButton.setMaximumWidth(width) aboutButton.setMinimumWidth(width) aboutButton.clicked.connect(self.about) # closeButton = QPushButton(u"\U00002573") closeButton = QPushButton(u"\U000026CC") closeLabel = QLabel("Close") closeButton.setFont(myFont) closeButton.setFlat(True) closeButton.setMaximumWidth(width) closeButton.setMinimumWidth(width) closeButton.clicked.connect(self.close_) buttongrid = QGridLayout() buttongrid.addWidget(self.menuButton, 0, 0) buttongrid.addWidget(mainButton, 1, 0) buttongrid.addWidget(setupButton, 2, 0) buttongrid.addWidget(self.refreshButton, 3, 0) buttongrid.addWidget(identifyButton, 4, 0) buttongrid.addWidget(aboutButton, 6, 0) buttongrid.addWidget(closeButton, 7, 0) buttongrid.addWidget(self.menuLabel, 0, 1) buttongrid.addWidget(mainLabel, 1, 1) buttongrid.addWidget(setupLabel, 2, 1) buttongrid.addWidget(self.refreshLabel, 3, 1) buttongrid.addWidget(identifyLabel, 4, 1) buttongrid.addWidget(aboutLabel, 6, 1) buttongrid.addWidget(closeLabel, 7, 1) self.labels.append(self.menuLabel) self.labels.append(mainLabel) self.labels.append(setupLabel) self.labels.append(self.refreshLabel) self.labels.append(identifyLabel) self.labels.append(aboutLabel) self.labels.append(closeLabel) self.menuLabel .mousePressEvent = self.menuLabelPressed mainLabel .mousePressEvent = self.mainLabel setupLabel.mousePressEvent = self.setupLabel self.refreshLabel.mousePressEvent = self.refreshLabelPressed identifyLabel.mousePressEvent = self.identifyLabel aboutLabel.mousePressEvent = self.aboutLabel closeLabel.mousePressEvent = self.closeLabel buttongrid.setRowStretch(0, 0) buttongrid.setRowStretch(1, 0) buttongrid.setRowStretch(2, 0) buttongrid.setRowStretch(3, 0) buttongrid.setRowStretch(4, 0) buttongrid.setRowStretch(5, 1) buttongrid.setRowStretch(6, 0) buttongrid.setRowStretch(7, 0) self.labels_set_visible(False) self.layout = QHBoxLayout() # buttonslayout.addWidget(mainButton) # buttonslayout.addWidget(setupButton) # buttonslayout.addStretch(1) # buttonslayout.addWidget(aboutButton) # hlayout.addLayout(buttonslayout) # hlayout.addLayout(buttongrid) # grid.addLayout(hlayout, 1, 1) buttongrid.setSpacing(0) self.layout.addLayout(buttongrid) self.body_layout = QVBoxLayout() self.body_layout.setContentsMargins(0, 0, 0, 1) self.body_layout.setSpacing(0) self.title_layout = QHBoxLayout() self.title_layout.setContentsMargins(0, 0, 0, 0) self.title_layout.setSpacing(0) self.titleLabel = QLabel("Monitor Control") self.titleLabel.setWordWrap(True) self.titleLabel.setSizeIncrement(10, 10) myFont = self.titleLabel.font() myFont.setBold(True) self.titleLabel.setFont(myFont) width = self.titleLabel.fontMetrics().boundingRect("OO").width() + 7 height = width # okButton.height() self.titleLabel.mousePressEvent = self.mainLabel self.backButton = QPushButton(u"\U00002190", self) myFont = self.backButton.font() myFont.setBold(True) self.backButton.setFont(myFont) self.backButton.setMaximumWidth(width) self.backButton.setMinimumWidth(width) self.backButton.setFlat(True) self.backButton.clicked.connect(self.main) self.titleLabel.setMinimumHeight(self.backButton.height()) self.title_layout.addWidget(self.backButton, 0, QtCore.Qt.AlignVCenter) self.title_layout.addSpacing(20) self.title_layout.addWidget(self.titleLabel, 1, QtCore.Qt.AlignVCenter) # self.backButton.setAlignment(Qt.AlignTop) self.title_layout.setAlignment(QtCore.Qt.AlignTop) self.body_layout.addLayout(self.title_layout) self.main_frame = QtWidgets.QFrame(self) self.main_layout = QVBoxLayout() self.feature_brightness = FeatureWidget( self.main_frame, "Brightness", self.app.brightness) self.feature_contrast = FeatureWidget( self.main_frame, "Contrast", self.app.contrast) self.main_layout.addWidget(self.feature_brightness) self.main_layout.addWidget(self.feature_contrast) self.main_layout.addStretch(1) self.main_frame.setLayout(self.main_layout) self.main_frame.hide() self.body_layout.addWidget(self.main_frame, 1) self.setup_frame = QtWidgets.QFrame(self) leftButton = QPushButton("<", self.setup_frame) width = leftButton.fontMetrics().boundingRect("<").width() + 7 leftButton.setFlat(True) leftButton.setMaximumWidth(width) leftButton.setMinimumWidth(width) leftButton.setSizePolicy(QtWidgets.QSizePolicy( QSizePolicy.Fixed, QSizePolicy.Expanding)) self.setup_layout = QHBoxLayout() self.setup_layout.addWidget(leftButton) self.feature_setup_widget = FeatureSetupWidget( self.app, self.setup_frame) # hlayout.addWidget(self.feature_setup_widget, 1) self.feature_setup_widget.setSizePolicy( QSizePolicy.Expanding, QSizePolicy.Expanding) rightButton = QPushButton(">", self.setup_frame) rightButton.setFlat(True) rightButton.setMaximumWidth(width) rightButton.setMinimumWidth(width) rightButton.setSizePolicy(QtWidgets.QSizePolicy( QSizePolicy.Fixed, QSizePolicy.Expanding)) self.setup_layout.addWidget(self.feature_setup_widget, 1) self.setup_layout.addWidget(rightButton) self.setup_layout.setContentsMargins(0, 0, 0, 0) self.setup_layout.setSpacing(0) leftButton.clicked.connect(self.feature_setup_widget.previous) rightButton.clicked.connect(self.feature_setup_widget.next) self.setup_frame.setLayout(self.setup_layout) # self.layout.setContentsMargins(0, 0, 0, 0) self.layout.setSpacing(10) self.body_layout.addWidget(self.setup_frame, 1) self.layout.addLayout(self.body_layout, 1) self.about_frame = QtWidgets.QFrame(self) self.about_layout = QVBoxLayout() self.aboutLabel1 = QLabel("About", self.about_frame) self.aboutLabel1.setWordWrap(True) myFont = self.aboutLabel1.font() myFont.setBold(True) self.aboutLabel1.setFont(myFont) about = "©️ ™️ Juno\n\nMonitor Control synchronizes your monitor hardware properties like brightness and contrast.\nThese properties can be changed by the software sliders, or monitor buttons. These changes are monitored and read, and subsequently set to the other monitors using a calibration. This will ensure an input change has the same result on all monitors.\n" self.aboutLabel2 = QLabel("{}".format(about), self.about_frame) self.aboutLabel2.setAlignment( QtCore.Qt.AlignLeft | QtCore.Qt.AlignTop) self.aboutLabel2.setWordWrap(True) self.about_layout.addWidget(self.aboutLabel1) self.about_layout.addWidget(self.aboutLabel2, 1) self.about_frame.setLayout(self.about_layout) self.about_frame.hide() self.body_layout.addWidget(self.about_frame, 1) # self.layout.setSizeConstraint(QtGui.QLayout.setFixedSize) self.setLayout(self.layout) self.setWindowIcon(QtGui.QIcon('artifacts/icon.png')) # set the title self.setWindowTitle("Monitors Control") self.main() self.setFixedSize(400, 250)
class MainWindow(QMainWindow): def __init__(self, shared_dict): super(MainWindow, self).__init__() self.shared_dict = shared_dict self.setStyleSheet(styles.main_window) self.centralWidget = QWidget(self) self.gridLayout_central = QGridLayout(self.centralWidget) self.navFrame = NavFrame(self.centralWidget) self.sitesFrame = SitesFrame(self.centralWidget) self.stackedWidget = StackedWidget(self.centralWidget, self.shared_dict) self.init_window() self.set_start_state() def set_start_state(self): # set nav btn connection self.navFrame.radioButton_add.toggled.connect(lambda: self.go_to_page(0)) self.navFrame.radioButton_monitored.toggled.connect(lambda: self.go_to_page(1)) self.navFrame.radioButton_options.toggled.connect(lambda: self.go_to_page(2)) self.navFrame.radioButton_about.toggled.connect(lambda: self.go_to_page(3)) self.navFrame.radioButton_add.setChecked(True) self.stackedWidget.pageAllegroAdd.pushButton_bn.clicked.connect(lambda: self.new_link_handler(False)) def new_link_handler(self, is_monitor): element = self.stackedWidget.pageAllegroAdd.new_link_handler(is_monitor) if element is not None: self.stackedWidget.pageAllegroMonitored.add_to_list(element["name"], element["link"], element["is_done"], element["price"], element["xpath"], element["time"], element["is_monitoring"]) def init_window(self): # set window self.setGeometry(100, 100, 900, 620) import os self.setWindowIcon(QIcon(os.path.join(path, './img/icon.png'))) self.setWindowTitle("WebCheck") # set centralWidget sizePolicy = QSizePolicy(QSizePolicy.Minimum, QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(2) sizePolicy.setVerticalStretch(2) sizePolicy.setHeightForWidth(self.centralWidget.sizePolicy().hasHeightForWidth()) self.centralWidget.setSizePolicy(sizePolicy) self.centralWidget.setMinimumSize(QSize(900, 540)) self.setCentralWidget(self.centralWidget) # set grid layout central self.gridLayout_central.setSpacing(0) self.gridLayout_central.setContentsMargins(0, 0, 0, 0) self.gridLayout_central.setRowStretch(0, 1) self.gridLayout_central.setRowStretch(1, 10) self.gridLayout_central.setColumnStretch(0, 1) self.gridLayout_central.setColumnStretch(1, 3) self.gridLayout_central.addWidget(self.navFrame, 0, 0, 9, 1) self.gridLayout_central.addWidget(self.sitesFrame, 0, 1, 1, 1) self.gridLayout_central.addWidget(self.stackedWidget, 1, 1, 1, 1) def go_to_page(self, index): if index == 0: self.stackedWidget.setCurrentIndex(0) elif index == 1: self.stackedWidget.setCurrentIndex(1) elif index == 2: self.stackedWidget.setCurrentIndex(2) elif index == 3: self.stackedWidget.setCurrentIndex(3) elif index == 4: self.stackedWidget.setCurrentIndex(4)
def __init__(self): QWidget.__init__(self) self.setWindowTitle("Backend Discord-GUI") self.changeStyle('fusion') palette = QPalette() palette.setColor(QPalette.Window, QColor(53, 53, 53)) palette.setColor(QPalette.WindowText, Qt.white) palette.setColor(QPalette.Text, Qt.white) palette.setColor(QPalette.Button, QColor(60, 60, 60)) palette.setColor(QPalette.ButtonText, Qt.white) palette.setColor(QPalette.Base, QColor(40, 40, 40)) palette.setColor(QPalette.ToolTipBase, QColor(60, 60, 60)) palette.setColor(QPalette.ToolTipText, Qt.white) palette.setColor(QPalette.PlaceholderText, Qt.white) palette.setColor(QPalette.BrightText, Qt.white) palette.setColor(QPalette.Highlight, QColor(106, 13, 173)) palette.setColor(QPalette.HighlightedText, Qt.white) topButtonLayout = QGroupBox("Configurations") topStatsLayout = QGroupBox("Statistics") layoutLeft = QHBoxLayout() botConfigButton = QPushButton("Bot Config") botConfigButton.clicked.connect(lambda: CommentPopup()) serverSettingsButton = QPushButton("Server Settings") settingsButton = QPushButton("Settings") layoutLeft.addWidget(botConfigButton) layoutLeft.addWidget(serverSettingsButton) layoutLeft.addWidget(settingsButton) layoutRight = QVBoxLayout() botReadyLabel = QLabel("Bot_Ready: False") botStatusLabel = QLabel("Bot_Status: Off") # botDatabaseLabel = QLabel("Bot_Database: None") # botStandbyLabel = QLabel("Bot_Standby: False") layoutRight.addWidget(botReadyLabel) layoutRight.addWidget(botStatusLabel) # layoutRight.addWidget(botDatabaseLabel) # layoutRight.addWidget(botStandbyLabel) topButtonLayout.setLayout(layoutLeft) topStatsLayout.setLayout(layoutRight) self.createLeftSide() self.createRightSide() self.createProgressBar() topLayout = QGridLayout() topLayout.addWidget(topButtonLayout, 0, 0) topLayout.addWidget(topStatsLayout, 0, 1) topLayout.setColumnStretch(0, 1) mainLayout = QGridLayout() mainLayout.addLayout(topLayout, 0, 0, 1, 2) mainLayout.addWidget(self.leftSideGB, 1, 0) mainLayout.addWidget(self.topRightGroupBox, 1, 1) mainLayout.addWidget(self.progressBar, 3, 0, 1, 2) mainLayout.setRowStretch(1, 2) mainLayout.setColumnStretch(0, 1) mainLayout.setColumnStretch(1, 2) self.setLayout(mainLayout) QApplication.setPalette(palette)
class PageAllegroAdd(QWidget): def __init__(self, parent=None, shared_dict=None): QWidget.__init__(self, parent) parent.addWidget(self) self.shared_dict = shared_dict self.gridLayout = QGridLayout(self) self.gridLayout.setContentsMargins(0, 0, 0, 0) self.gridLayout.setRowStretch(0, 1) self.gridLayout.setRowStretch(1, 1) self.gridLayout.setRowStretch(2, 1) self.gridLayout.setRowStretch(3, 1) self.gridLayout.setRowStretch(4, 1) self.gridLayout.setRowStretch(5, 1) self.gridLayout.setRowStretch(6, 1) self.gridLayout.setRowStretch(7, 1) self.gridLayout.setRowStretch(8, 1) self.gridLayout.setRowStretch(9, 1) self.gridLayout.setRowStretch(10, 1) self.gridLayout.setRowStretch(11, 1) self.gridLayout.setRowStretch(12, 1) self.gridLayout.setRowStretch(13, 1) self.gridLayout.setRowStretch(14, 2) self.gridLayout.setRowStretch(15, 1) self.gridLayout.setColumnStretch(0, 5) self.gridLayout.setColumnStretch(1, 5) self.gridLayout.setColumnStretch(2, 1) self.gridLayout.setColumnStretch(3, 2) self.gridLayout.setColumnStretch(4, 1) self.gridLayout.setColumnStretch(5, 2) self.gridLayout.setColumnStretch(6, 1) self.gridLayout.setColumnStretch(7, 2) self.gridLayout.setColumnStretch(8, 3) self.gridLayout.setColumnStretch(9, 5) # create lineEdits self.lineEdit_login = QLineEdit(self) self.lineEdit_login.setMinimumSize(QSize(0, 60)) self.lineEdit_login.setSizeIncrement(QSize(40, 40)) self.lineEdit_login.setStyleSheet(styles.lineEdit) self.lineEdit_login.setMaxLength(32767) self.gridLayout.addWidget(self.lineEdit_login, 4, 1, 1, 3) self.lineEdit_login.setPlaceholderText("login or email of your account") self.lineEdit_password = QLineEdit(self) self.lineEdit_password.setMinimumSize(QSize(20, 60)) self.lineEdit_password.setStyleSheet(styles.lineEdit) self.lineEdit_password.setEchoMode(QLineEdit.Password) self.lineEdit_password.setReadOnly(False) self.gridLayout.addWidget(self.lineEdit_password, 7, 1, 1, 3) self.lineEdit_password.setPlaceholderText("password of your account") self.lineEdit_email = QLineEdit(self) self.lineEdit_email.setMinimumSize(QSize(0, 60)) self.lineEdit_email.setStyleSheet(styles.lineEdit) self.lineEdit_email.setFrame(True) self.lineEdit_email.setEchoMode(QLineEdit.Normal) self.gridLayout.addWidget(self.lineEdit_email, 7, 5, 1, 4) self.lineEdit_email.setPlaceholderText("email to which the notification will be sent") self.lineEdit_link = QLineEdit(self) self.lineEdit_link.setMinimumSize(QSize(0, 60)) self.lineEdit_link.setStyleSheet(styles.lineEdit) self.gridLayout.addWidget(self.lineEdit_link, 10, 1, 1, 8) self.lineEdit_link.setPlaceholderText("link to the page that you want to monitor") self.lineEdit_price = QLineEdit(self) self.lineEdit_price.setMinimumSize(QSize(0, 60)) self.lineEdit_price.setStyleSheet(styles.lineEdit) self.gridLayout.addWidget(self.lineEdit_price, 13, 1, 1, 1) self.lineEdit_price.setPlaceholderText("Price below which to notificate") self.lineEdit_xpath = QLineEdit(self) self.lineEdit_xpath.setMinimumSize(QSize(0, 60)) self.lineEdit_xpath.setStyleSheet(styles.lineEdit) self.gridLayout.addWidget(self.lineEdit_xpath, 13, 3, 1, 3) self.lineEdit_xpath.setPlaceholderText("XPATH of element with the price") self.lineEdit_time = QLineEdit(self) self.lineEdit_time.setMinimumSize(QSize(0, 60)) self.lineEdit_time.setStyleSheet(styles.lineEdit) self.gridLayout.addWidget(self.lineEdit_time, 13, 7, 1, 2) self.lineEdit_time.setPlaceholderText("interval between refreshes") # Create Labels self.label_title = QLabel("Add new monitoring object", self) self.label_title.setStyleSheet(styles.label_title) self.label_title.setAlignment(Qt.AlignCenter) self.gridLayout.addWidget(self.label_title, 0, 1, 1, 8) self.label_info = QLabel("", self) self.label_info.setStyleSheet(styles.label_info_wrong) self.label_info.setAlignment(Qt.AlignCenter) self.gridLayout.addWidget(self.label_info, 1, 1, 1, 8) self.label_login = QLabel("Allegro login", self) self.label_login.setStyleSheet(styles.label_lineEdit) self.gridLayout.addWidget(self.label_login, 3, 1, 1, 3) self.label_password = QLabel("Allegro password", self) self.label_password.setStyleSheet(styles.label_lineEdit) self.gridLayout.addWidget(self.label_password, 6, 1, 1, 3) self.label_email = QLabel("Email to notificate", self) self.label_email.setStyleSheet(styles.label_lineEdit) self.gridLayout.addWidget(self.label_email, 6, 5, 1, 4) self.label_link = QLabel("Product link", self) self.label_link.setStyleSheet(styles.label_lineEdit) self.gridLayout.addWidget(self.label_link, 9, 1, 1, 8) self.label_price = QLabel("Price", self) self.label_price.setStyleSheet(styles.label_lineEdit) self.gridLayout.addWidget(self.label_price, 12, 1, 1, 1) self.label_xpath = QLabel("Monitored element", self) self.label_xpath.setStyleSheet(styles.label_lineEdit) self.gridLayout.addWidget(self.label_xpath, 12, 3, 1, 3) self.label_time = QLabel("Refresh time[s]", self) self.label_time.setStyleSheet(styles.label_lineEdit) self.gridLayout.addWidget(self.label_time, 12, 7, 1, 2) self.pushButton_search = QPushButton(self) self.pushButton_search.clicked.connect(lambda: webbrowser.open('https://allegro.pl/')) icon = QIcon() icon.addFile(os.path.join(path, "img/search.png"), QSize(), QIcon.Selected, QIcon.Off) self.pushButton_search.setIcon(icon) self.pushButton_search.setIconSize(QSize(100, 100)) self.pushButton_search.setStyleSheet("""QPushButton{border:none;}""") self.pushButton_search.setCursor(QCursor(Qt.PointingHandCursor)) self.gridLayout.addWidget(self.pushButton_search, 3, 7, 3, 1) # Create spacers self.spacer_search_l = QSpacerItem(40, 20, QSizePolicy.Expanding, QSizePolicy.Minimum) self.gridLayout.addItem(self.spacer_search_l, 5, 5, 1, 2) self.spacer_search_r = QSpacerItem(40, 20, QSizePolicy.Expanding, QSizePolicy.Minimum) self.gridLayout.addItem(self.spacer_search_r, 5, 8, 1, 1) self.spacer_search_t = QSpacerItem(20, 40, QSizePolicy.Minimum, QSizePolicy.Expanding) self.gridLayout.addItem(self.spacer_search_t, 2, 1, 1, 8) self.spacer_search_b = QSpacerItem(20, 40, QSizePolicy.Minimum, QSizePolicy.Expanding) self.gridLayout.addItem(self.spacer_search_b, 5, 1, 1, 8) self.spacer_email_l = QSpacerItem(40, 20, QSizePolicy.Expanding, QSizePolicy.Minimum) self.gridLayout.addItem(self.spacer_email_l, 7, 4, 1, 1) self.spacer_link_l = QSpacerItem(40, 20, QSizePolicy.MinimumExpanding, QSizePolicy.Minimum) self.gridLayout.addItem(self.spacer_link_l, 13, 0, 1, 1) self.spacer_link_r = QSpacerItem(40, 20, QSizePolicy.MinimumExpanding, QSizePolicy.Minimum) self.gridLayout.addItem(self.spacer_link_r, 13, 9, 1, 1) self.spacer_link_t = QSpacerItem(20, 40, QSizePolicy.Minimum, QSizePolicy.Expanding) self.gridLayout.addItem(self.spacer_link_t, 8, 1, 1, 8) self.spacer_link_b = QSpacerItem(20, 40, QSizePolicy.Minimum, QSizePolicy.Expanding) self.gridLayout.addItem(self.spacer_link_b, 11, 1, 1, 8) self.spacer_price_b = QSpacerItem(20, 40, QSizePolicy.Minimum, QSizePolicy.Expanding) self.gridLayout.addItem(self.spacer_price_b, 14, 1, 1, 7) # create frame bottom self.frame_bottom = QFrame(self) self.frame_bottom.setStyleSheet("""QFrame{background-color: #fff; padding: 10px;}""") self.frame_bottom.setFrameShape(QFrame.StyledPanel) self.frame_bottom.setFrameShadow(QFrame.Raised) self.gridLayout.addWidget(self.frame_bottom, 15, 0, 1, 10) self.horizontalLayout_frame_bottom = QHBoxLayout(self.frame_bottom) self.spacer_frame_bottom_l = QSpacerItem(40, 20, QSizePolicy.Expanding, QSizePolicy.Minimum) self.horizontalLayout_frame_bottom.addItem(self.spacer_frame_bottom_l) self.pushButton_bn = QPushButton("Buy when price drops", self.frame_bottom) self.pushButton_bn.setMinimumSize(QSize(0, 40)) self.pushButton_bn.setStyleSheet(styles.btn_light) self.horizontalLayout_frame_bottom.addWidget(self.pushButton_bn) self.pushButton_bn.setShortcut("Return") self.spacer_frame_bottom_c = QSpacerItem(40, 20, QSizePolicy.Expanding, QSizePolicy.Minimum) self.horizontalLayout_frame_bottom.addItem(self.spacer_frame_bottom_c) self.pushButton_monitor = QPushButton("Monitor", self.frame_bottom) self.pushButton_monitor.clicked.connect(lambda: self.new_link_handler(True)) self.pushButton_monitor.setMinimumSize(QSize(0, 40)) self.pushButton_monitor.setStyleSheet(styles.btn_dark) self.horizontalLayout_frame_bottom.addWidget(self.pushButton_monitor) self.spacer_frame_bottom_r = QSpacerItem(40, 20, QSizePolicy.Expanding, QSizePolicy.Minimum) self.horizontalLayout_frame_bottom.addItem(self.spacer_frame_bottom_r) self.horizontalLayout_frame_bottom.setStretch(0, 1) self.horizontalLayout_frame_bottom.setStretch(1, 1) self.horizontalLayout_frame_bottom.setStretch(2, 2) self.horizontalLayout_frame_bottom.setStretch(3, 1) self.horizontalLayout_frame_bottom.setStretch(4, 1) self.timer = QTimer(self) auto_login, auto_pwd, auto_email, auto_time = data.get_autofill() self.lineEdit_login.setText(auto_login) self.lineEdit_password.setText(auto_pwd) self.lineEdit_email.setText(auto_email) self.lineEdit_time.setText(str(auto_time)) def new_link_handler(self, is_monitoring): # check if fields were filled properly no_warnings = True is_email = False link = "" login = "" email = "" password = "" xpath = "" price = 0 time = 60 if self.lineEdit_email.text() == "": self.lineEdit_email.setStyleSheet(styles.lineEdit_warning) no_warnings = False else: self.lineEdit_email.setStyleSheet(styles.lineEdit) email = self.lineEdit_email.text() for symbol in email: if symbol == '@': is_email = True if not is_email: self.lineEdit_email.setStyleSheet(styles.lineEdit_warning) no_warnings = False if self.lineEdit_login.text() == "": self.lineEdit_login.setStyleSheet(styles.lineEdit_warning) no_warnings = False else: self.lineEdit_login.setStyleSheet(styles.lineEdit) login = self.lineEdit_login.text() if self.lineEdit_link.text() == "": self.lineEdit_link.setStyleSheet(styles.lineEdit_warning) no_warnings = False else: self.lineEdit_link.setStyleSheet(styles.lineEdit) link = self.lineEdit_link.text() if self.lineEdit_password.text() == "": self.lineEdit_password.setStyleSheet(styles.lineEdit_warning) no_warnings = False else: self.lineEdit_password.setStyleSheet(styles.lineEdit) password = self.lineEdit_password.text() if self.lineEdit_price.text() == "": self.lineEdit_price.setStyleSheet(styles.lineEdit_warning) no_warnings = False else: self.lineEdit_price.setStyleSheet(styles.lineEdit) price = float(self.lineEdit_price.text()) if self.lineEdit_xpath.text() == "": self.lineEdit_xpath.setStyleSheet(styles.lineEdit_warning) no_warnings = False else: self.lineEdit_xpath.setStyleSheet(styles.lineEdit) xpath = self.lineEdit_xpath.text() if self.lineEdit_time.text() == "": self.lineEdit_time.setStyleSheet(styles.lineEdit_warning) no_warnings = False else: self.lineEdit_time.setStyleSheet(styles.lineEdit) time = int(self.lineEdit_time.text()) if no_warnings: self.lineEdit_login.clear() self.lineEdit_password.clear() self.lineEdit_email.clear() self.lineEdit_link.clear() self.lineEdit_price.clear() self.lineEdit_xpath.clear() self.lineEdit_time.clear() try: data.add_monitored_elements(login, email, password, link, price, xpath, time, is_monitoring) self.shared_dict['isTerminatedP2'] = True except InvalidArgumentException: self.set_info_text("Warning. Wrong link submitted", True) except KeyError: self.set_info_text("Error. This page has already monitored", True) else: self.set_info_text("Info. Object was successfully added", False) self.lineEdit_login.setText(self.auto_login) self.lineEdit_password.setText(self.auto_pwd) self.lineEdit_email.setText(self.auto_email) self.lineEdit_time.setText(self.auto_time) self.lineEdit_link.clear() self.lineEdit_price.clear() self.lineEdit_xpath.clear() else: self.set_info_text("Warning. Fill all field properly", True) return data.get_element(link) # def on_monitor(self): # new_price = monitoring.check_if_price_lower(self.label_link, self.label_xpath, self.label_price, self.label_time) # email_send.send_email(self.label_email, self.label_link, new_price) def set_info_text(self, text, is_warning): self.label_info.setText(text) if is_warning: self.label_info.setStyleSheet(styles.label_info_wrong) else: self.label_info.setStyleSheet(styles.label_info_right) self.timer.setInterval(5000) self.timer.timeout.connect(lambda: self.label_info.setText("")) self.timer.start()
class PlotWindow(QtWidgets.QMainWindow): def __init__(self, nrows=1, ncols=1, **kwargs): matplotlib.use('Qt5Agg') qapp = QtWidgets.QApplication.instance() if qapp is None: qapp = QtWidgets.QApplication(sys.argv) self.qapp = qapp super().__init__() self._main = QtWidgets.QWidget() self.setStyle(QStyleFactory.create('Fusion')) self.setCentralWidget(self._main) self.layout = QGridLayout(self._main) marker_kw = {} for k in marker_default_params.keys(): if k in kwargs.keys(): marker_kw[k] = kwargs.pop(k) title = kwargs.pop('title', None) icon = kwargs.pop('icon', None) if icon != None: self.setWindowIcon(QtGui.QIcon(str(icon))) marker_kw['interactive'] = kwargs.pop('interactive', True) marker_kw['top_axes'] = kwargs.pop('top_axes', None) marker_kw['link_all'] = kwargs.pop('link_all', False) self.single_trace = kwargs.pop('single_trace', False) subplot_kw = kwargs.pop('subplot_kw', {}) sharex = kwargs.pop('sharex', False) sharey = kwargs.pop('sharey', False) gridspec_kw = kwargs.pop('gridspec_kw', None) self.fig = plt.figure(**kwargs) self.axes_grid = self.fig.subplots(nrows, ncols, squeeze=False, sharex=False, sharey=False, subplot_kw=subplot_kw, gridspec_kw=gridspec_kw) self.axes = self.axes_grid.flatten() self.nrows = nrows self.ncols = ncols self.canvas = self.fig.canvas self.canvas.mpl_disconnect(self.canvas.manager.key_press_handler_id) self.canvas.manager.show = self._show self.layout.addWidget(self.canvas, 0, 0, (self.nrows * self.ncols) + 1, 1) self.toolbar = NavigationToolbar(self.canvas, self, coordinates=False) self.build_toolbar() self.addToolBar(self.toolbar) self.fig.canvas.toolbar = self.toolbar self.canvas.setFocusPolicy(QtCore.Qt.ClickFocus) self.canvas.setFocus() p = self.palette() p.setColor(self.backgroundRole(), Qt.white) self.setPalette(p) title = 'Figure {}'.format( self.fig.canvas.manager.num) if title == None else title self.setWindowTitle(title) self._drop_event_handler = None self.fig.marker_enable(**marker_kw) self.fig.qapp = self.qapp self.fig.app = self self.draw_updates = False self.axes_cb_group = [] self.current_data_format = None self.data_format_options = None for i, ax in enumerate(self.axes): ax_cb = AxesCheckBoxGroup( self, ax, "Axes {},{}".format(i // self.nrows, i % self.nrows)) self.axes_cb_group.append(ax_cb) def keyPressEvent(self, event): if event.key() in (QtCore.Qt.Key_F5, ): self.fig.canvas.draw() super().keyPressEvent(event) def set_draw_updates(self, state): prev = self.draw_updates self.draw_updates = state return prev def add_toolbar_actions(self, *widgets, end=True): for icon_path, name, tooltip, action in widgets: icon = QtGui.QPixmap(str(icon_path)) icon.setDevicePixelRatio(self.canvas._dpi_ratio) a = self.toolbar.addAction(QtGui.QIcon(icon), name, action) a.setToolTip(tooltip) if end: locLabel = QLabel("", self.toolbar) locLabel.setAlignment(QtCore.Qt.AlignRight | QtCore.Qt.AlignTop) locLabel.setSizePolicy( QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Ignored)) self.toolbar.addWidget(locLabel) def build_toolbar(self): self.toolbar.removeAction(self.toolbar._actions['configure_subplots']) self.toolbar.removeAction(self.toolbar._actions['forward']) self.toolbar.removeAction(self.toolbar._actions['back']) widgets = [ (str(dir_ / 'icons/layout_large.png'), 'Layout', 'Apply Tight Layout', self.set_tight_layout), (str(dir_ / 'icons/copy_large.png'), 'Copy', 'Copy To Clipboard', self.copy_figure), (str(dir_ / 'icons/erase_large.png'), 'Delete', 'Remove All Markers', self.remove_all), (str(dir_ / 'icons/autoscale_y.png'), 'Autoscale', 'Autoscale Y-Axis', self.autoscale_y), (str(dir_ / 'icons/autoscale_x.png'), 'Autoscale', 'Autoscale X-Axis', self.autoscale_x), (str(dir_ / 'icons/set_format_large.png'), 'Set Data Format', 'Set Data Format', self.set_data_format), ] self.add_toolbar_actions(*widgets, end=False) self.toolbar.addSeparator() def add_drop_event_handler(self, handler): self._drop_event_handler = handler if self._drop_event_handler != None: self.setAcceptDrops(True) def dragEnterEvent(self, e): if e.mimeData().hasText(): text = e.mimeData().text() m = re.search(r's\d+p$', text) if m != None: e.accept() else: e.ignore() else: e.ignore() def dropEvent(self, e): text = e.mimeData().text() self._drop_event_handler(text) self.change_data_format(self.current_data_format) self.update_axes_groups() self.autoscale_x() self.remove_all() self.fig.canvas.draw() def set_data_format(self): dialog = DataFormatDialog(self, self.change_data_format, self.data_format_options) dialog.show() def change_data_format(self, options): self.current_data_format = options for i, ax in enumerate(self.axes): self._data_format_handler(ax, options[i]) self.autoscale_y() def add_data_format_handler(self, func, format_options, initial=None): self._data_format_handler = func self.data_format_options = format_options self.current_data_format = [initial] * len(self.axes) def autoscale_x(self): for ax_cb in self.axes_cb_group: ax_cb.scale_visible(yscale=False) self.fig.canvas.draw() def autoscale_y(self): for ax_cb in self.axes_cb_group: ax_cb.scale_visible(xscale=False) self.fig.canvas.draw() def remove_all(self): for ax in self.fig._top_axes: ax.marker_delete_all() ax.draw_lines_markers() for l_ax in ax.marker_linked_axes: l_ax.marker_delete_all() l_ax.draw_lines_markers() def set_tight_layout(self): self.fig.tight_layout() self.canvas.draw() def copy_figure(self): buf = io.BytesIO() self.fig.savefig(buf) image = Image.open(buf) output = io.BytesIO() image.convert("RGB").save(output, "BMP") data = output.getvalue()[14:] output.close() win32clipboard.OpenClipboard() win32clipboard.EmptyClipboard() win32clipboard.SetClipboardData(win32clipboard.CF_DIB, data) win32clipboard.CloseClipboard() buf.close() def update_axes_groups(self): for i, ax_cb in enumerate(self.axes_cb_group): ax_cb.update_checkboxes() def create_axes_groups(self): for i, ax_cb in enumerate(self.axes_cb_group): ax_cb.add_to_layout(self.layout, i, 1) self.layout.addWidget(QGroupBox(), i + 1, 1) self.layout.setColumnStretch(0, 1) self.layout.setRowStretch(i + 1, 1) def _show(self): self.create_axes_groups() self.set_draw_updates(True) self.show() plt.close(self.fig)
def init_ui(self): # Menu grid layout and its settings grid = QGridLayout(self) grid.setColumnMinimumWidth(4, 260) grid.setColumnStretch(4, 0) for i in [1, 2, 3, 5]: grid.setColumnMinimumWidth(i, 75) grid.setColumnStretch(i, 0) for i in [0, 6]: grid.setColumnStretch(i, 1) grid.setRowMinimumHeight(1, 360) grid.setRowMinimumHeight(2, 25) for i in [0, 3]: grid.setRowStretch(i, 1) # Widgets self.tabw = QTabWidget(self) grid.addWidget(self.tabw, 1, 1, 1, 5) self.tabs = {} self.tabs['pile'] = QWidget(self) self.pilegrid = QGridLayout(self.tabs['pile']) self.pilegrid.setRowStretch(6, 1) self.tabw.addTab(self.tabs['pile'], 'Sandpile') self.tabs['visl'] = QWidget(self) self.vslgrid = QGridLayout(self.tabs['visl']) self.tabw.addTab(self.tabs['visl'], 'Visual') self.pilegrid.addWidget(QLabel('Seed:', self.tabs['pile']), 0, 0, 1, 1) self.pilegrid.addWidget(QLabel('Type:', self.tabs['pile']), 2, 0, 1, 1) self.seedfield = QLineEdit(self.tabs['pile']) self.pilegrid.addWidget(self.seedfield, 1, 0, 1, 4) self.buttons = {} self.buttons['cont'] = QPushButton('Continue', self) def func1(): self.root.toggle_menu() self.root.toggle_pause() self.buttons['cont'].clicked.connect(func1) grid.addWidget(self.buttons['cont'], 2, 1, 1, 1) self.buttons['rest'] = QPushButton('Restart', self) def func2(): self.root.restart_pile() func1() self.buttons['rest'].clicked.connect(func2) grid.addWidget(self.buttons['rest'], 2, 2, 1, 1) self.buttons['roll'] = QPushButton('Reset', self) def func3(): txt = self.seedfield.text() try: seed = eval(txt) except: seed = [[8]] self.root.reroll_pile(piletype=self.piletype, seed=seed) func1() self.buttons['roll'].clicked.connect(func3) grid.addWidget(self.buttons['roll'], 2, 3, 1, 1) self.buttons['clsm'] = QPushButton('Close Menu', self) self.buttons['clsm'].clicked.connect(self.root.toggle_menu) grid.addWidget(self.buttons['clsm'], 2, 5, 1, 1) self.typeradios = {} for i, key in enumerate(['o4i', 'o4f', 'o8i', 'o8f']): b = QRadioButton(key, self.tabs['pile']) self.typeradios[key] = b self.pilegrid.addWidget(b, 3, i, 1, 1) for i, key in enumerate(['t4i', 't4f', 't8f']): b = QRadioButton(key, self.tabs['pile']) self.typeradios[key] = b self.pilegrid.addWidget(b, 4, i, 1, 1) for i, key in enumerate(['t6hi', 't6hf', 't6vi', 't6vf']): b = QRadioButton(key, self.tabs['pile']) self.typeradios[key] = b self.pilegrid.addWidget(b, 5, i, 1, 1) for k in self.typeradios: b = self.typeradios[k] b.clicked.connect(self.set_piletype) self.vslgrid.addWidget(QLabel('Timed delay:', self.tabs['visl']), 0, 0, 1, 1) self.vslgrid.addWidget(QLabel('Frames per step:', self.tabs['visl']), 1, 0, 1, 1) self.vslgrid.setRowStretch(2, 1) self.vslgrid.setColumnStretch(2, 1) self.tdspinbox = QSpinBox(self.tabs['visl']) self.tdspinbox.setMinimum(10) self.tdspinbox.valueChanged.connect(self.set_td) self.vslgrid.addWidget(self.tdspinbox, 0, 1, 1, 1) self.fpsspinbox = QSpinBox(self.tabs['visl']) self.fpsspinbox.setMinimum(1) self.fpsspinbox.setMaximum(300) self.fpsspinbox.valueChanged.connect(self.set_fps) self.vslgrid.addWidget(self.fpsspinbox, 1, 1, 1, 1)