def __init__(self): super().__init__() self.initTable() gen = QPushButton('Generate') gen.clicked.connect(self.output) filename = QLineEdit(FILENAME) hbox0 = QHBoxLayout() hbox0.addWidget(gen) hbox0.addWidget(filename) save = QPushButton('Save') savefn = QLineEdit('TileMenuDesktopEntries.cfg') hbox1 = QHBoxLayout() hbox1.addWidget(save) hbox1.addWidget(savefn) load = QPushButton('Load') loadfn = QLineEdit('TileMenuDesktopEntries.cfg') hbox2 = QHBoxLayout() hbox2.addWidget(load) hbox2.addWidget(loadfn) vbox = QVBoxLayout() vbox.addWidget(self.table) vbox.addLayout(hbox1) vbox.addLayout(hbox2) vbox.addLayout(hbox0) self.setGeometry(300, 300, 960, 500) self.setLayout(vbox) self.show()
def __init__(self, parent): super(PercentSlider, self).__init__(parent) self._slider = QSlider(Qt.Vertical, self) self._slider.setMinimum(-100) self._slider.setMaximum(100) self._slider.setValue(0) self._slider.setTickInterval(100) self._slider.setTickPosition(QSlider.TicksBothSides) self._slider.valueChanged.connect(lambda: self._spinbox.setValue(self._slider.value())) self._spinbox = QSpinBox(self) self._spinbox.setMinimum(-100) self._spinbox.setMaximum(100) self._spinbox.setValue(0) self._spinbox.valueChanged.connect(lambda: self._slider.setValue(self._spinbox.value())) self._zero_button = make_icon_button("hand-stop-o", "Zero setpoint", self, on_clicked=self.zero) layout = QVBoxLayout(self) sub_layout = QHBoxLayout(self) sub_layout.addStretch() sub_layout.addWidget(self._slider) sub_layout.addStretch() layout.addLayout(sub_layout) layout.addWidget(self._spinbox) layout.addWidget(self._zero_button) self.setLayout(layout) self.setMinimumHeight(400)
def add_to_layout(layout, *items): """Add items to QVBox and QHBox layouts easily. Keyword arguments: layout -- a layout oject (QVBoxLayout or QHBoxLayout) or a string if "v" or "h" create a QVBox or QHBox respectively *items -- list with items to be added """ if isinstance(layout, str): if layout == "v": layout = QVBoxLayout() elif layout == "h": layout = QHBoxLayout() else: raise TypeError("Invalid layout!") for item in items: if isinstance(item, QWidget): layout.addWidget(item) elif isinstance(item, QLayout): layout.addLayout(item) elif isinstance(item, QSpacerItem): layout.addItem(item) elif item is None: layout.addStretch() else: raise TypeError("Argument of wrong type!") return layout
def __init__(self, gallery, tuple_first_idx, text=None, parent = None): super().__init__(parent, flags= Qt.Dialog | Qt.FramelessWindowHint) main_layout = QVBoxLayout() self.main_widget.setLayout(main_layout) g_showcase = GalleryShowcaseWidget() g_showcase.set_gallery(gallery, (170//1.40, 170)) if text: t_layout = QHBoxLayout() main_layout.addLayout(t_layout) t_layout.addWidget(g_showcase, 1) info = QLabel(text) info.setWordWrap(True) t_layout.addWidget(info) else: main_layout.addWidget(g_showcase, 0, Qt.AlignCenter) self.list_w = QListWidget(self) main_layout.addWidget(self.list_w, 3) main_layout.addLayout(self.buttons_layout) for t in tuple_first_idx: item = GalleryListItem(t) item.setText(t[0]) self.list_w.addItem(item) buttons = self.add_buttons('Choose') buttons[0].clicked.connect(self.finish) self.resize(400, 400) self.show()
def __init__(self, parent=None): super().__init__(parent) self.setSubTitle(self.tr("<h2>Select Menu Style</h2>")) texts = [ self.tr("<p>Application Menu is the default for KaOS because of its \ extremely lightweight (and fast) structure.</p>"), self.tr("<p>Application Launcher is the standard for KDE. \ Application shortcuts are arranged under a tab structure.</p>"), self.tr("<p>Application Panel is a full screen menu style. \ Application shortcuts are arranged so that you can access them quickly and easily.</p>") ] self.menus = [[":/data/images/menu-kicker.png", texts[0]], [":/data/images/menu-kickoff.png", texts[1]], [":/data/images/menu-kimpanel.png", texts[2]]] vlayout = QVBoxLayout(self) labelLayout = QHBoxLayout() iconLabel = QLabel() iconLabel.setMaximumSize(64, 64) iconLabel.setPixmap(QIcon.fromTheme("kde").pixmap(64, 64)) labelLayout.addWidget(iconLabel) label = QLabel(self) label.setText(self.tr("<p>You can also customize your <strong>KDE menu</strong> as you like. \ Please choose one from the following styles.</p>")) labelLayout.addWidget(label) vlayout.addLayout(labelLayout) vlayout.addItem(QSpacerItem(20, 40, QSizePolicy.Preferred, QSizePolicy.Preferred)) self.comboBox = QComboBox(self) self.comboBox.addItem(self.tr("Application Menu")) self.comboBox.addItem(self.tr("Application Launcher")) self.comboBox.addItem(self.tr("Application Dashboard")) vlayout.addWidget(self.comboBox) vlayout.addItem(QSpacerItem(20, 40, QSizePolicy.Preferred, QSizePolicy.Preferred)) hlayout = QHBoxLayout(self) self.labelMenu = QLabel(self) self.labelMenu.setPixmap(QPixmap(self.menus[0][0])) self.labelMenu.setMaximumSize(350 ,214) hlayout.addWidget(self.labelMenu) self.labelText = QLabel(self) self.labelText.setWordWrap(True) self.labelText.setText(self.tr(self.menus[0][1])) hlayout.addWidget(self.labelText) vlayout.addLayout(hlayout) vlayout.addItem(QSpacerItem(20, 40, QSizePolicy.Preferred, QSizePolicy.Preferred)) self.comboBox.currentIndexChanged.connect(self.menuSelect) self.menuSelected = 0
def __init__(self, citylist, accurate_url, appid, parent=None): super(CityListDlg, self).__init__(parent) self.citylist = citylist self.accurate_url = accurate_url self.appid = appid self.listWidget = QListWidget() self.listWidget.addItems(self.citylist) buttonLayout = QVBoxLayout() self.buttonBox = QDialogButtonBox() self.buttonBox.setOrientation(Qt.Horizontal) self.buttonBox.setStandardButtons(QDialogButtonBox.Ok | QDialogButtonBox.Cancel) self.buttonBox.rejected.connect(self.reject) self.buttonBox.accepted.connect(self.accept) layoutT = QVBoxLayout() layout = QHBoxLayout() layout.addWidget(self.listWidget) layout.addLayout(buttonLayout) for text, slot in ((self.tr("&Add..."), self.add), (self.tr("&Remove..."), self.remove), (self.tr("&Up"), self.up), (self.tr("&Down"), self.down), (self.tr("De&fault"), self.default), (self.tr("&Sort"), self.listWidget.sortItems)): button = QPushButton(text) buttonLayout.addWidget(button) button.clicked.connect(slot) buttonLayout.addWidget(self.buttonBox) self.status = QLabel() layoutT.addLayout(layout) layoutT.addWidget(self.status) self.setLayout(layoutT) self.checklength()
def __init__(self, parent=None): super(ResultHandler, self).__init__() self.setWindowTitle('Dash results') self.control_label = QLabel() self.rendered_label = QLabel() self.diff_label = QLabel() self.mask_label = QLabel() self.new_mask_label = QLabel() self.scrollArea = QScrollArea() self.widget = QWidget() self.test_name_label = QLabel() grid = QGridLayout() grid.addWidget(self.test_name_label, 0, 0) grid.addWidget(QLabel('Control'), 1, 0) grid.addWidget(QLabel('Rendered'), 1, 1) grid.addWidget(QLabel('Difference'), 1, 2) grid.addWidget(self.control_label, 2, 0) grid.addWidget(self.rendered_label, 2, 1) grid.addWidget(self.diff_label, 2, 2) grid.addWidget(QLabel('Current Mask'), 3, 0) grid.addWidget(QLabel('New Mask'), 3, 1) grid.addWidget(self.mask_label, 4, 0) grid.addWidget(self.new_mask_label, 4, 1) self.widget.setLayout(grid) self.scrollArea.setWidget(self.widget) v_layout = QVBoxLayout() v_layout.addWidget(self.scrollArea, 1) next_image_button = QPushButton() next_image_button.setText('Skip') next_image_button.pressed.connect(self.load_next) self.overload_spin = QDoubleSpinBox() self.overload_spin.setMinimum(1) self.overload_spin.setMaximum(255) self.overload_spin.setValue(1) self.overload_spin.valueChanged.connect(lambda: save_mask_button.setEnabled(False)) preview_mask_button = QPushButton() preview_mask_button.setText('Preview New Mask') preview_mask_button.pressed.connect(self.preview_mask) preview_mask_button.pressed.connect(lambda: save_mask_button.setEnabled(True)) save_mask_button = QPushButton() save_mask_button.setText('Save New Mask') save_mask_button.pressed.connect(self.save_mask) button_layout = QHBoxLayout() button_layout.addWidget(next_image_button) button_layout.addWidget(QLabel('Mask diff multiplier:')) button_layout.addWidget(self.overload_spin) button_layout.addWidget(preview_mask_button) button_layout.addWidget(save_mask_button) button_layout.addStretch() v_layout.addLayout(button_layout) self.setLayout(v_layout)
def init(self): vbox = QVBoxLayout() self.setLayout(vbox) text = QLineEdit('0.') text.setReadOnly(True) vbox.addWidget(text) grid = QGridLayout() vbox.addLayout(grid) names = ['Exit', 'AC', 'DEL', '+/-', '7', '8', '9', '/', '4', '5', '6', '*', '1', '2', '3', '-', '0', '.', '=', '+'] positions = [(i, j) for i in range(5) for j in range(4)] for position, name in zip(positions, names): btn = QPushButton(name) grid.addWidget(btn, *position) self.move(300, 200) self.setWindowTitle('Calculator') self.show()
def export_history_dialog(self): d = WindowModalDialog(self, _('Export History')) d.setMinimumSize(400, 200) vbox = QVBoxLayout(d) defaultname = os.path.expanduser('~/vialectrum-history.csv') select_msg = _('Select file to export your wallet transactions to') hbox, filename_e, csv_button = filename_field(self, self.config, defaultname, select_msg) vbox.addLayout(hbox) vbox.addStretch(1) hbox = Buttons(CancelButton(d), OkButton(d, _('Export'))) vbox.addLayout(hbox) #run_hook('export_history_dialog', self, hbox) self.update() if not d.exec_(): return filename = filename_e.text() if not filename: return try: self.do_export_history(filename, csv_button.isChecked()) except (IOError, os.error) as reason: export_error_label = _("Electrum was unable to produce a transaction export.") self.parent.show_critical(export_error_label + "\n" + str(reason), title=_("Unable to export history")) return self.parent.show_message(_("Your wallet history has been successfully exported."))
def __init__(self, *args): super().__init__(BrickletAnalogIn, *args) self.ai = self.device # the firmware version of a EEPROM Bricklet can (under common circumstances) # not change during the lifetime of an EEPROM Bricklet plugin. therefore, # it's okay to make final decisions based on it here self.has_range = self.firmware_version >= (2, 0, 1) self.has_averaging = self.firmware_version >= (2, 0, 3) self.cbe_voltage = CallbackEmulator(self.ai.get_voltage, None, self.cb_voltage, self.increase_error_count) self.current_voltage = CurveValueWrapper() # float, V plots = [('Voltage', Qt.red, self.current_voltage, format_voltage)] self.plot_widget = PlotWidget('Voltage [V]', plots, y_resolution=0.001) layout = QVBoxLayout(self) layout.addWidget(self.plot_widget) if self.has_range: self.combo_range = QComboBox() self.combo_range.addItem('Automatic', BrickletAnalogIn.RANGE_AUTOMATIC) if self.has_averaging: self.combo_range.addItem('0 - 3.30 V', BrickletAnalogIn.RANGE_UP_TO_3V) self.combo_range.addItem('0 - 6.05 V', BrickletAnalogIn.RANGE_UP_TO_6V) self.combo_range.addItem('0 - 10.32 V', BrickletAnalogIn.RANGE_UP_TO_10V) self.combo_range.addItem('0 - 36.30 V', BrickletAnalogIn.RANGE_UP_TO_36V) self.combo_range.addItem('0 - 45.00 V', BrickletAnalogIn.RANGE_UP_TO_45V) self.combo_range.currentIndexChanged.connect(self.range_changed) hlayout = QHBoxLayout() hlayout.addWidget(QLabel('Range:')) hlayout.addWidget(self.combo_range) hlayout.addStretch() if self.has_averaging: self.spin_average = QSpinBox() self.spin_average.setMinimum(0) self.spin_average.setMaximum(255) self.spin_average.setSingleStep(1) self.spin_average.setValue(50) self.spin_average.editingFinished.connect(self.spin_average_finished) hlayout.addWidget(QLabel('Average Length:')) hlayout.addWidget(self.spin_average) line = QFrame() line.setObjectName("line") line.setFrameShape(QFrame.HLine) line.setFrameShadow(QFrame.Sunken) layout.addWidget(line) layout.addLayout(hlayout)
def __init__(self, parent): super(CharacterDialog, self).__init__(parent) self.setWindowTitle(_("KeepKey Seed Recovery")) self.character_pos = 0 self.word_pos = 0 self.loop = QEventLoop() self.word_help = QLabel() self.char_buttons = [] vbox = QVBoxLayout(self) vbox.addWidget(WWLabel(CHARACTER_RECOVERY)) hbox = QHBoxLayout() hbox.addWidget(self.word_help) for i in range(4): char_button = CharacterButton('*') char_button.setMaximumWidth(36) self.char_buttons.append(char_button) hbox.addWidget(char_button) self.accept_button = CharacterButton(_("Accept Word")) self.accept_button.clicked.connect(partial(self.process_key, 32)) self.rejected.connect(partial(self.loop.exit, 1)) hbox.addWidget(self.accept_button) hbox.addStretch(1) vbox.addLayout(hbox) self.finished_button = QPushButton(_("Seed Entered")) self.cancel_button = QPushButton(_("Cancel")) self.finished_button.clicked.connect(partial(self.process_key, Qt.Key_Return)) self.cancel_button.clicked.connect(self.rejected) buttons = Buttons(self.finished_button, self.cancel_button) vbox.addSpacing(40) vbox.addLayout(buttons) self.refresh() self.show()
def __init__(self, parent=None): super(ToolOffsetDialog, self).__init__(parent) self._color = QColor(0, 0, 0, 150) self._state = False self.setWindowModality(Qt.ApplicationModal) self.setWindowFlags(self.windowFlags() | Qt.Tool | Qt.Dialog | Qt.WindowStaysOnTopHint | Qt.WindowSystemMenuHint) self.setMinimumSize(200, 200) buttonBox = QDialogButtonBox() buttonBox.setEnabled(False) STATUS.connect('not-all-homed', lambda w, axis: buttonBox.setEnabled(False)) STATUS.connect('all-homed', lambda w: buttonBox.setEnabled(True)) STATUS.connect('state-estop', lambda w: buttonBox.setEnabled(False)) STATUS.connect('state-estop-reset', lambda w: buttonBox.setEnabled(STATUS.machine_is_on() and STATUS.is_all_homed())) for i in('X', 'Y', 'Z'): b = 'button_%s' % i self[b] = QPushButton('Zero %s' % i) self[b].clicked.connect(self.zeroPress('%s' % i)) buttonBox.addButton(self[b], 3) v = QVBoxLayout() h = QHBoxLayout() self._o = TOOLVIEW_WIDGET() self._o._hal_init() self.setLayout(v) v.addWidget(self._o) b = QPushButton('OK') b.clicked.connect(lambda: self.close()) h.addWidget(b) h.addWidget(buttonBox) v.addLayout(h) self.setModal(True)
def widgetImage(self): """Create main image display. """ imageArea = QHBoxLayout() scroll = QScrollArea() scroll.setAlignment(QtCore.Qt.AlignCenter) self.imageLabel = QLabel(self) scroll.setWidget(self.imageLabel) next = QPushButton(self.tr('>')) next.clicked.connect(self.nextCluster) prev = QPushButton(self.tr('<')) prev.clicked.connect(self.prevCluster) imageArea.addWidget(prev) imageArea.addWidget(scroll) imageArea.addWidget(next) vbox = QVBoxLayout() self.clusterCountLabel = QLabel(self) self.clusterCountLabel.setAlignment(QtCore.Qt.AlignCenter) f = QtGui.QFont('Arial', 14, QtGui.QFont.Bold); self.clusterCountLabel.setFont(f) vbox.addWidget(self.clusterCountLabel) vbox.addLayout(imageArea) return vbox
def __init__(self, *args): super().__init__(BrickletTemperatureV2, *args) self.tem = self.device self.cbe_temperature = CallbackEmulator(self.tem.get_temperature, None, self.cb_temperature, self.increase_error_count) self.current_temperature = CurveValueWrapper() # float, °C plots_temperature = [('Temperature', Qt.red, self.current_temperature, '{} °C'.format)] self.plot_widget_temperature = PlotWidget('Temperature [°C]', plots_temperature, y_resolution=0.01) self.enable_heater = QCheckBox("Enable Heater") self.enable_heater.stateChanged.connect(self.enable_heater_changed) layout_plot = QHBoxLayout() layout_plot.addWidget(self.plot_widget_temperature) layout_config = QHBoxLayout() layout_config.addStretch() layout_config.addWidget(self.enable_heater) layout_config.addStretch() layout_main = QVBoxLayout(self) layout_main.addLayout(layout_plot) layout_main.addLayout(layout_config)
def show_info_dialog( caption, parent, initial_text ): dialog = QDialog( parent ) dialog.setWindowTitle( caption ) # Create OK and Cancel buttons in a horizontal box. ok_button = QPushButton("OK") ok_button.setDefault(True) ok_button.clicked.connect(dialog.accept) cancel_button = QPushButton("Cancel") cancel_button.setDefault(False) cancel_button.clicked.connect(dialog.reject) hbox = QHBoxLayout() hbox.addWidget(cancel_button,0) hbox.addStretch() hbox.addWidget(ok_button,0) # Lay out a Plain Text Edit above the buttons. vbox = QVBoxLayout() pt_editor = QPlainTextEdit() pt_editor.document().setPlainText( initial_text ) vbox.addWidget(pt_editor,1) vbox.addLayout(hbox,0) dialog.setLayout(vbox) result = dialog.exec_() if result : return pt_editor.document().toPlainText() else : return None
def __init__(self, path, gallery, parent=None): super().__init__(parent) gallery.dead_link = True def commit(): msgbox = QMessageBox(self) msgbox.setIcon(QMessageBox.Question) msgbox.setWindowTitle('Type of gallery source') msgbox.setInformativeText('What type of gallery source is it?') dir = msgbox.addButton('Directory', QMessageBox.YesRole) archive = msgbox.addButton('Archive', QMessageBox.NoRole) msgbox.exec() new_path = '' if msgbox.clickedButton() == dir: new_path = QFileDialog.getExistingDirectory(self, 'Choose directory') elif msgbox.clickedButton() == archive: new_path = QFileDialog.getOpenFileName(self, 'Choose archive', filter=utils.FILE_FILTER) new_path = new_path[0] else: return None if new_path: g = utils.update_gallery_path(new_path, gallery) self.UPDATE_SIGNAL.emit(g) self.close() def remove_commit(): self.REMOVE_SIGNAL.emit(gallery) self.close() main_layout = QVBoxLayout() inner_layout = QHBoxLayout() cover = QLabel() img = QPixmap(gallery.profile) cover.setPixmap(img) title_lbl = QLabel(gallery.title) title_lbl.setAlignment(Qt.AlignCenter) info_lbl = QLabel("The path to this gallery has been removed\n"+ "What do you want to do?") #info_lbl.setWordWrap(True) path_lbl = QLabel(path) path_lbl.setWordWrap(True) info_lbl.setAlignment(Qt.AlignCenter) inner_layout.addWidget(cover) inner_layout.addWidget(info_lbl) main_layout.addLayout(inner_layout) main_layout.addWidget(path_lbl) close_btn = QPushButton('Close') close_btn.clicked.connect(self.close) update_btn = QPushButton('Update path...') update_btn.clicked.connect(commit) remove_btn = QPushButton('Remove') remove_btn.clicked.connect(remove_commit) buttons_layout = QHBoxLayout() buttons_layout.addWidget(remove_btn) buttons_layout.addWidget(update_btn) buttons_layout.addWidget(close_btn) main_layout.addWidget(title_lbl) main_layout.addLayout(buttons_layout) self.main_widget.setLayout(main_layout) self.adjustSize() self.show()
def changeTileWidth(): """Change tile width (tile block size) and reset image-scene""" dlg = QDialog(self) dlg.setWindowTitle("Viewer Tile Width") dlg.setModal(True) spinBox = QSpinBox(parent=dlg) spinBox.setRange(128, 10 * 1024) spinBox.setValue(self.editor.imageScenes[0].tileWidth()) ctrl_layout = QHBoxLayout() ctrl_layout.addSpacerItem(QSpacerItem(10, 0, QSizePolicy.Expanding)) ctrl_layout.addWidget(QLabel("Tile Width:")) ctrl_layout.addWidget(spinBox) button_box = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel, parent=dlg) button_box.accepted.connect(dlg.accept) button_box.rejected.connect(dlg.reject) dlg_layout = QVBoxLayout() dlg_layout.addLayout(ctrl_layout) dlg_layout.addWidget( QLabel("Setting will apply current view immediately,\n" "and all other views upon restart.") ) dlg_layout.addWidget(button_box) dlg.setLayout(dlg_layout) if dlg.exec_() == QDialog.Accepted: for s in self.editor.imageScenes: if s.tileWidth != spinBox.value(): s.setTileWidth(spinBox.value()) s.reset()
def virtual_keyboard(self, i, pw): i = i % 3 if i == 0: chars = 'abcdefghijklmnopqrstuvwxyz ' elif i == 1: chars = 'ABCDEFGHIJKLMNOPQRTSUVWXYZ ' elif i == 2: chars = '1234567890!?.,;:/%&()[]{}+-' n = len(chars) s = [] for i in range(n): while True: k = random.randint(0, n - 1) if k not in s: s.append(k) break def add_target(t): return lambda: pw.setText(str(pw.text()) + t) vbox = QVBoxLayout() grid = QGridLayout() grid.setSpacing(2) for i in range(n): l_button = QPushButton(chars[s[i]]) l_button.setFixedWidth(25) l_button.setFixedHeight(25) l_button.clicked.connect(add_target(chars[s[i]])) grid.addWidget(l_button, i // 6, i % 6) vbox.addLayout(grid) return vbox
def __init__(self, tup_gallery, parent = None, menu = None): super().__init__(parent) self.setMaximumWidth(16777215) assert isinstance(tup_gallery, tuple), "Incorrect type received, expected tuple" assert isinstance(tup_gallery[0], str) and isinstance(tup_gallery[1], list) main_layout = QVBoxLayout() # todo make it scroll scroll_area = QScrollArea() dummy = QWidget() self.gallery_layout = misc.FlowLayout(dummy) scroll_area.setWidgetResizable(True) scroll_area.setMaximumHeight(400) scroll_area.setMidLineWidth(620) scroll_area.setBackgroundRole(scroll_area.palette().Shadow) scroll_area.setFrameStyle(scroll_area.NoFrame) scroll_area.setWidget(dummy) text = tup_gallery[0] galleries = tup_gallery[1] main_layout.addWidget(scroll_area, 3) for g in galleries: gall_w = misc.GalleryShowcaseWidget(parent=self, menu=menu()) gall_w.set_gallery(g, (170//1.40, 170)) gall_w.double_clicked.connect(self.gallery_doubleclicked.emit) self.gallery_layout.addWidget(gall_w) text_lbl = QLabel(text) text_lbl.setAlignment(Qt.AlignCenter) main_layout.addWidget(text_lbl) main_layout.addLayout(self.buttons_layout) self.main_widget.setLayout(main_layout) self.setMaximumHeight(500) self.setMaximumWidth(620) self.resize(620, 500) self.show()
def randomWidget(self): group = QGroupBox("Randomize") layout = QGridLayout() self.randomCount = QSpinBox() layout.addWidget(QLabel(self.tr("Count")), 0, 0) layout.addWidget(self.randomCount, 0, 1) self.minBrushSize = BrushSizeWidget(15) self.maxBrushSize = BrushSizeWidget(50) layout.addWidget(QLabel(self.tr("Min")), 1, 0) layout.addWidget(self.minBrushSize, 1, 1) layout.addWidget(QLabel(self.tr("Max")), 2, 0) layout.addWidget(self.maxBrushSize, 2, 1) self.xAngle = QSpinBox() self.yAngle = QSpinBox() self.zAngle = QSpinBox() layout.addWidget(QLabel(self.tr("Angle X")), 3, 0) layout.addWidget(self.xAngle, 3, 1) layout.addWidget(QLabel(self.tr("Angle Y")), 4, 0) layout.addWidget(self.yAngle, 4, 1) layout.addWidget(QLabel(self.tr("Angle Z")), 5, 0) layout.addWidget(self.zAngle, 5, 1) container = QVBoxLayout() container.addLayout(layout) container.addStretch(1) group.setLayout(container) group.setFixedWidth(150) return group
def btnModifyTableStruct_Clicked(self,event): self.dlg=QDialog(self) self.dlg.setWindowTitle(self.CurrentTable+'表结构修改:') self.dlg.setWindowFlags(Qt.Window| Qt.MSWindowsFixedSizeDialogHint ) #lay lay=QVBoxLayout() self.dlgMake_AddColumn(lay) self.dlgMake_RenameColumn(lay) self.dlgMake_ModifyColumnType(lay) self.dlgMake_ModifyColumnConstraint(lay) #layLists layLists=QHBoxLayout() lay.addLayout(layLists) self.dlgMake_DeleteColumn(layLists) self.dlgMake_OrderColumns(layLists) ##layBtns layBtns=QHBoxLayout() lay.addLayout(layBtns) ##btnOk btnOk=QPushButton('提交修改') btnOk.clicked.connect(self.btnOk_Clicked) layBtns.addWidget(btnOk) ##btnCancel btnCancel=QPushButton('放弃修改') btnCancel.clicked.connect(self.btnCancel_Clicked) layBtns.addWidget(btnCancel) self.dlg.setLayout(lay) self.dlg.open()
def __init__(self): super().__init__() # 사용한 위젯들을 생성 lbl1 = QLabel('This is') #<---- 1 lbl2 = QLabel('Layout Example') okButton = QPushButton("OK") cancelButton = QPushButton("Cancel") hbox = QHBoxLayout() #<---- 2 hbox.addStretch(1) #<---- 3 hbox.addWidget(okButton) #<---- 4 hbox.addWidget(cancelButton) #<---- 5 vbox = QVBoxLayout() #<---- 6 vbox.addWidget(lbl1) #<---- 7 vbox.addWidget(lbl2) #<---- 8 vbox.addLayout(hbox) #<---- 9 window = QWidget() #<---- 10 window.setLayout(vbox) #<---- 11 self.setCentralWidget(window) #<---- 12 self.setGeometry(300, 300, 300, 150) self.setWindowTitle('Layout Example') self.show()
def _get_control_layout(self): """ Create static layout. """ widget = QWidget() vbox = QVBoxLayout() widget.setLayout(vbox) vbox.setContentsMargins(0, 0, 0, 0) self.template_combo_box = QComboBox() self.template_combo_box.currentIndexChanged.connect(self._item_selected) vbox.addWidget(self.template_combo_box) scrollable_vbox = utils.get_scrollable(self.controls_layout) vbox.addWidget(scrollable_vbox, stretch=80) buttons_layout = QHBoxLayout() vbox.addLayout(buttons_layout, stretch=20) b = QPushButton("Назад") b.setObjectName("controls") b.clicked.connect(self._close) buttons_layout.addWidget(b) widget.setGraphicsEffect(utils.get_shadow()) return widget
def __init__(self, parent, node): super(FileServerWidget, self).__init__(parent) self.setTitle('File server (uavcan.protocol.file.*)') self._node = node self._file_server = None self._path_widgets = [] self._start_button = make_icon_button('rocket', 'Launch/stop the file server', self, checkable=True, on_clicked=self._on_start_stop) self._start_button.setEnabled(False) self._tmr = QTimer(self) self._tmr.setSingleShot(False) self._tmr.timeout.connect(self._update_on_timer) self._tmr.start(500) self._add_path_button = \ make_icon_button('plus', 'Add lookup path (lookup paths can be modified while the server is running)', self, on_clicked=self._on_add_path) layout = QVBoxLayout(self) controls_layout = QHBoxLayout(self) controls_layout.addWidget(self._start_button) controls_layout.addWidget(self._add_path_button) controls_layout.addStretch(1) layout.addLayout(controls_layout) self.setLayout(layout)
def __init__(self, parent=None): super().__init__(parent) self.setSubTitle(self.tr("<h2>Setup Mouse Behavior</h2>")) vlayout = QVBoxLayout(self) labelLayout = QHBoxLayout() imageLabel = QLabel() imageLabel.setPixmap(QPixmap(":/data/images/preferences-desktop-peripherals.png")) imageLabel.setMaximumSize(64, 64) labelLayout.addWidget(imageLabel) mouseLabel = QLabel(self) mouseLabel.setText(self.tr("""<p>The <strong>clicking behavior</strong> defines how many times you want to click when you are opening a file. If you are <strong>left handed</strong>, you may prefer to swap the left and right buttons of your pointing device.</p>""")) mouseLabel.setWordWrap(True) labelLayout.addWidget(mouseLabel) vlayout.addLayout(labelLayout) vlayout.addItem(QSpacerItem(20, 100, QSizePolicy.Preferred, QSizePolicy.Preferred)) hlayout = QHBoxLayout() vlayout.addLayout(hlayout) self.createGroupBox(hlayout) vlayout.addItem(QSpacerItem(20, 40, QSizePolicy.Preferred, QSizePolicy.Preferred)) self.folderSingleClick = False self.mouseButtonMap = "RightHanded" self.reverseScrollPolarity = False
def init_ui(self): path = os.getcwd() url = path + HTM_FILE self.webView.setUrl(QtCore.QUrl(url)) self.webView.page().loadFinished.connect(self.load_finished) # for test self.inputText.setEnabled(False) self.inputText.setAcceptRichText(False) self.inputText.setToolTip("每行一组经纬度,纬度lat在前\n" + "以空格、逗号或制表符分隔") self.runButton.clicked.connect(self.add_points) # show all points in input text window self.clrButton.clicked.connect(self.clr_points) buttonBox = QHBoxLayout() # button box buttonBox.addStretch() buttonBox.addWidget(self.runButton) buttonBox.addWidget(self.clrButton) rightBox = QVBoxLayout() # right box rightBox.addWidget(self.sourceType) rightBox.addWidget(self.inputText) rightBox.addLayout(buttonBox) rightBox.addWidget(self.statusBar) layout = QHBoxLayout() # main box layout.addWidget(self.webView) layout.addLayout(rightBox) self.setLayout(layout) self.setWindowTitle('经纬度地图显示') self.show()
def __init__(self, parent=None): super(ConfigurationPage, self).__init__(parent) configGroup = QGroupBox("Server configuration") serverLabel = QLabel("Server:") serverCombo = QComboBox() serverCombo.addItem("Trolltech (Australia)") serverCombo.addItem("Trolltech (Germany)") serverCombo.addItem("Trolltech (Norway)") serverCombo.addItem("Trolltech (People's Republic of China)") serverCombo.addItem("Trolltech (USA)") serverLayout = QHBoxLayout() serverLayout.addWidget(serverLabel) serverLayout.addWidget(serverCombo) configLayout = QVBoxLayout() configLayout.addLayout(serverLayout) configGroup.setLayout(configLayout) mainLayout = QVBoxLayout() mainLayout.addWidget(configGroup) mainLayout.addStretch(1) self.setLayout(mainLayout)
def initialize(self): tab_widget = QTabWidget() tab1 = QWidget() tab2 = QWidget() juggle_button = QPushButton("Juggle") juggle_button.clicked.connect(self.start_simulation) hbox = QHBoxLayout() hbox.addStretch(1) hbox.addWidget(juggle_button) vbox = QVBoxLayout(tab1) vbox.addStretch(1) vbox.addLayout(hbox) hbox2 = QHBoxLayout(tab2) tab_widget.addTab(tab1, "Main") tab_widget.addTab(tab2, "Other") self.setCentralWidget(tab_widget) menubar = self.menuBar() file_menu = menubar.addMenu('&File') help_menu = menubar.addMenu('&Help') about = help_menu.addMenu('&About') exit_action = QAction(QIcon('exit.png'), '&Exit', self) exit_action.triggered.connect(qApp.quit) file_menu.addAction(exit_action) self.setGeometry(300, 300, 350, 300) self.setWindowTitle('Juggling Simulator') self.show()
def __init__(self, page): super(LogTool, self).__init__(page) layout = QVBoxLayout() self.setLayout(layout) self.fontLabel = QLabel() self.fontChooser = QFontComboBox(currentFontChanged=self.changed) self.fontSize = QDoubleSpinBox(valueChanged=self.changed) self.fontSize.setRange(6.0, 32.0) self.fontSize.setSingleStep(0.5) self.fontSize.setDecimals(1) box = QHBoxLayout() box.addWidget(self.fontLabel) box.addWidget(self.fontChooser, 1) box.addWidget(self.fontSize) layout.addLayout(box) self.showlog = QCheckBox(toggled=self.changed) layout.addWidget(self.showlog) self.rawview = QCheckBox(toggled=self.changed) layout.addWidget(self.rawview) self.hideauto = QCheckBox(toggled=self.changed) layout.addWidget(self.hideauto) app.translateUI(self)
def __init__(self, parent): super(GeneralPreferences, self).__init__(parent) layout = QVBoxLayout() self.setLayout(layout) self.typq = QCheckBox() self.tagl = QCheckBox() self.barnum = QCheckBox() self.neutdir = QCheckBox() self.midi = QCheckBox() self.metro = QCheckBox() self.paperSizeLabel = QLabel() self.paper = QComboBox() self.paper.addItems(paperSizes) self.paperLandscape = QCheckBox(enabled=False) self.paper.activated.connect(self.slotPaperChanged) layout.addWidget(self.typq) layout.addWidget(self.tagl) layout.addWidget(self.barnum) layout.addWidget(self.neutdir) layout.addWidget(self.midi) layout.addWidget(self.metro) box = QHBoxLayout(spacing=2) box.addWidget(self.paperSizeLabel) box.addWidget(self.paper) box.addWidget(self.paperLandscape) layout.addLayout(box) app.translateUI(self) self.loadSettings() self.window().finished.connect(self.saveSettings)
class VistaInserisciMovimento(QWidget): def __init__(self, controller, callback, parent=None): super(VistaInserisciMovimento, self).__init__(parent) self.setFixedSize(500, 400) self.controller = controller self.callback = callback # creo un dizionario vuoto, da popolare con le voci del movimento self.info = {} self.v_layout = QVBoxLayout() btn_aggiungi = QPushButton("Aggiugngi") btn_aggiungi.setStyleSheet( "background-color: #90ee90; font-size: 13px; font-weight: bold;") btn_aggiungi.clicked.connect(self.aggiugni_movimento) btn_annulla = QPushButton("Annulla") btn_annulla.setStyleSheet( "background-color: #f08080; font-size: 13px; font-weight: bold;") btn_annulla.clicked.connect(self.annulla) btn_data = QPushButton("Inserisci data") btn_data.clicked.connect(self.visualizza_calendario) self.v_layout.addLayout( self.get_label_line("<b>Causale</b>", "Causale", "Causale")) self.v_layout.addLayout( self.get_label_line("<b>Importo<b/>", "Importo", "0000.00")) self.v_layout.addLayout(self.get_radio_button(['Incasso', 'Spesa'])) self.v_layout.addWidget(btn_data) self.v_layout.addItem( QSpacerItem(45, 45, QSizePolicy.Minimum, QSizePolicy.Minimum)) self.v_layout.addWidget(btn_aggiungi) self.v_layout.addWidget(btn_annulla) self.setLayout(self.v_layout) # funzione di scelta del tipo di movimento def get_radio_button(self, lista): h_lay = QHBoxLayout() h_lay.addWidget(QLabel("<b>Tipo di movimento<b/>")) # passo una lista (incasso, spesa) for item in lista: self.radiobutton = QRadioButton(item) self.radiobutton.tipo = item self.radiobutton.toggled.connect(self.scelta_radio) h_lay.addWidget(self.radiobutton) return h_lay # funzione che ritorna true o false a seconda della selezione del radioButton def scelta_radio(self): self.radioButton = self.sender() # la scelta viene usata per il calcolo del saldo totale dei movimenti if self.radioButton.isChecked(): if self.radioButton.tipo == "Incasso": self.tipo = True if self.radioButton.tipo == "Spesa": self.tipo = False # funzione di visualizzazione del calendario che permette di selezionare la data def visualizza_calendario(self): self.window = QWidget() self.v1_layout = QVBoxLayout() self.calendario = QCalendarWidget() self.calendario.setGridVisible(True) self.v1_layout.addWidget(self.calendario) self.btn_conferma = QPushButton("Conferma") self.btn_conferma.clicked.connect(self.window.close) self.v1_layout.addWidget(self.btn_conferma) self.window.setLayout(self.v1_layout) self.window.show() # funzione che ritorna la data che viene selezionata nel calendario def data_selezionata(self): oggi = datetime.today() oggi_formattato = oggi.strftime("%d/%m/%Y") oggi_formattato_per_unix = datetime.strptime(oggi_formattato, '%d/%m/%Y') oggi_unix = datetime.timestamp(oggi_formattato_per_unix) try: data_selezionata = self.calendario.selectedDate() data = "{}/{}/{}".format(data_selezionata.day(), data_selezionata.month(), data_selezionata.year()) self.calendario.close() return data except: QMessageBox.critical(self, 'Errore', 'Per favore, inserisci la data', QMessageBox.Ok, QMessageBox.Ok) #funzione che ritorna un layout con una lable ed una casella di testo poste in orizzontale def get_label_line(self, label, tipo, placeholder): layout = QHBoxLayout() layout.addWidget(QLabel(label)) current_text_edit = QLineEdit(self) current_text_edit.setPlaceholderText(placeholder) layout.addWidget(current_text_edit) self.info[tipo] = current_text_edit return layout # funzione di annullamento di inserimento del movimento def annulla(self): self.close() from listamovimenti.views.VistaListaMovimenti import VistaListaMovimenti self.vistaListaMovimenti = VistaListaMovimenti() return self.vistaListaMovimenti.show() # funzione di aggiunta del movimento con i campi immessi nella vista di inserimento def aggiugni_movimento(self): try: data = self.data_selezionata() causale = self.info["Causale"].text() descrizione = str(self.radioButton.tipo) if isinstance(float(self.info["Importo"].text()), float): importo = self.info["Importo"].text() else: QMessageBox.critical( self, 'Errore', 'Per favore, inserisci un importo valido', QMessageBox.Ok, QMessageBox.Ok) if descrizione == "": QMessageBox.critical( self, 'Errore', 'Per favore, inserisci tutte le informazioni richieste', QMessageBox.Ok, QMessageBox.Ok) else: print("Creo movimento") self.movimento = Movimento(data, causale, descrizione, importo) self.movimento.isEntrata = self.tipo self.controller.aggiungi_movimento(self.movimento) print("Aggiunto alla lista") self.controller.save_data() self.callback() self.close() from listamovimenti.views.VistaListaMovimenti import VistaListaMovimenti VistaListaMovimenti().update() self.vistaListaMovimenti = VistaListaMovimenti() return self.vistaListaMovimenti.show() except: QMessageBox.critical( self, 'Errore', 'Per favore, inserisci tutte le informazioni richieste nel modo corretto', QMessageBox.Ok, QMessageBox.Ok)
class GuiProjectLoad(QDialog): NONE_STATE = 0 NEW_STATE = 1 OPEN_STATE = 2 C_NAME = 0 C_COUNT = 1 C_TIME = 2 def __init__(self, theParent): QDialog.__init__(self, theParent) logger.debug("Initialising GuiProjectLoad ...") self.setObjectName("GuiProjectLoad") self.mainConf = nw.CONFIG self.theParent = theParent self.theTheme = theParent.theTheme self.openState = self.NONE_STATE self.openPath = None sPx = self.mainConf.pxInt(16) nPx = self.mainConf.pxInt(96) iPx = self.theTheme.baseIconSize self.outerBox = QVBoxLayout() self.innerBox = QHBoxLayout() self.outerBox.setSpacing(sPx) self.innerBox.setSpacing(sPx) self.setWindowTitle("Open Project") self.setMinimumWidth(self.mainConf.pxInt(650)) self.setMinimumHeight(self.mainConf.pxInt(400)) self.setModal(True) self.nwIcon = QLabel() self.nwIcon.setPixmap( self.theParent.theTheme.getPixmap("novelwriter", (nPx, nPx))) self.innerBox.addWidget(self.nwIcon, 0, Qt.AlignTop) self.projectForm = QGridLayout() self.projectForm.setContentsMargins(0, 0, 0, 0) self.listBox = QTreeWidget() self.listBox.setSelectionMode(QAbstractItemView.SingleSelection) self.listBox.setDragDropMode(QAbstractItemView.NoDragDrop) self.listBox.setColumnCount(3) self.listBox.setHeaderLabels(["Working Title", "Words", "Last Opened"]) self.listBox.setRootIsDecorated(False) self.listBox.itemSelectionChanged.connect(self._doSelectRecent) self.listBox.itemDoubleClicked.connect(self._doOpenRecent) self.listBox.setIconSize(QSize(iPx, iPx)) treeHead = self.listBox.headerItem() treeHead.setTextAlignment(self.C_COUNT, Qt.AlignRight) treeHead.setTextAlignment(self.C_TIME, Qt.AlignRight) self.lblRecent = QLabel("<b>Recently Opened Projects</b>") self.lblPath = QLabel("<b>Path</b>") self.selPath = QLineEdit("") self.selPath.setReadOnly(True) self.browseButton = QPushButton("...") self.browseButton.setMaximumWidth( int(2.5 * self.theTheme.getTextWidth("..."))) self.browseButton.clicked.connect(self._doBrowse) self.projectForm.addWidget(self.lblRecent, 0, 0, 1, 3) self.projectForm.addWidget(self.listBox, 1, 0, 1, 3) self.projectForm.addWidget(self.lblPath, 2, 0, 1, 1) self.projectForm.addWidget(self.selPath, 2, 1, 1, 1) self.projectForm.addWidget(self.browseButton, 2, 2, 1, 1) self.projectForm.setColumnStretch(0, 0) self.projectForm.setColumnStretch(1, 1) self.projectForm.setColumnStretch(2, 0) self.projectForm.setVerticalSpacing(self.mainConf.pxInt(4)) self.projectForm.setHorizontalSpacing(self.mainConf.pxInt(8)) self.innerBox.addLayout(self.projectForm) self.buttonBox = QDialogButtonBox(QDialogButtonBox.Open | QDialogButtonBox.Cancel) self.buttonBox.accepted.connect(self._doOpenRecent) self.buttonBox.rejected.connect(self._doCancel) self.newButton = self.buttonBox.addButton("New", QDialogButtonBox.ActionRole) self.newButton.clicked.connect(self._doNewProject) self.outerBox.addLayout(self.innerBox) self.outerBox.addWidget(self.buttonBox) self.setLayout(self.outerBox) self._populateList() self._doSelectRecent() keyDelete = QShortcut(self.listBox) keyDelete.setKey(QKeySequence(Qt.Key_Delete)) keyDelete.activated.connect(self._keyPressDelete) logger.debug("GuiProjectLoad initialisation complete") return ## # Buttons ## def _doOpenRecent(self): """Close the dialog window with a recent project selected. """ logger.verbose("GuiProjectLoad open button clicked") self._saveSettings() self.openPath = None self.openState = self.NONE_STATE selItems = self.listBox.selectedItems() if selItems: self.openPath = selItems[0].data(self.C_NAME, Qt.UserRole) self.openState = self.OPEN_STATE self.accept() return def _doSelectRecent(self): """A recent item has been selected. """ selList = self.listBox.selectedItems() if selList: self.selPath.setText(selList[0].data(self.C_NAME, Qt.UserRole)) return def _doBrowse(self): """Browse for a folder path. """ logger.verbose("GuiProjectLoad browse button clicked") dlgOpt = QFileDialog.Options() dlgOpt |= QFileDialog.DontUseNativeDialog projFile, _ = QFileDialog.getOpenFileName( self, "Open novelWriter Project", "", "novelWriter Project File (%s);;All Files (*)" % nwFiles.PROJ_FILE, options=dlgOpt) if projFile: thePath = os.path.abspath(os.path.dirname(projFile)) self.selPath.setText(thePath) self.openPath = thePath self.openState = self.OPEN_STATE self.accept() return def _doCancel(self): """Close the dialog window without doing anything. """ logger.verbose("GuiProjectLoad close button clicked") self.openPath = None self.openState = self.NONE_STATE self.close() return def _doNewProject(self): """Create a new project. """ logger.verbose("GuiProjectLoad new project button clicked") self._saveSettings() self.openPath = None self.openState = self.NEW_STATE self.accept() return def _keyPressDelete(self): """Remove an entry from the recent projects list. """ selList = self.listBox.selectedItems() if selList: msgYes = self.theParent.askQuestion( "Remove Entry", "Remove the selected entry from the recent projects list?") if msgYes: self.mainConf.removeFromRecentCache(selList[0].data( self.C_NAME, Qt.UserRole)) self._populateList() return ## # Events ## def closeEvent(self, theEvent): """Capture the user closing the dialog so we can save settings. """ self._saveSettings() theEvent.accept() return ## # Internal Functions ## def _saveSettings(self): """Save the changes made to the dialog. """ colWidths = [0, 0, 0] colWidths[self.C_NAME] = self.listBox.columnWidth(self.C_NAME) colWidths[self.C_COUNT] = self.listBox.columnWidth(self.C_COUNT) colWidths[self.C_TIME] = self.listBox.columnWidth(self.C_TIME) self.mainConf.setProjColWidths(colWidths) return def _populateList(self): """Populate the list box with recent project data. """ listOrder = [] listData = {} for projPath in self.mainConf.recentProj.keys(): theEntry = self.mainConf.recentProj[projPath] theTitle = "" theTime = 0 theWords = 0 if "title" in theEntry.keys(): theTitle = theEntry["title"] if "time" in theEntry.keys(): theTime = theEntry["time"] if "words" in theEntry.keys(): theWords = theEntry["words"] if theTime > 0: listOrder.append(theTime) listData[theTime] = [theTitle, theWords, projPath] self.listBox.clear() hasSelection = False for timeStamp in sorted(listOrder, reverse=True): newItem = QTreeWidgetItem([""] * 4) newItem.setIcon(self.C_NAME, self.theParent.theTheme.getIcon("proj_nwx")) newItem.setText(self.C_NAME, listData[timeStamp][0]) newItem.setData(self.C_NAME, Qt.UserRole, listData[timeStamp][2]) newItem.setText(self.C_COUNT, formatInt(listData[timeStamp][1])) newItem.setText( self.C_TIME, datetime.fromtimestamp(timeStamp).strftime("%x %X")) newItem.setTextAlignment(self.C_NAME, Qt.AlignLeft | Qt.AlignVCenter) newItem.setTextAlignment(self.C_COUNT, Qt.AlignRight | Qt.AlignVCenter) newItem.setTextAlignment(self.C_TIME, Qt.AlignRight | Qt.AlignVCenter) newItem.setFont(self.C_TIME, self.theTheme.guiFontFixed) self.listBox.addTopLevelItem(newItem) if not hasSelection: newItem.setSelected(True) hasSelection = True projColWidth = self.mainConf.getProjColWidths() if len(projColWidth) == 3: self.listBox.setColumnWidth(self.C_NAME, projColWidth[self.C_NAME]) self.listBox.setColumnWidth(self.C_COUNT, projColWidth[self.C_COUNT]) self.listBox.setColumnWidth(self.C_TIME, projColWidth[self.C_TIME]) return
class PyEmailerUi(QMainWindow): def __init__(self, sPic): super().__init__() self.pic = sPic print(QStyleFactory.keys()) self.setWindowTitle(cfg.keyboard_title) self.generalLayout = QVBoxLayout() self.showFullScreen() self._centralWidget = QWidget(self) self.setCentralWidget(self._centralWidget) self._centralWidget.setLayout(self.generalLayout) self._centralWidget.setFixedSize(560, 400) self._createDisplay() self._createButtons() global view view = self # Snip def _createDisplay(self): self.display = QLineEdit() self.display2 = QLabel() self.display2.setText(cfg.keyboard_help) self.display.setAlignment(Qt.AlignRight) self.display.setReadOnly(True) self.generalLayout.addWidget(self.display2) self.generalLayout.addWidget(self.display) def setDisplayText(self, text): self.display.setText(text) self.display.setFocus() def displayText(self): return self.display.text() def _close_and_send(self): global sPicture global iTimeSpent print("close and send") print(self.display.text()) f = open(cfg.result_path, "a+") print( str(datetime.now()) + "#" + self.display.text() + "#" + self.pic + "\n") f.write( str(datetime.now()) + "#" + self.display.text() + "#" + self.pic + "\n") f.close() self.hide() self.setDisplayText('') iTimeSpent = 1000 def _close(self): global iTimeSpent self.setDisplayText('') self.hide() iTimeSpent = 1000 def clearDisplay(self): self.setDisplayText('') def _createButtons(self): self.buttons = {} buttonsLayout = QGridLayout() buttons = { cfg.keyboard_short_1: (5, 1, 104), cfg.keyboard_short_2: (5, 3, 104), cfg.keyboard_short_3: (5, 5, 160), cfg.keyboard_domain_1: (5, 8, 50), cfg.keyboard_domain_2: (5, 9, 50), cfg.keyboard_domain_3: (5, 10, 50), '1': (0, 1, 50), '2': (0, 2, 50), '3': (0, 3, 50), '4': (0, 4, 50), '5': (0, 5, 50), '6': (0, 6, 50), '7': (0, 7, 50), '8': (0, 8, 50), '9': (0, 9, 50), '0': (0, 10, 50), 'A': (1, 1, 50), 'B': (1, 2, 50), 'C': (1, 3, 50), 'D': (1, 4, 50), 'E': (1, 5, 50), 'F': (1, 6, 50), 'G': (1, 7, 50), 'H': (1, 8, 50), 'I': (1, 9, 50), 'J': (1, 10, 50), 'K': (2, 1, 50), 'L': (2, 2, 50), 'M': (2, 3, 50), 'N': (2, 4, 50), 'O': (2, 5, 50), 'P': (2, 6, 50), 'Q': (2, 7, 50), 'R': (2, 8, 50), 'S': (2, 9, 50), 'T': (2, 10, 50), 'U': (3, 1, 50), 'V': (3, 2, 50), 'W': (3, 3, 50), 'X': (3, 4, 50), 'Y': (3, 5, 50), 'Z': (3, 6, 50), '!': (3, 7, 50), ',': (3, 8, 50), '.': (3, 9, 50), '@': (3, 10, 50), '-': (4, 1, 50), '_': (4, 2, 50), '#': (4, 3, 50), '$': (4, 4, 50), '%': (4, 5, 50), '^': (4, 6, 50), '&&': (4, 7, 50), '*': (4, 8, 50), '+': (4, 9, 50), ';': (4, 10, 50), cfg.keyboard_clear: (6, 1, 104), cfg.keyboard_cancel: (6, 3, 104), cfg.keyboard_send: (6, 5, 325), } for btnText, pos in buttons.items(): self.buttons[btnText] = QPushButton(btnText) self.buttons[btnText].setFixedSize(pos[2], 40) buttonsLayout.addWidget(self.buttons[btnText], pos[0], pos[1]) self.generalLayout.addLayout(buttonsLayout)
def __init__(self): super(Palette_Docker, self).__init__() # make base-widget and layout widget = QWidget() layout = QVBoxLayout() buttonLayout = QHBoxLayout() widget.setLayout(layout) self.setWindowTitle(i18n("Python Palette Docker")) # Make a combobox and add palettes self.cmb_palettes = QComboBox() allPalettes = Application.resources("palette") for palette_name in allPalettes: self.cmb_palettes.addItem(palette_name) self.cmb_palettes.model().sort(0) if len(allPalettes.keys()) > 0: self.currentPalette = Palette(allPalettes[list( allPalettes.keys())[0]]) else: self.currentPalette = None self.cmb_palettes.currentTextChanged.connect(self.slot_paletteChanged) layout.addWidget(self.cmb_palettes) # add combobox to the layout self.paletteView = PaletteView() self.paletteView.setPalette(self.currentPalette) layout.addWidget(self.paletteView) self.paletteView.entrySelectedForeGround.connect( self.slot_swatchSelected) self.colorComboBox = QComboBox() self.colorList = list() buttonLayout.addWidget(self.colorComboBox) self.bnSetColor = QToolButton() self.bnSetColor.setText(i18n("Set")) self.bnSetColor.clicked.connect(self.slot_get_color_from_combobox) buttonLayout.addWidget(self.bnSetColor) self.addEntry = QAction(self) self.addEntry.setIconText(i18n("+")) self.addEntry.triggered.connect(self.slot_add_entry) self.addGroup = QAction(self) self.addGroup.triggered.connect(self.slot_add_group) self.addGroup.setText(i18n("Add Group")) self.addGroup.setIconText(str("\U0001F4C2")) self.removeEntry = QAction(self) self.removeEntry.setText(i18n("Remove Entry")) self.removeEntry.setIconText("-") self.removeEntry.triggered.connect(self.slot_remove_entry) addEntryButton = QToolButton() addEntryButton.setDefaultAction(self.addEntry) buttonLayout.addWidget(addEntryButton) addGroupButton = QToolButton() addGroupButton.setDefaultAction(self.addGroup) buttonLayout.addWidget(addGroupButton) removeEntryButton = QToolButton() removeEntryButton.setDefaultAction(self.removeEntry) buttonLayout.addWidget(removeEntryButton) # QActions self.extra = QToolButton() self.editPaletteData = QAction(self) self.editPaletteData.setText(i18n("Edit Palette Settings")) self.editPaletteData.triggered.connect(self.slot_edit_palette_data) self.extra.setDefaultAction(self.editPaletteData) buttonLayout.addWidget(self.extra) self.actionMenu = QMenu() self.exportToGimp = QAction(self) self.exportToGimp.setText(i18n("Export as GIMP Palette File")) self.exportToGimp.triggered.connect(self.slot_export_to_gimp_palette) self.exportToInkscape = QAction(self) self.exportToInkscape.setText( i18n("Export as Inkscape SVG with Swatches")) self.exportToInkscape.triggered.connect( self.slot_export_to_inkscape_svg) self.sortColors = QAction(self) self.sortColors.setText(i18n("Sort Colors")) self.sortColors.triggered.connect(self.slot_sort_colors) self.actionMenu.addAction(self.editPaletteData) self.actionMenu.addAction(self.exportToGimp) self.actionMenu.addAction(self.exportToInkscape) # self.actionMenu.addAction(self.sortColors) self.extra.setMenu(self.actionMenu) layout.addLayout(buttonLayout) self.slot_fill_combobox() self.setWidget(widget) # add widget to the docker
def new_channel_dialog(self): lnworker = self.parent.wallet.lnworker d = WindowModalDialog(self.parent, _('Open Channel')) vbox = QVBoxLayout(d) vbox.addWidget(QLabel(_('Enter Remote Node ID or connection string or invoice'))) local_nodeid = FreezableLineEdit() local_nodeid.setMinimumWidth(700) local_nodeid.setText(bh2u(lnworker.node_keypair.pubkey)) local_nodeid.setFrozen(True) local_nodeid.setCursorPosition(0) remote_nodeid = QLineEdit() remote_nodeid.setMinimumWidth(700) amount_e = BTCAmountEdit(self.parent.get_decimal_point) # max button def spend_max(): amount_e.setFrozen(max_button.isChecked()) if not max_button.isChecked(): return make_tx = self.parent.mktx_for_open_channel('!') try: tx = make_tx(None) except (NotEnoughFunds, NoDynamicFeeEstimates) as e: max_button.setChecked(False) amount_e.setFrozen(False) self.main_window.show_error(str(e)) return amount = tx.output_value() amount = min(amount, LN_MAX_FUNDING_SAT) amount_e.setAmount(amount) max_button = EnterButton(_("Max"), spend_max) max_button.setFixedWidth(100) max_button.setCheckable(True) suggest_button = QPushButton(d, text=_('Suggest')) suggest_button.clicked.connect(lambda: remote_nodeid.setText(bh2u(lnworker.suggest_peer() or b''))) clear_button = QPushButton(d, text=_('Clear')) clear_button.clicked.connect(lambda: remote_nodeid.setText('')) h = QGridLayout() h.addWidget(QLabel(_('Your Node ID')), 0, 0) h.addWidget(local_nodeid, 0, 1) h.addWidget(QLabel(_('Remote Node ID')), 1, 0) h.addWidget(remote_nodeid, 1, 1) h.addWidget(suggest_button, 1, 2) h.addWidget(clear_button, 1, 3) h.addWidget(QLabel('Amount'), 2, 0) hbox = QHBoxLayout() hbox.addWidget(amount_e) hbox.addWidget(max_button) hbox.addStretch(1) h.addLayout(hbox, 2, 1) vbox.addLayout(h) ok_button = OkButton(d) ok_button.setDefault(True) vbox.addLayout(Buttons(CancelButton(d), ok_button)) if not d.exec_(): return if max_button.isChecked() and amount_e.get_amount() < LN_MAX_FUNDING_SAT: # if 'max' enabled and amount is strictly less than max allowed, # that means we have fewer coins than max allowed, and hence we can # spend all coins funding_sat = '!' else: funding_sat = amount_e.get_amount() connect_str = str(remote_nodeid.text()).strip() self.parent.open_channel(connect_str, funding_sat, 0)
def add_options_panel(self): # Prepare the sliders options_layout = QVBoxLayout() options_layout.addStretch() # Centralize the sliders sliders_layout = QVBoxLayout() max_label_width = -1 # Get min and max for all dof ranges = [] for i in range(self.model.nbSegment()): seg = self.model.segment(i) for r in seg.QRanges(): ranges.append([r.min(), r.max()]) for i in range(self.model.nbQ()): slider_layout = QHBoxLayout() sliders_layout.addLayout(slider_layout) # Add a name name_label = QLabel() name = f"{self.model.nameDof()[i].to_string()}" name_label.setText(name) name_label.setPalette(self.palette_active) label_width = name_label.fontMetrics().boundingRect( name_label.text()).width() if label_width > max_label_width: max_label_width = label_width slider_layout.addWidget(name_label) # Add the slider slider = QSlider(Qt.Horizontal) slider.setMinimumSize(100, 0) slider.setMinimum(ranges[i][0] * self.double_factor) slider.setMaximum(ranges[i][1] * self.double_factor) slider.setPageStep(self.double_factor) slider.setValue(0) slider.valueChanged.connect(self.__move_avatar_from_sliders) slider.sliderReleased.connect( partial(self.__update_muscle_analyses_graphs, False, False, False, False)) slider_layout.addWidget(slider) # Add the value value_label = QLabel() value_label.setText(f"{0:.2f}") value_label.setPalette(self.palette_active) slider_layout.addWidget(value_label) # Add to the main sliders self.sliders.append((name_label, slider, value_label)) # Adjust the size of the names for name_label, _, _ in self.sliders: name_label.setFixedWidth(max_label_width + 1) # Put the sliders in a scrollable area sliders_widget = QWidget() sliders_widget.setLayout(sliders_layout) sliders_scroll = QScrollArea() sliders_scroll.setFrameShape(0) sliders_scroll.setWidgetResizable(True) sliders_scroll.setWidget(sliders_widget) options_layout.addWidget(sliders_scroll) # Add reset button button_layout = QHBoxLayout() options_layout.addLayout(button_layout) reset_push_button = QPushButton("Reset") reset_push_button.setPalette(self.palette_active) reset_push_button.released.connect(self.reset_q) button_layout.addWidget(reset_push_button) copyq_push_button = QPushButton("Copy Q to clipboard") copyq_push_button.setPalette(self.palette_active) copyq_push_button.released.connect(self.copy_q_to_clipboard) button_layout.addWidget(copyq_push_button) # Add the radio button for analyses option_analyses_group = QGroupBox() option_analyses_layout = QVBoxLayout() # Add text analyse_text = QLabel() analyse_text.setPalette(self.palette_active) analyse_text.setText("Analyses") option_analyses_layout.addWidget(analyse_text) # Add the no analyses radio_none = QRadioButton() radio_none.setPalette(self.palette_active) radio_none.setChecked(True) radio_none.toggled.connect( lambda: self.__select_analyses_panel(radio_none, 0)) radio_none.setText("None") option_analyses_layout.addWidget(radio_none) # Add the muscles analyses radio_muscle = QRadioButton() radio_muscle.setPalette(self.palette_active) radio_muscle.toggled.connect( lambda: self.__select_analyses_panel(radio_muscle, 1)) radio_muscle.setText("Muscles") option_analyses_layout.addWidget(radio_muscle) # Add the layout to the interface option_analyses_group.setLayout(option_analyses_layout) options_layout.addWidget(option_analyses_group) # Finalize the options panel options_layout.addStretch() # Centralize the sliders # Animation panel animation_layout = QVBoxLayout() animation_layout.addWidget(self.vtk_window.avatar_widget) # Add the animation slider animation_slider_layout = QHBoxLayout() animation_layout.addLayout(animation_slider_layout) load_push_button = QPushButton("Load movement") load_push_button.setPalette(self.palette_active) load_push_button.released.connect(self.__load_movement_from_button) animation_slider_layout.addWidget(load_push_button) # Controllers self.play_stop_push_button = QPushButton() self.play_stop_push_button.setIcon(self.start_icon) self.play_stop_push_button.setPalette(self.palette_active) self.play_stop_push_button.setEnabled(False) self.play_stop_push_button.released.connect( self.__start_stop_animation) animation_slider_layout.addWidget(self.play_stop_push_button) slider = QSlider(Qt.Horizontal) slider.setMinimum(0) slider.setMaximum(100) slider.setValue(0) slider.setEnabled(False) slider.valueChanged.connect(self.__animate_from_slider) animation_slider_layout.addWidget(slider) self.record_push_button = QPushButton() self.record_push_button.setIcon(self.record_icon) self.record_push_button.setPalette(self.palette_active) self.record_push_button.setEnabled(True) self.record_push_button.released.connect(self.__record) animation_slider_layout.addWidget(self.record_push_button) self.stop_record_push_button = QPushButton() self.stop_record_push_button.setIcon(self.stop_icon) self.stop_record_push_button.setPalette(self.palette_active) self.stop_record_push_button.setEnabled(False) self.stop_record_push_button.released.connect(self.__stop_record, True) animation_slider_layout.addWidget(self.stop_record_push_button) # Add the frame count frame_label = QLabel() frame_label.setText(f"{0}") frame_label.setPalette(self.palette_inactive) animation_slider_layout.addWidget(frame_label) self.movement_slider = (slider, frame_label) # Global placement of the window self.vtk_window.main_layout.addLayout(options_layout, 0, 0) self.vtk_window.main_layout.addLayout(animation_layout, 0, 1) self.vtk_window.main_layout.setColumnStretch(0, 1) self.vtk_window.main_layout.setColumnStretch(1, 2) # Change the size of the window to account for the new sliders self.vtk_window.resize(self.vtk_window.size().width() * 2, self.vtk_window.size().height()) # Prepare all the analyses panel self.muscle_analyses = MuscleAnalyses(self.analyses_muscle_widget, self) if biorbd.currentLinearAlgebraBackend() == 1: radio_muscle.setEnabled(False) else: if self.model.nbMuscles() == 0: radio_muscle.setEnabled(False) self.__select_analyses_panel(radio_muscle, 1)
def _create_recorder_gui(self, export_callback): window = QMainWindow() window.setWindowFlag(Qt.WindowStaysOnTopHint, True) window.setWindowTitle("Video Export Tool") main_widget = QWidget() main_layout = QVBoxLayout() main_widget.setLayout(main_layout) round_slider_box = QHBoxLayout() slider = QSlider(Qt.Horizontal) slider.setTickInterval(1) slider.setTickPosition(1) slider.setMaximum(len(self.records) - 1) slider.setMinimum(0) slider.setSliderPosition(0) text = QLabel("rounds: 1/%d" % len(self.records)) def onchange(value): self._viewer.inject_record_data(self.records[value]) self._viewer.glDraw() text.setText("rounds: %d/%d" % (value + 1, len(self.records))) # noinspection PyUnresolvedReferences slider.valueChanged.connect(onchange) round_slider_box.addWidget(text) round_slider_box.addWidget(slider) fps_edit = QLineEdit() fps_edit.setText(str(self._world.vis.get_rounds_per_second())) fpsbox = QHBoxLayout() fpsbox.addWidget(QLabel("rounds per second:")) fpsbox.addWidget(fps_edit) width, height = self._world.vis.get_viewer_res() width_edit = QLineEdit() width_edit.setText(str(width)) height_edit = QLineEdit() height_edit.setText(str(height)) resbox = QHBoxLayout() resbox.addWidget(QLabel("resolution:")) resbox.addWidget(width_edit) resbox.addWidget(QLabel("x")) resbox.addWidget(height_edit) start_frame = QLineEdit("1") end_frame = QLineEdit(str(len(self.records))) frames_box = QHBoxLayout() frames_box.addWidget(QLabel("first frame:")) frames_box.addWidget(start_frame) frames_box.addWidget(QLabel("last frame:")) frames_box.addWidget(end_frame) codec_combo = QComboBox() codec_combo.addItem("mp4v", 'mp4v') codec_combo.addItem("X264", 'X264') codec_combo.addItem("MJPG", 'MJPG') codec_combo.addItem("DIVX", 'DIVX') codec_combo.addItem("XVID", 'XVID') codec_box = QHBoxLayout() codec_box.addWidget(QLabel("codec:")) codec_box.addWidget(codec_combo) anim_checkbox = QCheckBox("export with animation") anim_checkbox.setChecked(self._world.vis.get_animation()) export_button = QPushButton("export video") def export_call(): try: input_rps = float(fps_edit.text()) if input_rps <= 0: show_msg("Rounds per second has to be greater than 0!", Level.WARNING, window) return except ValueError: show_msg("Rounds per second has to be a number!", Level.WARNING, window) return try: input_width = int(width_edit.text()) if input_width <= 0: show_msg("Width has to be greater than 0!", Level.WARNING, window) return except ValueError: show_msg("Width has to be an integer!", Level.WARNING, window) return try: input_height = int(height_edit.text()) if input_height <= 0: show_msg("Height has to be greater than 0!", Level.WARNING, window) return except ValueError: show_msg("Height has to be an integer!", Level.WARNING, window) return try: ff = int(start_frame.text()) ef = int(end_frame.text()) if ff < 1 or ef < 1: show_msg("frame index cannot be lower than 1", Level.WARNING, window) return if ff > len(self.records) or ef > len(self.records): show_msg( "frame index cannot be higher than the index of last frame (%d)" % len(self.records), Level.WARNING, window) return if ff > ef: show_msg( "index of first frame cannot be higher than index of last frame", Level.WARNING, window) return except ValueError: show_msg("frame index has to be an integer!", Level.WARNING, window) return window.setDisabled(True) export_callback(input_rps, input_width, input_height, codec_combo.itemData(codec_combo.currentIndex()), ff, ef, anim_checkbox.isChecked()) window.setDisabled(False) # noinspection PyUnresolvedReferences export_button.clicked.connect(export_call) main_layout.addLayout(round_slider_box) main_layout.addLayout(frames_box) main_layout.addLayout(fpsbox) main_layout.addLayout(resbox) main_layout.addLayout(codec_box) main_layout.addWidget(anim_checkbox) main_layout.addWidget(export_button) window.setCentralWidget(main_widget) return window
def __init__(self, folder=None, title='', logo=None, parent=None): super(BaseWindow, self).__init__(parent) self.resize(900, 600) self.setWindowTitle(title) ssDir = os.path.join(here, "..", "_tools", "") if logo: self.setWindowIcon(QIcon(logo)) else: self.setWindowIcon(QIcon(os.path.join(ssDir, 'toto.ico'))) sshFile = os.path.join(ssDir, 'TCobra.qss') with open(sshFile, "r") as fh: self.setStyleSheet(fh.read()) self.opt = [] # Main window layout = QHBoxLayout() font = QFont() font.setFamily("Rod") font.setPointSize(23) # left pannel Left = QVBoxLayout() #Plotting Methods from Matplotlib with plt.style.context("cyberpunk"): self.figure = plt.figure() self.canvas = FigureCanvas(self.figure) self.canvas.setMaximumHeight(525) self.canvas.setMaximumHeight(725) self.toolbar = NavigationToolbar(self.canvas, self) #Labels self.label = QLabel(self) self.label.setFont(font) self.label.setText(" %s" % title) self.label.setMaximumSize(625, 30) Left.addWidget(self.label) Left.addWidget(self.canvas) Left.addWidget(self.toolbar) # Right pannel Right = QVBoxLayout() label2 = QLabel(self) label2.setFont(font) label2.setText("Select Method:") Right.addWidget(label2) # Initisialize the methods self.method_names = QListWidget() self.method_names.currentRowChanged.connect(self.display) self.method_options = QStackedWidget() methods = self.init_folder(folder) for method in methods.keys(): item = QListWidgetItem(method) self.method_names.addItem(item) self.method_options.addWidget(methods[method]) Right.addWidget(self.method_names) #Right.addWidget(self.method_options) ## Slider scroll = QScrollArea() scroll.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOn) scroll.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOn) scroll.setWidgetResizable(True) scroll.setWidget(self.method_options) Right.addWidget(scroll) ## button bttn_box = QHBoxLayout() goPlot = QPushButton('Try') goPlot.setMaximumSize(60, 20) goPlot.clicked.connect(self.filter) resetPlot = QPushButton('Reset') resetPlot.setMaximumSize(60, 20) resetPlot.clicked.connect(self.reset) savePlot = QPushButton('Save') savePlot.setMaximumSize(60, 20) savePlot.clicked.connect(self.save) cancelPlot = QPushButton('Cancel') cancelPlot.setMaximumSize(60, 20) cancelPlot.clicked.connect(self.cancel) bttn_box.addWidget(goPlot) bttn_box.addWidget(resetPlot) bttn_box.addWidget(savePlot) bttn_box.addWidget(cancelPlot) # Vertically aligns the filte method Right.addLayout(bttn_box) layout.addLayout(Left) layout.addLayout(Right) self.setLayout(layout)
class StartFrame(QWidget, Logger): name = "StartFrame" def __init__(self, parent, param): super().__init__(parent=parent) self.layout = QVBoxLayout() self.buttons = dict() self.param = param self.game_frame = GameParameters(param=self.param["parametrization"]) self.network_frame = NetworkParameters(param=self.param["network"]) self.group_game = QGroupBox("Game parametrization") self.group_network = QGroupBox("Network parameters") self.setup() def setup(self): self.buttons["new"] = QPushButton("New game") self.fill_frames() self.fill_layout() self.buttons["new"].clicked.connect(self.push_new_game) def fill_frames(self): self.group_game.setLayout(self.game_frame.layout) self.group_network.setLayout(self.network_frame.layout) def fill_layout(self): self.layout.addWidget(self.group_network) self.layout.addWidget(self.group_game) horizontal_layout = QHBoxLayout() horizontal_layout.addWidget(self.buttons["new"], alignment=Qt.AlignCenter) self.layout.addLayout(horizontal_layout) self.setLayout(self.layout) def prepare(self): self.setFocus() self.buttons["new"].setFocus() self.set_buttons_activation(True) def push_new_game(self): self.log("Push 'new game' button.") # save interface parameters self.save_network_parameters() self.save_parametrization() # do stuff... self.erase_sql_tables() self.set_missing_players() self.set_buttons_activation(False) self.parent().show_frame_assignment_php() def set_buttons_activation(self, value): for b in self.buttons.values(): b.setEnabled(value) def save_network_parameters(self): self.param["network"] = self.network_frame.get_widgets_values() self.parent().save_parameters("network", self.param["network"]) self.parent().set_server_parameters(self.param) def save_parametrization(self): self.param["parametrization"] = self.game_frame.get_widgets_values() self.parent().save_parameters("parametrization", self.param["parametrization"]) self.parent().set_parametrization(self.param["parametrization"]) def set_missing_players(self): self.parent().set_missing_players( self.param["network"]["missing_players"]) def erase_sql_tables(self): self.parent().check_for_erasing_tables()
def render_widget(self): height = 200 layout = QVBoxLayout(self) layout.setObjectName('body') layout.setAlignment(Qt.AlignTop) header = QHBoxLayout() # Image imageWid = Picture(self.image.value, 240, 160) image_path = config.market.market_url + '/product/v1/allproducts/images/?path=' + self.image.value imageWid = ProductQML(self, image=image_path, img_width=240, img_height=160) imageWid.obj.signals.click.connect( lambda: app.event.emit(app.events.DETAIL_UPDATE)) header.addWidget(imageWid) right = QVBoxLayout() right.setAlignment(Qt.AlignTop) right.setSpacing(15) # Title title = Label(self.name) title.setObjectName('name') right.addWidget(title) # category catbox = QHBoxLayout() catbox.setSpacing(5) type_text = 'Batch' if self.ptype == 'file' else 'Streaming' icon = self.icon.value if icon: iconL = QLabel() iconL.setObjectName('icon') iconL.setPixmap(QPixmap(icon)) catbox.addWidget(iconL) type_wid = Builder().text(type_text).name('type_text').style( "color: #444;font-size:14").build() catbox.addWidget(type_wid) catbox.addSpacing(10) category = Label(self.category) category.setObjectName('category') category.setAlignment(Qt.AlignCenter) category.setMaximumWidth(80) catbox.addWidget(category) catbox.addStretch(1) right.addLayout(catbox) # Timestamp and Remain Days tbox = QHBoxLayout() timestamp = QLabel(self.created.value) timestamp.setObjectName('timestamp') tbox.addWidget(timestamp) sales = QLabel(str(self.sales.value) + ' sales') sales.setObjectName('sales') tbox.addWidget(sales) tbox.addStretch(1) right.addLayout(tbox) # CPC and Sales hbox = QHBoxLayout() hbox.setObjectName('hbox1') cpc = QLabel(str(self.cpc.value)) cpc.setObjectName('cpc') cpc_unit = QLabel('CPC') cpc_unit.setObjectName('cpc_unit') hbox.addWidget(cpc) hbox.addWidget(cpc_unit) # Buy button def openPurchaseDialog(_): self.buying(True) if not self.paying: market_hash = self.market_hash owner_address = self.owner_address purchaseDlg = PurchaseDialog(self, price=self.cpc, gas=self.gas, account=self.account, storagePath=self.storagePath, password=self.password, market_hash=market_hash, name=self.name.value, owner_address=owner_address) purchaseDlg.show() self.buy = Button.Builder(width=100, height=30).text('Buy')\ .style('primary')\ .click(openPurchaseDialog)\ .build() hbox.addWidget(self.buy) if self.owner_address == wallet.market_client.public_key: self.buy.setEnabled(False) # Buy Loading self.buy_loading = Loading() hbox.addWidget(self.buy_loading) self.buy_loading.hide() hbox.addStretch(1) right.addLayout(hbox) header.addLayout(right) layout.addLayout(header) # Description desc = DetailHeader('Description') layout.addWidget(desc) desc = Label(self.description) desc.setWordWrap(True) layout.addWidget(desc) height += 300 layout.addStretch(1) widget_ = QWidget() widget_.setObjectName('parent_widget') widget_.setLayout(layout) widget_.setFixedWidth(720) widget_.setFixedHeight(height) widget_.setStyleSheet(self.style()) self.add_orders_ui(widget_) return widget_
class SetupSymbole(QWidget): def __init__(self, m): QWidget.__init__(self) self.MW = m self.chiffreTemp = "" self.gameVar = GameVar() self.lineEdit = QLineEdit("") font = self.lineEdit.font() # lineedit current font font.setPointSize(30) # change it's size self.lineEdit.setFont(font) self.lineEdit.setAlignment(QtCore.Qt.AlignCenter) self.lineEdit.setFixedHeight(100) self.lineEdit.setFixedWidth(400) self.btnsSymbole = [] self.boxsSymbole = [] for i in range(4): box = QHBoxLayout() for j in range(3): btn = QPushButton("") f = btn.font() f.setPointSize(20) btn.setFont(f) btn.setMaximumHeight(400) btn.setFixedHeight(100) self.btnsSymbole.append(btn) box.addWidget(btn) self.boxsSymbole.append(box) self.linehboxSymbole = QHBoxLayout() self.linehboxSymbole.addWidget(self.lineEdit) self.vboxSymbole = QVBoxLayout() self.vboxSymbole.addLayout(self.linehboxSymbole) for box in self.boxsSymbole: self.vboxSymbole.addLayout(box) self.setGeometry(0, 0, 416, 720) self.setLayout(self.vboxSymbole) def resetBtn(self): for btn in self.btnsSymbole: btn.setText("") btn.clicked.connect(self.mRien) btn.clicked.disconnect() self.repaint() @pyqtSlot() def mRien(self): pass @pyqtSlot() def mSetSymbole(self): self.resetBtn() self.chiffreTemp = "" self.lineEdit.setText(self.chiffreTemp) print(self.MW.setup.lastSymClicked) for i in range(0, 9): self.btnsSymbole[i].setText(str(i + 1)) self.btnsSymbole[i].value = i + 1 self.btnsSymbole[i].clicked.connect(self.chiffre) self.btnsSymbole[i + 1].setText("0") self.btnsSymbole[i + 1].value = 0 self.btnsSymbole[i + 1].clicked.connect(self.chiffre) self.btnsSymbole[i + 2].setText("<-") self.btnsSymbole[i + 2].value = -1 self.btnsSymbole[i + 2].clicked.connect(self.chiffre) self.btnsSymbole[i + 3].setText("Valider") self.btnsSymbole[i + 3].value = -2 self.btnsSymbole[i + 3].clicked.connect(self.chiffre) @pyqtSlot() def chiffre(self): btnClicked = self.sender() try: if btnClicked.value == -2: # OK print("clic") if self.chiffreTemp != "": for col in self.gameVar.symboleColonnes: if int(self.chiffreTemp) in col or int( self.chiffreTemp ) == 0: # Ajout si Numéro symbole existant self.gameVar.symboleInstalle[ self.MW.setup.lastSymClicked] = int( self.chiffreTemp) print("break") break self.chiffreTemp = "" self.mRetourSetupSymbole() return elif btnClicked.value == -1: # effacer self.chiffreTemp = self.chiffreTemp[:-1] else: self.chiffreTemp += str(btnClicked.value) except: pass self.lineEdit.setText(self.chiffreTemp) @pyqtSlot() def mRetourSetupSymbole(self): self.resetBtn() self.MW.stackSetup.setCurrentIndex(0) self.MW.setup.mSymbole() # retour au setup avec 2 colonnes @pyqtSlot() def mRetourSetupPrincipal(self): self.resetBtn() self.MW.stackSetup.setCurrentIndex(0) self.MW.setup.mPrincipal()
class App(QWidget): FROM, TO, DATE, SUBJECT, MESSAGE = range(5) def __init__(self, mails_lst=[], my_mail="", send=None, receive=None, labels=None): super().__init__() # self.setAttribute(QtCore.Qt.WA_DeleteOnClose) self.sendClass = send self.receiveClass = receive self.labelsClass = labels self.mails_lst = mails_lst self.mails = mails_lst[1] self.my_mail = my_mail self.labels = ["All", "Inbox", "Sent", "Trash"] self.title = 'SMTP Email Client' self.left = 0 self.top = 0 self.width = 1024 self.height = 600 self.total_cols = 5 self.ret_val = False self.is_first_ret_val = True self.is_reload_mails = False self.messages_file = 'messages.data' self.initUI() def toolbarButtonClick(self, i): def buttonClick(): if self.send_button.isChecked(): self.send_button.setChecked(False) self.sendMenuToggleClick(False) # for l in self.label_buttons: # print(l.isChecked()) if self.label_buttons[i].isChecked(): # if self.is_reload_mails: # self.reloadMails() # print("mails reloaded") # self.is_reload_mails = False print(f"displaying label category '{self.labels[i]}'") for index, label_button in enumerate(self.label_buttons): if index != i: label_button.setChecked(False) self.mails = self.mails_lst[i] self.reloadMails() else: self.label_buttons[i].setChecked(True) return buttonClick def parallelReloading(self): temp_mails_lst = [] for label in self.labelsClass: temp_mails_lst.append( self.receiveClass.get_message(category=label)) index = [label.isChecked() for label in self.label_buttons].index(True) self.mails_lst = temp_mails_lst self.mails = temp_mails_lst[index] write_to_file(self.messages_file, self.mails_lst) self.is_reload_mails = True def parallelSending(self, to_addr, subj, msg): self.sendClass.send_message(to_addr, subj, msg) def reloadButtonClick(self, s): if self.receiveClass: if self.is_first_ret_val: print("reloading all mails") self.ret_val = threading.Thread(target=self.parallelReloading, args=()) self.ret_val.start() self.is_first_ret_val = False elif not self.ret_val.isAlive(): print("reloading all mails") self.ret_val = threading.Thread(target=self.parallelReloading, args=()) self.ret_val.start() else: print("reloading already taking place in background") else: print("unable to reload as 'receiveClass' missing") self.reload_button.setChecked(False) def sendMenuToggleClick(self, s): if s: self.toBox.setFixedWidth(self.contentView.width()) self.contentView.hide() self.toBox.show() self.subjectBox.show() self.messageBox.show() self.sendButtonBox.show() else: self.toBox.hide() self.subjectBox.hide() self.messageBox.hide() self.sendButtonBox.hide() self.contentView.show() def logoutButtonClick(self, s): print("loging out and closing app") sys.exit() def rowSelectionClick(self): if self.send_button.isChecked(): self.send_button.setChecked(False) self.sendMenuToggleClick(False) self.dataView.showColumn(1) self.dataView.showColumn(4) item = self.dataView.selectedIndexes() lst = [] for i in range(self.total_cols): text = item[i].model().itemFromIndex(item[i]).text() if i == 0 or i == 1: text = text.split() lst.append(text) self.dataView.hideColumn(1) self.dataView.hideColumn(4) msg = self.htmlString(lst) self.contentView.setPlainText("") self.contentView.textCursor().insertHtml(msg) def sendButtonClick(self): if self.sendClass: self.reloadButtonClick(True) # to_addr = re.split(r'[, ]', self.toBox.text()) to_addr = re.findall(r'[\w\.-]+@[\w\.-]+', self.toBox.text()) subj = self.subjectBox.text() msg = self.messageBox.toPlainText() send_ret_val = threading.Thread(target=self.parallelSending, args=(to_addr, subj, msg)) send_ret_val.start() else: print("unable to send as 'sendClass' missing") self.toBox.setText("") self.subjectBox.setText("") self.messageBox.setPlainText("") self.sendMenuToggleClick(False) self.send_button.setChecked(False) def initUI(self): # windows title and geometry set self.setWindowTitle(self.title) self.setGeometry(self.left, self.top, self.width, self.height) self.globalLayout = QVBoxLayout() menuLayout = QHBoxLayout() dataLayout = QHBoxLayout() labelLayout = QToolBar("Labels") self.label_buttons = [QAction(label, self) for label in self.labels] # button_action.setStatusTip("This is your button") for i, label_button in enumerate(self.label_buttons): label_button.triggered.connect(self.toolbarButtonClick(i)) labelLayout.addAction(label_button) label_button.setCheckable(True) # labelLayout.addAction(label_button) self.label_buttons[1].setChecked(True) optionLayout = QToolBar("Options") self.send_button = QAction(QIcon("images/icons8-email-60.png"), "Send Mail", self) self.reload_button = QAction(QIcon("images/icons8-reset-60.png"), "Reload Page", self) logout_button = QAction(QIcon("images/icons8-shutdown-60.png"), "Logout", self) self.send_button.triggered.connect(self.sendMenuToggleClick) self.reload_button.triggered.connect(self.reloadButtonClick) logout_button.triggered.connect(self.logoutButtonClick) optionLayout.addAction(self.send_button) optionLayout.addAction(self.reload_button) optionLayout.addAction(logout_button) self.send_button.setCheckable(True) self.reload_button.setCheckable(True) logout_button.setCheckable(True) # w1.setContentsMargins(0, 0, 0, 0) # w2.setContentsMargins(0, 0, 0, 0) # menuLayout.setSpacing(0) menuLayout.setContentsMargins(0, 0, 0, 0) optionLayout.setFixedWidth(106) menuLayout.addWidget(labelLayout, 10) menuLayout.addWidget(QLabel(self.my_mail), 1) menuLayout.addWidget(optionLayout) # dataview with non editable columns (from, date, subject etc) self.dataView = QTreeView() self.dataView.setRootIsDecorated(False) self.dataView.setAlternatingRowColors(True) self.dataView.setEditTriggers(QAbstractItemView.NoEditTriggers) # content view to display complete email message self.contentView = QPlainTextEdit() self.contentView.setReadOnly(True) self.sendLayout = QVBoxLayout() self.toBox = QLineEdit() self.subjectBox = QLineEdit() self.messageBox = QPlainTextEdit() self.sendButtonBox = QPushButton("Send") self.toBox.setPlaceholderText("To") self.subjectBox.setPlaceholderText("Subject") self.messageBox.setPlaceholderText("Message") self.sendLayout.addWidget(self.toBox) self.sendLayout.addWidget(self.subjectBox) self.sendLayout.addWidget(self.messageBox) self.sendLayout.addWidget(self.sendButtonBox) self.sendLayout.setSpacing(0) self.sendLayout.setContentsMargins(0, 0, 0, 0) # set layout of columns and content box horizontally dataLayout.addWidget(self.dataView, 3) dataLayout.addWidget(self.contentView, 2) dataLayout.addLayout(self.sendLayout) self.contentView.show() self.toBox.hide() self.subjectBox.hide() self.messageBox.hide() self.sendButtonBox.hide() self.sendButtonBox.clicked.connect(self.sendButtonClick) # create mail model to add to data view self.model = self.createMailModel(self) self.dataView.setModel(self.model) self.dataView.clicked.connect(self.rowSelectionClick) self.globalLayout.addLayout(menuLayout, 1) self.globalLayout.addLayout(dataLayout, 20) self.setLayout(self.globalLayout) self.addAllMails() self.autoColumnWidths() self.show() self.reloadButtonClick(True) def reloadMails(self): # self.mails = mails self.model.removeRows(0, self.model.rowCount()) self.addAllMails() self.autoColumnWidths() # set headers text for the created model def createMailModel(self, parent): model = QStandardItemModel(0, self.total_cols, parent) model.setHeaderData(self.FROM, Qt.Horizontal, "From") model.setHeaderData(self.TO, Qt.Horizontal, "To") model.setHeaderData(self.DATE, Qt.Horizontal, "Date") model.setHeaderData(self.SUBJECT, Qt.Horizontal, "Subject") model.setHeaderData(self.MESSAGE, Qt.Horizontal, "Message") return model # add content of mail to data view def addAllMails(self): today = date.today() today_date = today.strftime('%a, %d %b %Y') for mail in self.mails: if today_date == mail[2]: date_temp = mail[3] else: date_temp = mail[2] self.addMail(self.model, mail[0], mail[1], date_temp, mail[4], mail[5]) if self.mails: # msg = self.htmlString( # [self.mails[-1][0], self.mails[-1][1], self.mails[-1][4], self.mails[-1][5]]) msg = self.htmlString(self.mails[-1]) self.contentView.setPlainText("") self.contentView.textCursor().insertHtml(msg) def addMail(self, model, mailFrom, mailTo, date, subject, message): model.insertRow(0) mailFrom = ' '.join(map(str, mailFrom)) mailTo = ' '.join(map(str, mailTo)) model.setData(model.index(0, self.FROM), mailFrom) model.setData(model.index(0, self.TO), mailTo) model.setData(model.index(0, self.DATE), date) model.setData(model.index(0, self.SUBJECT), subject) model.setData(model.index(0, self.MESSAGE), message) def autoColumnWidths(self): width_plus = 30 self.dataView.setColumnWidth(1, 0) self.dataView.setColumnWidth(4, 0) for i in range(self.total_cols): self.dataView.resizeColumnToContents(i) width = self.dataView.columnWidth(i) self.dataView.setColumnWidth(i, width + width_plus) self.dataView.hideColumn(1) self.dataView.hideColumn(4) def htmlString(self, lst): fr_addr = "<b>From</b><br>" for l in lst[0]: fr_addr += f"{l}<br>" fr_addr += "<br>" to_addr = "<b>To</b><br>" for l in lst[1]: to_addr += f"{l}<br>" to_addr += "<br>" subject = f"<b>Subject</b><br>{lst[-2]}<br><br>" message = lst[-1].replace("\n", "<br>") message = f"<b>Message</b><br>{message}<br><br>" return fr_addr + to_addr + subject + message
def initUI(self): backButton = QPushButton('') backButton.setIcon(QIcon('image/back_2.png')) backButton.setIconSize(QSize(75, 75)) backButton.clicked.connect(self.back) db = SqliteDatabase('mydb.db') db.connect() j = 0 g = 0 h_city = QHBoxLayout() v_city = QVBoxLayout() v_city.setSpacing(10) for i in City.select().where(City.name == self.city_name): if j == 3: v_city.addLayout(h_city) h_city = QHBoxLayout() count = Institution.select().where(Institution.owner == i.name) city = ListCity(i.name, len(count), self.expansion) city.setObjectName(i.name) #city.clicked.connect(self.get_button_name) #city.clicked.connect(self.next) #city.clicked.connect(self.objectName()) city.move(-300, -300) v_city.addLayout(h_city) j = 0 else: count = Institution.select().where(Institution.owner == i.name) city = ListCity(i.name, len(count), self.expansion) city.setObjectName(i.name) print(city.objectName()) #city.clicked.connect(self.get_button_name) #city.clicked.connect(self.next) city.move(-300, -300) h_city.addWidget(city) j += 1 g += 1 if g < 4: v_city.addLayout(h_city) db.close() self.scroll = QScrollArea() self.scroll.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOn) self.scroll.setWidgetResizable(True) self.scroll.setStyleSheet( "border: 1px solid transparent; background-color: transparent;") #tt = MainWindow() gg = QWidget() gg.setLayout(v_city) self.scroll.setWidget(gg) self.title = QLabel("Результаты поиска") tit_h = QHBoxLayout() tit_h.addWidget(self.title, 20) tit_h.addWidget(backButton, 1) vv = QVBoxLayout() vv.addLayout(tit_h) vv.addWidget(self.scroll) self.title.setStyleSheet( "background-color: rgba(255, 255, 255, 0.5); color: black;" "border: 3px solid transparent;" "padding: 10px 0px 10px 0px;" "margin-top: 0px;" "font-size: 30px; font-family: Verdana;") backButton.setStyleSheet( "background-color: rgba(255, 255, 255, 0.1); padding: 12px;") self.setLayout(vv) p = QPalette() gradient = QLinearGradient(0, 0, 120, 400) gradient.setColorAt(0.0, QColor(117, 160, 252)) gradient.setColorAt(1.0, QColor(193, 203, 253)) p.setBrush(QPalette.Window, QBrush(gradient)) self.setPalette(p) if self.expansion == '1': self.showFullScreen() else: self.setGeometry(0, 30, 800, 600) self.setFixedSize(800, 600) self.setWindowTitle('Menubar') self.show()
class UploadWindowUI(object): title = "DERIVA File Uploader" def __init__(self, MainWin): # Main Window MainWin.setObjectName("UploadWindow") MainWin.setWindowTitle(MainWin.tr(self.title)) MainWin.resize(1024, 768) self.centralWidget = QWidget(MainWin) self.centralWidget.setObjectName("centralWidget") MainWin.setCentralWidget(self.centralWidget) self.verticalLayout = QVBoxLayout(self.centralWidget) self.verticalLayout.setContentsMargins(11, 11, 11, 11) self.verticalLayout.setSpacing(6) self.verticalLayout.setObjectName("verticalLayout") self.horizontalLayout = QHBoxLayout() self.pathLabel = QLabel("Directory:") self.horizontalLayout.addWidget(self.pathLabel) self.pathTextBox = QLineEdit() self.pathTextBox.setReadOnly(True) self.horizontalLayout.addWidget(self.pathTextBox) self.browseButton = QPushButton("Browse", self.centralWidget) self.browseButton.clicked.connect(MainWin.on_actionBrowse_triggered) self.horizontalLayout.addWidget(self.browseButton) self.verticalLayout.addLayout(self.horizontalLayout) # Splitter for Upload list/Log self.splitter = QSplitter(Qt.Vertical) # Table View (Upload list) self.uploadList = TableWidget(self.centralWidget) self.uploadList.setObjectName("uploadList") self.uploadList.setStyleSheet( """ QTableWidget { border: 2px solid grey; border-radius: 5px; } """) self.uploadList.setEditTriggers(QAbstractItemView.NoEditTriggers) # use NoEditTriggers to disable editing self.uploadList.setAlternatingRowColors(True) self.uploadList.setSelectionBehavior(QAbstractItemView.SelectRows) self.uploadList.setSelectionMode(QAbstractItemView.NoSelection) self.uploadList.verticalHeader().setDefaultSectionSize(18) # tighten up the row size self.uploadList.horizontalHeader().setStretchLastSection(True) self.uploadList.setSortingEnabled(True) # allow sorting self.splitter.addWidget(self.uploadList) # Log Widget self.logTextBrowser = QPlainTextEditLogger(self.centralWidget) self.logTextBrowser.widget.setObjectName("logTextBrowser") self.logTextBrowser.widget.setStyleSheet( """ QPlainTextEdit { border: 2px solid grey; border-radius: 5px; background-color: lightgray; } """) self.splitter.addWidget(self.logTextBrowser.widget) # add splitter self.splitter.setSizes([400, 200]) self.verticalLayout.addWidget(self.splitter) # Actions # Browse self.actionBrowse = QAction(MainWin) self.actionBrowse.setObjectName("actionBrowse") self.actionBrowse.setText(MainWin.tr("Browse")) self.actionBrowse.setToolTip(MainWin.tr("Set the upload directory")) self.actionBrowse.setShortcut(MainWin.tr("Ctrl+B")) # Upload self.actionUpload = QAction(MainWin) self.actionUpload.setObjectName("actionUpload") self.actionUpload.setText(MainWin.tr("Upload")) self.actionUpload.setToolTip(MainWin.tr("Upload files")) self.actionUpload.setShortcut(MainWin.tr("Ctrl+L")) self.actionUpload.setEnabled(False) # Rescan self.actionRescan = QAction(MainWin) self.actionRescan.setObjectName("actionRescan") self.actionRescan.setText(MainWin.tr("Rescan")) self.actionRescan.setToolTip(MainWin.tr("Rescan the upload directory")) self.actionRescan.setShortcut(MainWin.tr("Ctrl+R")) self.actionRescan.setEnabled(False) # Cancel self.actionCancel = QAction(MainWin) self.actionCancel.setObjectName("actionCancel") self.actionCancel.setText(MainWin.tr("Cancel")) self.actionCancel.setToolTip(MainWin.tr("Cancel any upload(s) in-progress")) self.actionCancel.setShortcut(MainWin.tr("Ctrl+C")) # Options self.actionOptions = QAction(MainWin) self.actionOptions.setObjectName("actionOptions") self.actionOptions.setText(MainWin.tr("Options")) self.actionOptions.setToolTip(MainWin.tr("Configuration Options")) self.actionOptions.setShortcut(MainWin.tr("Ctrl+P")) # Login self.actionLogin = QAction(MainWin) self.actionLogin.setObjectName("actionLogin") self.actionLogin.setText(MainWin.tr("Login")) self.actionLogin.setToolTip(MainWin.tr("Login to the server")) self.actionLogin.setShortcut(MainWin.tr("Ctrl+G")) self.actionLogin.setEnabled(False) # Logout self.actionLogout = QAction(MainWin) self.actionLogout.setObjectName("actionLogout") self.actionLogout.setText(MainWin.tr("Logout")) self.actionLogout.setToolTip(MainWin.tr("Logout of the server")) self.actionLogout.setShortcut(MainWin.tr("Ctrl+O")) self.actionLogout.setEnabled(False) # Exit self.actionExit = QAction(MainWin) self.actionExit.setObjectName("actionExit") self.actionExit.setText(MainWin.tr("Exit")) self.actionExit.setToolTip(MainWin.tr("Exit the application")) self.actionExit.setShortcut(MainWin.tr("Ctrl+Z")) # Help self.actionHelp = QAction(MainWin) self.actionHelp.setObjectName("actionHelp") self.actionHelp.setText(MainWin.tr("Help")) self.actionHelp.setToolTip(MainWin.tr("Help")) self.actionHelp.setShortcut(MainWin.tr("Ctrl+H")) # Menu Bar """ self.menuBar = QMenuBar(MainWin) self.menuBar.setObjectName("menuBar") MainWin.setMenuBar(self.menuBar) self.menuBar.setStyleSheet( "QMenuBar{font-family: Arial;font-style: normal;font-size: 10pt;font-weight: bold;};") """ # Tool Bar self.mainToolBar = QToolBar(MainWin) self.mainToolBar.setObjectName("mainToolBar") self.mainToolBar.setToolButtonStyle(Qt.ToolButtonTextUnderIcon) self.mainToolBar.setContextMenuPolicy(Qt.PreventContextMenu) MainWin.addToolBar(Qt.TopToolBarArea, self.mainToolBar) # Upload self.mainToolBar.addAction(self.actionUpload) self.actionUpload.setIcon(qApp.style().standardIcon(QStyle.SP_FileDialogToParent)) # Rescan self.mainToolBar.addAction(self.actionRescan) self.actionRescan.setIcon(qApp.style().standardIcon(QStyle.SP_BrowserReload)) # Cancel self.mainToolBar.addAction(self.actionCancel) self.actionCancel.setIcon(qApp.style().standardIcon(QStyle.SP_BrowserStop)) self.actionCancel.setEnabled(False) # Options self.mainToolBar.addAction(self.actionOptions) self.actionOptions.setIcon(qApp.style().standardIcon(QStyle.SP_FileDialogDetailedView)) # this spacer right justifies everything that comes after it spacer = QWidget() spacer.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) self.mainToolBar.addWidget(spacer) # Login self.mainToolBar.addAction(self.actionLogin) self.actionLogin.setIcon(qApp.style().standardIcon(QStyle.SP_DialogApplyButton)) # Logout self.mainToolBar.addAction(self.actionLogout) self.actionLogout.setIcon(qApp.style().standardIcon(QStyle.SP_DialogOkButton)) # Help #self.mainToolBar.addAction(self.actionHelp) self.actionHelp.setIcon(qApp.style().standardIcon(QStyle.SP_MessageBoxQuestion)) # Exit self.mainToolBar.addAction(self.actionExit) self.actionExit.setIcon(qApp.style().standardIcon(QStyle.SP_DialogCancelButton)) # Status Bar self.statusBar = QStatusBar(MainWin) self.statusBar.setToolTip("") self.statusBar.setStatusTip("") self.statusBar.setObjectName("statusBar") MainWin.setStatusBar(self.statusBar) # configure logging self.logTextBrowser.widget.log_update_signal.connect(MainWin.updateLog) self.logTextBrowser.setFormatter(logging.Formatter("%(asctime)s - %(levelname)s - %(message)s")) logging.getLogger().addHandler(self.logTextBrowser) # finalize UI setup QMetaObject.connectSlotsByName(MainWin)
class SettingsTabWidget(QWidget): def __init__(self, parent=None): """ Class constructor :param parent: Widget """ super(SettingsTabWidget, self).__init__(parent=parent, flags=Qt.Widget) self.left_layout = QGridLayout() # Layout that will gather the left parameters self.right_layout = QGridLayout() # Layout that will gather the right parameters self.horizontal_layout = QHBoxLayout() # Layout that will gather the left and right grids self.vertical_layout = QVBoxLayout() # Layout that will gather all layouts in this tab self.preview_fft_layout = QHBoxLayout() # Layout that will gather the FFT previews self.preview_expected_layout = QHBoxLayout() # Layout that will gather the expected results previews self.left_group = GroupBox(self) # Separator for the left parameters self.right_group = GroupBox(self) # Separator for the right parameters # self.left_preview = GroupBox(self) # Separator for the left previews # self.right_preview = GroupBox(self) # Separator for the right previews self.preview_fft_left = PlotWidget(self) # Left FFT preview self.preview_fft_right = PlotWidget(self) # Right FFT preview self.preview_expected_left = PlotWidget(self) # Left expected result preview self.preview_expected_right = PlotWidget(self) # Right expected result preview self.enable_left = QCheckBox() # Checkbox that will enable/disable the left components self.enable_right = QCheckBox() # Checkbox that will enable/disable the right components # Labels for wave components on the left side self.left_components = [] for i in range(4): component = QLabel(str(i + 1)) component.setMaximumHeight(30) component.setMinimumWidth(50) component.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) component.setProperty("UseSeparator", True) component.setProperty("SettingsLabel", True) self.left_components.append(component) # Labels for wave components on the right side self.right_components = [] for i in range(4): component = QLabel(str(i + 1)) component.setMaximumHeight(30) component.setMinimumWidth(50) component.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) component.setProperty("UseSeparator", True) component.setProperty("SettingsLabel", True) self.right_components.append(component) # Initial buttons that will be used to change wave parameters # Left side self.left_buttons_frequency = [] self.left_buttons_modulation = [] self.left_buttons_am_deepness = [] self.left_buttons_fm_deepness = [] self.left_buttons_fm_phase = [] self.left_buttons_amplitude = [] for i in range(4): button = QPushButton(" + ", self) button.setMaximumHeight(40) button.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) button.setObjectName("Parameter") button.clicked.connect(self.on_click_frequency) self.left_buttons_frequency.append(button) button = QPushButton(" + ", self) button.setMaximumHeight(40) button.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) button.setObjectName("Parameter") button.clicked.connect(self.on_click_am_percentage) self.left_buttons_am_deepness.append(button) button = QPushButton(" + ", self) button.setMaximumHeight(40) button.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) button.setObjectName("Parameter") button.clicked.connect(self.on_click_modulation) self.left_buttons_modulation.append(button) button = QPushButton(" + ", self) button.setMaximumHeight(40) button.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) button.setObjectName("Parameter") button.clicked.connect(self.on_click_fm_percentage) self.left_buttons_fm_deepness.append(button) button = QPushButton(" + ", self) button.setMaximumHeight(40) button.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) button.setObjectName("Parameter") button.clicked.connect(self.on_click_fm_phase) self.left_buttons_fm_phase.append(button) button = QPushButton(" + ", self) button.setMaximumHeight(40) button.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) button.setObjectName("Parameter") button.clicked.connect(self.on_click_amplitude) self.left_buttons_amplitude.append(button) # Initial buttons that will be used to change wave parameters # Right side self.right_buttons_frequency = [] self.right_buttons_modulation = [] self.right_buttons_am_deepness = [] self.right_buttons_fm_deepness = [] self.right_buttons_fm_phase = [] self.right_buttons_amplitude = [] for i in range(4): button = QPushButton(" + ", self) button.setMaximumHeight(40) button.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) button.setObjectName("Parameter") button.clicked.connect(self.on_click_frequency) self.right_buttons_frequency.append(button) button = QPushButton(" + ", self) button.setMaximumHeight(40) button.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) button.setObjectName("Parameter") button.clicked.connect(self.on_click_am_percentage) self.right_buttons_am_deepness.append(button) button = QPushButton(" + ", self) button.setMaximumHeight(40) button.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) button.setObjectName("Parameter") button.clicked.connect(self.on_click_fm_percentage) self.right_buttons_fm_deepness.append(button) button = QPushButton(" + ", self) button.setMaximumHeight(40) button.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) button.setObjectName("Parameter") button.clicked.connect(self.on_click_modulation) self.right_buttons_modulation.append(button) button = QPushButton(" + ", self) button.setMaximumHeight(40) button.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) button.setObjectName("Parameter") button.clicked.connect(self.on_click_fm_phase) self.right_buttons_fm_phase.append(button) button = QPushButton(" + ", self) button.setMaximumHeight(40) button.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) button.setObjectName("Parameter") button.clicked.connect(self.on_click_amplitude) self.right_buttons_amplitude.append(button) # Right labels self.right_carrier_frequency_label = QLabel("Carrier Frequency: ") self.right_carrier_frequency_label.setProperty("UseSeparator", True) self.right_carrier_frequency_label.setProperty("SettingsLabel", True) self.right_modulation_label = QLabel("Modulation: ") self.right_modulation_label.setProperty("UseSeparator", True) self.right_modulation_label.setProperty("SettingsLabel", True) self.right_am_percentage_label = QLabel("AM Percentage: ") self.right_am_percentage_label.setProperty("UseSeparator", True) self.right_am_percentage_label.setProperty("SettingsLabel", True) self.right_fm_percentage_label = QLabel("FM Percentage: ") self.right_fm_percentage_label.setProperty("UseSeparator", True) self.right_fm_percentage_label.setProperty("SettingsLabel", True) self.right_fm_phase_label = QLabel("FM Phase: ") self.right_fm_phase_label.setProperty("UseSeparator", True) self.right_fm_phase_label.setProperty("SettingsLabel", True) self.right_amplitude_label = QLabel("Amplitude: ") self.right_amplitude_label.setProperty("UseSeparator", True) self.right_amplitude_label.setProperty("SettingsLabel", True) # Left labels self.left_carrier_frequency_label = QLabel("Carrier Frequency: ") self.left_carrier_frequency_label.setProperty("UseSeparator", True) self.left_carrier_frequency_label.setProperty("SettingsLabel", True) self.left_modulation_label = QLabel("Modulation: ") self.left_modulation_label.setProperty("UseSeparator", True) self.left_modulation_label.setProperty("SettingsLabel", True) self.left_am_percentage_label = QLabel("AM Percentage: ") self.left_am_percentage_label.setProperty("UseSeparator", True) self.left_am_percentage_label.setProperty("SettingsLabel", True) self.left_fm_percentage_label = QLabel("FM Percentage: ") self.left_fm_percentage_label.setProperty("UseSeparator", True) self.left_fm_percentage_label.setProperty("SettingsLabel", True) self.left_fm_phase_label = QLabel("FM Phase: ") self.left_fm_phase_label.setProperty("UseSeparator", True) self.left_fm_phase_label.setProperty("SettingsLabel", True) self.left_amplitude_label = QLabel("Amplitude: ") self.left_amplitude_label.setProperty("UseSeparator", True) self.left_amplitude_label.setProperty("SettingsLabel", True) self.init_ui() def init_ui(self) -> None: """ Initialize ui elements :return: None """ self.left_group.setLayout(self.left_layout) self.left_group.setTitle("Left Ear") self.left_group.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) self.right_group.setLayout(self.right_layout) self.right_group.setTitle("Right Ear") self.right_group.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) self.left_layout.setSpacing(0) # Set left layout spacing as zero self.enable_right.setChecked(True) self.enable_right.stateChanged.connect(self.change_check) self.enable_left.setChecked(True) self.enable_left.stateChanged.connect(self.change_check) # Add the check boxes self.left_layout.addWidget(self.enable_left, 0, 0) self.right_layout.addWidget(self.enable_right, 0, 0) # Add the labels and initial buttons from the left side to left_layout self.left_layout.addWidget(self.left_carrier_frequency_label, 1, 0) self.left_layout.addWidget(self.left_modulation_label, 2, 0) self.left_layout.addWidget(self.left_am_percentage_label, 3, 0) self.left_layout.addWidget(self.left_fm_percentage_label, 4, 0) self.left_layout.addWidget(self.left_fm_phase_label, 5, 0) self.left_layout.addWidget(self.left_amplitude_label, 6, 0) for i in range(4): self.left_layout.addWidget(self.left_components[i], 0, i+1) self.left_layout.addWidget(self.left_buttons_frequency[i], 1, i+1) self.left_layout.addWidget(self.left_buttons_modulation[i], 2, i+1) self.left_layout.addWidget(self.left_buttons_am_deepness[i], 3, i+1) self.left_layout.addWidget(self.left_buttons_fm_deepness[i], 4, i+1) self.left_layout.addWidget(self.left_buttons_fm_phase[i], 5, i+1) self.left_layout.addWidget(self.left_buttons_amplitude[i], 6, i+1) self.left_layout.addWidget(QWidget(self, flags=Qt.Widget), 7, i+1) self.right_layout.setSpacing(0) # Set right layout spacing as zero # Add the labels and initial buttons from the right side to right_layout self.right_layout.addWidget(self.right_carrier_frequency_label, 1, 0) self.right_layout.addWidget(self.right_modulation_label, 2, 0) self.right_layout.addWidget(self.right_am_percentage_label, 3, 0) self.right_layout.addWidget(self.right_fm_percentage_label, 4, 0) self.right_layout.addWidget(self.right_fm_phase_label, 5, 0) self.right_layout.addWidget(self.right_amplitude_label, 6, 0) for i in range(4): self.right_layout.addWidget(self.right_components[i], 0, i+1) self.right_layout.addWidget(self.right_buttons_frequency[i], 1, i+1) self.right_layout.addWidget(self.right_buttons_modulation[i], 2, i+1) self.right_layout.addWidget(self.right_buttons_am_deepness[i], 3, i+1) self.right_layout.addWidget(self.right_buttons_fm_deepness[i], 4, i+1) self.right_layout.addWidget(self.right_buttons_fm_phase[i], 5, i+1) self.right_layout.addWidget(self.right_buttons_amplitude[i], 6, i+1) self.right_layout.addWidget(QWidget(self, flags=Qt.Widget), 7, i+1) # Add right and left layout to horizontal layout self.horizontal_layout.addWidget(self.left_group, alignment=Qt.AlignLeft) self.horizontal_layout.addWidget(self.right_group, alignment=Qt.AlignLeft) # Add previews to their layouts self.preview_fft_layout.addWidget(self.preview_fft_left, alignment=Qt.AlignCenter) self.preview_fft_layout.addWidget(self.preview_fft_right, alignment=Qt.AlignCenter) self.preview_expected_layout.addWidget(self.preview_expected_left, alignment=Qt.AlignCenter) self.preview_expected_layout.addWidget(self.preview_expected_right, alignment=Qt.AlignCenter) self.vertical_layout.addLayout(self.horizontal_layout) self.vertical_layout.addLayout(self.preview_fft_layout) self.vertical_layout.addLayout(self.preview_expected_layout) self.vertical_layout.addStretch() # Set self layout as horizontal_layout self.setLayout(self.vertical_layout) self.show() # Set self visible def on_click_frequency(self): """ When the frequency button is clicked, this method will be called. OBS.: When the mouse leaves the pop-up window, the pop-up will close itself. :return: None """ btn = self.sender() # Gets the button responsible for the call FrequencyPicker(btn) # Calls the pop-up value picker def on_click_modulation(self): btn = self.sender() ModulationPicker(btn) def on_click_am_percentage(self): btn = self.sender() AMPercentagePicker(btn) def on_click_fm_percentage(self): btn = self.sender() FMPercentagePicker(btn) def on_click_fm_phase(self): btn = self.sender() FMPhasePicker(btn) def on_click_amplitude(self): btn = self.sender() AmplitudePicker(btn) def test_event(self): print(self.right_group.size()) def resizeEvent(self, e): self.left_group.resize(self.size().width() / 2 - 10, self.left_group.size().height()) self.left_group.setMaximumWidth(self.width() / 2 - 10) self.right_group.resize(self.size().width() / 2 - 10, self.right_group.size().height()) self.right_group.setMaximumWidth(self.width() / 2 - 10) def change_check(self): check = self.sender() if check is self.enable_left: if not self.enable_left.checkState(): for b1, b2, b3, b4, b5, b6 in zip(self.left_buttons_frequency, self.left_buttons_amplitude, self.left_buttons_fm_phase, self.left_buttons_fm_deepness, self.left_buttons_am_deepness, self.left_buttons_modulation): b1.setDisabled(True) b2.setDisabled(True) b3.setDisabled(True) b4.setDisabled(True) b5.setDisabled(True) b6.setDisabled(True) else: for b1, b2, b3, b4, b5, b6 in zip(self.left_buttons_frequency, self.left_buttons_amplitude, self.left_buttons_fm_phase, self.left_buttons_fm_deepness, self.left_buttons_am_deepness, self.left_buttons_modulation): b1.setDisabled(False) b2.setDisabled(False) b3.setDisabled(False) b4.setDisabled(False) b5.setDisabled(False) b6.setDisabled(False) elif check is self.enable_right: if not self.enable_right.checkState(): for b1, b2, b3, b4, b5, b6 in zip(self.right_buttons_frequency, self.right_buttons_amplitude, self.right_buttons_fm_phase, self.right_buttons_fm_deepness, self.right_buttons_am_deepness, self.right_buttons_modulation): b1.setDisabled(True) b2.setDisabled(True) b3.setDisabled(True) b4.setDisabled(True) b5.setDisabled(True) b6.setDisabled(True) else: for b1, b2, b3, b4, b5, b6 in zip(self.right_buttons_frequency, self.right_buttons_amplitude, self.right_buttons_fm_phase, self.right_buttons_fm_deepness, self.right_buttons_am_deepness, self.right_buttons_modulation): b1.setDisabled(False) b2.setDisabled(False) b3.setDisabled(False) b4.setDisabled(False) b5.setDisabled(False) b6.setDisabled(False)
class Setup(QWidget): def __init__(self, m): QWidget.__init__(self) self.MW = m self.g = m.game self.setWindowTitle("Setup") self.gameVar = GameVar() self.menu = 0 self.lastSymClicked = -1 self.lineEdit = QTextEdit() font = self.lineEdit.font() # lineedit current font font.setPointSize(20) # change it's size self.lineEdit.setFont(font) self.lineEdit.setAlignment(QtCore.Qt.AlignCenter) self.lineEdit.setFixedHeight(100) self.lineEdit.setFixedWidth(400) self.lineEdit.setStyleSheet("border: 1px solid #1e1e1e;") self.lineEdit.setAlignment(QtCore.Qt.AlignCenter) if (self.gameVar.serialOK == 0): self.lineEdit.setText("Err Arduino") self.btns = [] self.boxs = [] for i in range(5): box = QHBoxLayout() for j in range(2): btn = QPushButton("") btn.setMaximumHeight(400) btn.setFixedHeight(100) f = btn.font() f.setPointSize(18) btn.setFont(f) self.btns.append(btn) box.addWidget(btn) self.boxs.append(box) self.linehbox = QHBoxLayout() self.linehbox.addWidget(self.lineEdit) self.vbox = QVBoxLayout() self.vbox.addLayout(self.linehbox) for box in self.boxs: self.vbox.addLayout(box) self.setGeometry(0, 0, 480, 720) self.setLayout(self.vbox) self.mPrincipal() @pyqtSlot() def mParametreInstalle(self, nextMenu='mPrincipal'): self.resetBtn() self.g.checkSensor() msg = "Chrono: " + str(self.gameVar.chrono[0]) + str( self.gameVar.chrono[1]) + ":" + str(self.gameVar.chrono[2]) + str( self.gameVar.chrono[3]) if not self.gameVar.chronoBoutonSon: msg = "Volume désactivé !" nbFilDeco = 0 for c in self.gameVar.ordreFils: if c[0] == "": nbFilDeco += 1 if sum(self.gameVar.etatFils.values()) != nbFilDeco: msg = "Fil déconnecté !" else: couleur = [] for cables in self.gameVar.ordreFils: couleur.append(cables[0][:3]) self.btns[4].setText("Fils : " + couleur[0] + ", " + couleur[1] + "\n" + str(couleur[2:])) self.lineEdit.setText(msg) self.btns[0].setText("pile : " + str(self.gameVar.nbPile)) self.btns[1].setText("S/N : " + str(self.gameVar.serialNumber[:5]) + "...") self.btns[2].setText("Symb : " + str(self.gameVar.symboleInstalle[0]) + " " + str(self.gameVar.symboleInstalle[1]) + " \n " + str(self.gameVar.symboleInstalle[3]) + " " + str(self.gameVar.symboleInstalle[2])) self.btns[3].setText( "Bouton :\n" + str(self.gameVar.listeBouton[self.gameVar.modeleBtn])) self.btns[5].setText("Nb Erreurs :\n" + str(self.gameVar.nbErreurMax)) self.btns[6].setText("Mentions :\n" + str(self.gameVar.mentionInstalle)) self.btns[-2].setText("Retour") self.btns[-2].clicked.connect(self.mPrincipal) self.btns[-1].setText("Suivant") self.btns[-1].clicked.connect(getattr(self, nextMenu)) @pyqtSlot() def mEscapeGame(self): gv = self.gameVar gv.nbPile = 3 gv.serialNumber = "AG54V6K-DF4SKV5E" gv.mentionInstalle = ["FRQ", "CAR"] gv.ordreFils = [ gv.filNoir, gv.filBlanc, gv.filMarron, gv.filGris, gv.filBleu ] gv.modeleBtn = 1 gv.symboleInstalle = [31, 21, 19, 24] gv.chrono = [6, 0, 0, 0, 0] gv.nbErreurMax = 5 gv.pause = 1 gv.escapeGame = 1 self.simonNbEtape = 5 self.mParametreInstalle("startGame") @pyqtSlot() def startGame(self): self.resetBtn() self.g.start() self.MW.stackSetup.setCurrentIndex(2) @pyqtSlot() def mBombe(self): self.resetBtn() self.gameVar.escapeGame = 0 self.mParametreInstalle("startGame") def resetBtn(self): self.lineEdit.setPalette(self.lineEdit.style().standardPalette()) self.lineEdit.setStyleSheet( "color: #ffffff;border: 1px solid #1e1e1e;") for btn in self.btns: btn.setText("") btn.clicked.connect(self.mRien) btn.clicked.disconnect() self.repaint() @pyqtSlot() def mRien(self): pass @pyqtSlot() def setValue(self, var, ret): btn = self.sender() setattr(self.gameVar, var, btn.value) getattr(self, ret)() @pyqtSlot() def toggleValueFromList(self, var, ret): btn = self.sender() mVar = getattr(self.gameVar, var) if btn.value in mVar: mVar.remove(btn.value) else: mVar.append(btn.value) getattr(self, ret)() @pyqtSlot() def mPrincipal(self): self.resetBtn() self.lineEdit.setText("Menu Principal") self.lineEdit.setAlignment(QtCore.Qt.AlignCenter) self.btns[0].setText("Paramètres") self.btns[0].clicked.connect(self.mParametres) self.btns[1].setText("Voir\nParamètres") self.btns[1].clicked.connect(self.mParametreInstalle) self.btns[2].setText("niveau 1") self.btns[2].clicked.connect(lambda: self.niveau(1)) self.btns[3].setText("niveau 2") self.btns[3].clicked.connect(lambda: self.niveau(2)) self.btns[4].setText("niveau 3") self.btns[4].clicked.connect(lambda: self.niveau(3)) self.btns[5].setText("niveau 4") self.btns[5].clicked.connect(lambda: self.niveau(4)) self.btns[6].setText("niveau 5") self.btns[6].clicked.connect(lambda: self.niveau(5)) self.btns[-3].setText("Jouer") self.btns[-3].clicked.connect(self.mBombe) self.btns[-2].setText("Quitter") self.btns[-2].clicked.connect(self.exit) self.btns[-1].setText("Escape Game") self.btns[-1].clicked.connect(self.mEscapeGame) @pyqtSlot() def niveau(self, lvl): gv = self.gameVar if lvl == 1: gv.nbPile = 2 gv.serialNumber = "XD7FSRD/SFPJCMLZ" gv.mentionInstalle = ["BOB", "CAR"] gv.ordreFils = [ gv.filNoir, gv.filBlanc, gv.filMarron, gv.filGris, gv.filBleu ] gv.modeleBtn = 1 gv.symboleInstalle = [9, 12, 7, 28] gv.chrono = [0, 5, 0, 0, 0] gv.moduleWin = [1, 1, 0, 0, 0] gv.nbErreurMax = 5 if lvl == 2: gv.nbPile = 3 gv.serialNumber = "AG54V6K-DF4SKV5E" gv.mentionInstalle = ["FRK", "FRQ"] gv.ordreFils = [ gv.filBleu, gv.filRien, gv.filMarron, gv.filGris, gv.filRien ] gv.modeleBtn = 1 gv.symboleInstalle = [5, 21, 31, 7] gv.chrono = [0, 5, 0, 0, 0] gv.moduleWin = [ 0, 1, 0, 0, 0 ] # Led verte pour : Simon, ScreenGame, fils, symbole, bouton gv.nbErreurMax = 5 gv.simonNbEtape = 3 if lvl == 3: gv.nbPile = 0 gv.serialNumber = "1547-439-17H3-28" gv.mentionInstalle = ["MSA", "TRN"] gv.ordreFils = [ gv.filRien, gv.Noir, gv.filRien, gv.filGris, gv.filBlanc ] gv.modeleBtn = 1 gv.symboleInstalle = [15, 3, 26, 8] gv.chrono = [0, 6, 0, 0, 0] gv.moduleWin = [ 0, 0, 0, 0, 0 ] # Led verte pour : Simon, ScreenGame, fils, symbole, bouton gv.nbErreurMax = 4 gv.simonNbEtape = 4 if lvl == 4: gv.nbPile = 4 gv.serialNumber = "DGH4-HV36-ULM4LV" gv.mentionInstalle = ["CAR"] gv.ordreFils = [ gv.filRien, gv.filRien, gv.filRien, gv.filGris, gv.filBlanc ] gv.modeleBtn = 1 gv.symboleInstalle = [31, 21, 22, 4] gv.chrono = [0, 4, 3, 0, 0] gv.moduleWin = [ 0, 0, 0, 0, 0 ] # Led verte pour : Simon, ScreenGame, fils, symbole, bouton gv.nbErreurMax = 3 gv.simonNbEtape = 4 if lvl == 5: gv.nbPile = 1 gv.serialNumber = "1547-439-17H3-28" gv.mentionInstalle = ["BOB", "MSA"] gv.ordreFils = [ gv.filGris, gv.filBlanc, gv.filNoir, gv.filMarron, gv.filBleu ] gv.modeleBtn = 1 gv.symboleInstalle = [31, 21, 22, 4] gv.chrono = [0, 4, 0, 0, 0] gv.moduleWin = [ 0, 0, 0, 0, 0 ] # Led verte pour : Simon, ScreenGame, fils, symbole, bouton gv.nbErreurMax = 2 gv.simonNbEtape = 5 self.mBombe() @pyqtSlot() def exit(self): sys.exit(0) @pyqtSlot() def mParametres(self): self.resetBtn() self.lineEdit.setText("Accessoires") self.lineEdit.setAlignment(QtCore.Qt.AlignCenter) self.btns[0].setText("piles") self.btns[0].clicked.connect(self.mPile) self.btns[1].setText("Num Série") self.btns[1].clicked.connect(self.mNumSerie) self.btns[2].setText("Mentions") self.btns[2].clicked.connect(self.mMentions) self.btns[3].setText("Fils") self.btns[3].clicked.connect(self.mFils) self.btns[4].setText("Bouton") self.btns[4].clicked.connect(self.mBouton) self.btns[5].setText("Symbole") self.btns[5].clicked.connect(self.mSymbole) self.btns[6].setText("Chrono") self.btns[6].clicked.connect(self.mChrono) self.btns[7].setText("Nb Erreur") self.btns[7].clicked.connect(self.mNbErreur) self.btns[-2].setText("Retour") self.btns[-2].clicked.connect(self.mPrincipal) self.btns[-1].setText("Suivant") self.btns[-1].clicked.connect(self.mPrincipal) @pyqtSlot() def mPile(self): self.resetBtn() self.lineEdit.setText("Pile : " + str(self.gameVar.nbPile)) self.lineEdit.setAlignment(QtCore.Qt.AlignCenter) self.resetBtn() self.menu = 2 for i in range(5): self.btns[i].setText(str(i)) self.btns[i].value = i self.btns[i].clicked.connect( lambda: self.setValue("nbPile", "mPile")) self.btns[-2].setText("Retour") self.btns[-2].clicked.connect(self.mParametres) self.btns[-1].setText("Suivant") self.btns[-1].clicked.connect(self.mNumSerie) @pyqtSlot() def mNumSerie(self): self.resetBtn() self.lineEdit.setText("ID Num Série : " + str(self.gameVar.serialNumber)) self.lineEdit.setAlignment(QtCore.Qt.AlignCenter) for sn, btn in zip(self.gameVar.listeSerialNumber, self.btns[:-2]): btn.setText(sn[:5] + "...") btn.value = sn btn.clicked.connect( lambda: self.setValue("serialNumber", "mNumSerie")) self.btns[-2].setText("Retour") self.btns[-2].clicked.connect(self.mParametres) self.btns[-1].setText("Suivant") self.btns[-1].clicked.connect(self.mMentions) @pyqtSlot() def mMentions(self): self.resetBtn() self.lineEdit.setText("Mention Active : " + str(self.gameVar.mentionInstalle)) self.lineEdit.setAlignment(QtCore.Qt.AlignCenter) for ment, btn in zip(self.gameVar.mentionDispo, self.btns[:-2]): btn.setText(ment) btn.value = ment btn.clicked.connect(lambda: self.toggleValueFromList( "mentionInstalle", "mMentions")) self.btns[-2].setText("Retour") self.btns[-2].clicked.connect(self.mParametres) self.btns[-1].setText("Suivant") self.btns[-1].clicked.connect(self.mFils) @pyqtSlot() def mFils(self): self.resetBtn() couleur = [] for cables in self.gameVar.ordreFils: couleur.append(cables[0]) self.lineEdit.setText("Ordre Cables : " + str(couleur)) self.lineEdit.setAlignment(QtCore.Qt.AlignCenter) for i, btn in zip(range(5), self.btns[:-3]): btn.setText("Emplacement " + str(i + 1)) btn.value = i btn.clicked.connect(self.mCouleurFils) self.btns[-3].clicked.connect(self.setCouleurFil) self.btns[-2].setText("Retour") self.btns[-2].clicked.connect(self.mParametres) self.btns[-1].setText("Suivant") self.btns[-1].clicked.connect(self.mBouton) @pyqtSlot() def mCouleurFils(self): btnClicked = self.sender() print(btnClicked.value) self.resetBtn() for fil, btn in zip(self.gameVar.filDispo, self.btns[:-2]): btn.setText(str(fil[0])) btn.value = btnClicked.value btn.fil = fil btn.clicked.connect(self.setCouleurFil) self.btns[-3].setText("Rien") self.btns[-3].fil = -1 self.btns[-3].value = btnClicked.value self.btns[-3].clicked.connect(self.setCouleurFil) @pyqtSlot() def setCouleurFil(self): btnClicked = self.sender() print(btnClicked.value) if btnClicked.fil == -1: print("btnClicked.value == -1") self.gameVar.ordreFils[btnClicked.value] = self.gameVar.filRien else: print("else") if len(self.gameVar.ordreFils) <= btnClicked.value: self.gameVar.ordreFils.append(btnClicked.fil) else: self.gameVar.ordreFils[btnClicked.value] = btnClicked.fil self.mFils() @pyqtSlot() def mBouton(self): self.resetBtn() self.lineEdit.setText( "Modèle Bouton :\n" + str(self.gameVar.listeBouton[self.gameVar.modeleBtn])) self.lineEdit.setAlignment(QtCore.Qt.AlignCenter) for idBtn, btn in zip(self.gameVar.listeBouton, self.btns[:-2]): btn.setText(idBtn) btn.value = self.gameVar.listeBouton.index(idBtn) btn.clicked.connect(lambda: self.setValue("modeleBtn", "mBouton")) self.btns[-2].setText("Retour") self.btns[-2].clicked.connect(self.mParametres) self.btns[-1].setText("Suivant") self.btns[-1].clicked.connect(self.mSymbole) def chkSymbole(self): gv = self.gameVar for col in gv.symboleColonnes: # colonne du manuel if all(elem in col for elem in gv.symboleInstalle ): # Si les 4 symboles se trouve dans la colonne return True return False @pyqtSlot() def symboleAleatoire(self): self.gameVar.symboleInstalle = random.sample( random.choice(self.gameVar.symboleColonnes), 4) self.mSymbole() @pyqtSlot() def mSymbole(self): self.resetBtn() if self.chkSymbole(): # Si les 4 symboles se trouve dans la colonne self.lineEdit.setText("Symbole OK") self.lineEdit.setAlignment(QtCore.Qt.AlignCenter) else: if not 0 in self.gameVar.symboleInstalle: print(self.gameVar.symboleInstalle) pRed = QPalette() pRed.setColor(QPalette.Base, Qt.red) self.lineEdit.setPalette(pRed) self.lineEdit.setText("Combinaison de symbole impossible") elif self.gameVar.symboleInstalle.count( 0 ) <= 3: # aide si tout les symboles ne sont pas encore choisi symbolePossible = [] for col in self.gameVar.symboleColonnes: listSansZero = list( filter((0).__ne__, self.gameVar.symboleInstalle)) if all(x in col for x in listSansZero): symbolePossible.extend( [x for x in col if x not in listSansZero]) if len(symbolePossible) != 0: symbolePossibleAleatoire = random.sample( symbolePossible, len(symbolePossible)) self.lineEdit.setText("Sym possible : " + str(symbolePossibleAleatoire)) else: self.lineEdit.setText("Aucune combinaison possible") else: self.lineEdit.setText("Symbole") self.lineEdit.setAlignment(QtCore.Qt.AlignCenter) self.btns[0].setText(str(self.gameVar.symboleInstalle[0])) self.btns[0].value = 0 self.btns[0].clicked.connect(self.callmSymbole) self.btns[1].setText(str(self.gameVar.symboleInstalle[1])) self.btns[1].value = 1 self.btns[1].clicked.connect(self.callmSymbole) self.btns[2].setText(str(self.gameVar.symboleInstalle[3])) self.btns[2].value = 3 self.btns[2].clicked.connect(self.callmSymbole) self.btns[3].setText(str(self.gameVar.symboleInstalle[2])) self.btns[3].value = 2 self.btns[3].clicked.connect(self.callmSymbole) self.btns[-3].setText("Aleatoire") self.btns[-3].clicked.connect(self.symboleAleatoire) self.btns[-2].setText("Retour") self.btns[-2].clicked.connect(self.mParametres) self.btns[-1].setText("Suivant") self.btns[-1].clicked.connect(self.mChrono) @pyqtSlot() def callmSymbole(self): btnClicked = self.sender() self.resetBtn() self.lastSymClicked = btnClicked.value self.MW.stackSetup.setCurrentIndex(1) self.MW.setupSymbole.mSetSymbole() @pyqtSlot() def mChrono(self): self.resetBtn() self.lineEdit.setText("Chrono: " + str(self.gameVar.chrono[0]) + str(self.gameVar.chrono[1]) + ":" + str(self.gameVar.chrono[2]) + str(self.gameVar.chrono[3])) self.btns[0].setText("-1") self.btns[0].value = ("chronoMoins", 1) self.btns[0].clicked.connect(self.msetChrono) self.btns[1].setText("+1") self.btns[1].value = ("chronoPlus", 1) self.btns[1].clicked.connect(self.msetChrono) self.btns[2].setText("-5") self.btns[2].value = ("chronoMoins", 5) self.btns[2].clicked.connect(self.msetChrono) self.btns[3].setText("+5") self.btns[3].value = ("chronoPlus", 5) self.btns[3].clicked.connect(self.msetChrono) self.btns[4].setText("-10") self.btns[4].value = ("chronoMoins", 10) self.btns[4].clicked.connect(self.msetChrono) self.btns[5].setText("+10") self.btns[5].value = ("chronoPlus", 10) self.btns[5].clicked.connect(self.msetChrono) self.btns[-2].setText("Retour") self.btns[-2].clicked.connect(self.mParametres) self.btns[-1].setText("Suivant") self.btns[-1].clicked.connect(self.mNbErreur) self.lineEdit.setAlignment(QtCore.Qt.AlignCenter) @pyqtSlot() def msetChrono(self): btnClicked = self.sender() c = Chrono s = getattr(c, btnClicked.value[0]) s(self.g, btnClicked.value[1]) self.mChrono() @pyqtSlot() def mNbErreur(self): self.resetBtn() self.lineEdit.setText("Nb erreur : " + str(self.gameVar.nbErreurMax)) self.lineEdit.setAlignment(QtCore.Qt.AlignCenter) for i, btn in zip(range(1, 6), self.btns[:-2]): btn.setText(str(i)) btn.value = i btn.clicked.connect(self.mSetNbErreur) self.btns[-2].setText("Retour") self.btns[-2].clicked.connect(self.mParametres) self.btns[-1].setText("Suivant") self.btns[-1].clicked.connect(self.mParametres) @pyqtSlot() def mSetNbErreur(self): btnClicked = self.sender() self.gameVar.nbErreurMax = btnClicked.value self.mNbErreur()
def __init__(self, *, parent: 'ElectrumWindow', desc, prompt_if_unsaved, finalized: bool, external_keypairs=None): '''Transactions in the wallet will show their description. Pass desc to give a description for txs not yet in the wallet. ''' # We want to be a top-level window QDialog.__init__(self, parent=None) self.tx = None # type: Optional[Transaction] self.external_keypairs = external_keypairs self.finalized = finalized self.main_window = parent self.config = parent.config self.wallet = parent.wallet self.prompt_if_unsaved = prompt_if_unsaved self.saved = False self.desc = desc self.setMinimumWidth(640) self.resize(1200, 600) self.set_title() self.psbt_only_widgets = [] # type: List[QWidget] vbox = QVBoxLayout() self.setLayout(vbox) vbox.addWidget(QLabel(_("Transaction ID:"))) self.tx_hash_e = ButtonsLineEdit() self.tx_hash_e.add_qr_show_button(config=self.config, title='Transaction ID') self.tx_hash_e.setReadOnly(True) vbox.addWidget(self.tx_hash_e) self.add_tx_stats(vbox) vbox.addSpacing(10) self.inputs_header = QLabel() vbox.addWidget(self.inputs_header) self.inputs_textedit = QTextEditWithDefaultSize() vbox.addWidget(self.inputs_textedit) self.txo_color_recv = TxOutputColoring( legend=_("Receiving Address"), color=ColorScheme.GREEN, tooltip=_("Wallet receive address")) self.txo_color_change = TxOutputColoring( legend=_("Change Address"), color=ColorScheme.YELLOW, tooltip=_("Wallet change address")) self.txo_color_2fa = TxOutputColoring( legend=_("TrustedCoin (2FA) batch fee"), color=ColorScheme.BLUE, tooltip=_( "TrustedCoin (2FA) fee for the next batch of transactions")) outheader_hbox = QHBoxLayout() outheader_hbox.setContentsMargins(0, 0, 0, 0) vbox.addLayout(outheader_hbox) self.outputs_header = QLabel() outheader_hbox.addWidget(self.outputs_header) outheader_hbox.addStretch(2) outheader_hbox.addWidget(self.txo_color_recv.legend_label) outheader_hbox.addWidget(self.txo_color_change.legend_label) outheader_hbox.addWidget(self.txo_color_2fa.legend_label) self.outputs_textedit = QTextEditWithDefaultSize() vbox.addWidget(self.outputs_textedit) self.sign_button = b = QPushButton(_("Sign")) b.clicked.connect(self.sign) self.broadcast_button = b = QPushButton(_("Broadcast")) b.clicked.connect(self.do_broadcast) self.save_button = b = QPushButton(_("Save")) b.clicked.connect(self.save) self.cancel_button = b = QPushButton(_("Close")) b.clicked.connect(self.close) b.setDefault(True) self.export_actions_menu = export_actions_menu = QMenu() self.add_export_actions_to_menu(export_actions_menu) export_actions_menu.addSeparator() export_submenu = export_actions_menu.addMenu( _("For CoinJoin; strip privates")) self.add_export_actions_to_menu(export_submenu, gettx=self._gettx_for_coinjoin) self.psbt_only_widgets.append(export_submenu) export_submenu = export_actions_menu.addMenu( _("For hardware device; include xpubs")) self.add_export_actions_to_menu(export_submenu, gettx=self._gettx_for_hardware_device) self.psbt_only_widgets.append(export_submenu) self.export_actions_button = QToolButton() self.export_actions_button.setText(_("Export")) self.export_actions_button.setMenu(export_actions_menu) self.export_actions_button.setPopupMode(QToolButton.InstantPopup) self.finalize_button = QPushButton(_('Finalize')) self.finalize_button.clicked.connect(self.on_finalize) partial_tx_actions_menu = QMenu() ptx_merge_sigs_action = QAction(_("Merge signatures from"), self) ptx_merge_sigs_action.triggered.connect(self.merge_sigs) partial_tx_actions_menu.addAction(ptx_merge_sigs_action) self._ptx_join_txs_action = QAction(_("Join inputs/outputs"), self) self._ptx_join_txs_action.triggered.connect(self.join_tx_with_another) partial_tx_actions_menu.addAction(self._ptx_join_txs_action) self.partial_tx_actions_button = QToolButton() self.partial_tx_actions_button.setText(_("Combine")) self.partial_tx_actions_button.setMenu(partial_tx_actions_menu) self.partial_tx_actions_button.setPopupMode(QToolButton.InstantPopup) self.psbt_only_widgets.append(self.partial_tx_actions_button) # Action buttons self.buttons = [ self.partial_tx_actions_button, self.sign_button, self.broadcast_button, self.cancel_button ] # Transaction sharing buttons self.sharing_buttons = [ self.finalize_button, self.export_actions_button, self.save_button ] run_hook('transaction_dialog', self) if not self.finalized: self.create_fee_controls() vbox.addWidget(self.feecontrol_fields) self.hbox = hbox = QHBoxLayout() hbox.addLayout(Buttons(*self.sharing_buttons)) hbox.addStretch(1) hbox.addLayout(Buttons(*self.buttons)) vbox.addLayout(hbox) self.set_buttons_visibility() dialogs.append(self)
def initUI(self): backButton = QPushButton('') backButton.setIcon(QIcon('image/back_2.png')) backButton.setIconSize(QSize(75, 75)) backButton.clicked.connect(self.back) tab = QTabWidget() tab.setTabPosition(QTabWidget.South) self.city_name = QLineEdit() cities = QWidget() form_cities = QFormLayout() form_cities.setAlignment(Qt.AlignVCenter) form_cities.addRow(QLabel('Название города'), self.city_name) cities.setLayout(form_cities) tab.addTab(cities, 'Города') btn = QPushButton('xii') btn.clicked.connect(self.search_city) btn_h = QHBoxLayout() btn_h.addStretch(3) btn_h.addWidget(backButton) hh = QHBoxLayout() hh.addStretch(1) hh.addWidget(tab, 3) hh.addStretch(1) vv = QVBoxLayout() vv.addLayout(btn_h) vv.addStretch(1) vv.addLayout(hh) vv.addStretch(1) vv.addWidget(btn) self.setLayout(vv) style = "QTabWidget {background-color: rgb(117, 160, 252); font-size: 30px;}" \ "QLabel {background-color: transparent; font-size: 20px;}" \ "QLineEdit {background-color: white; font-size: 20px; border: 1px solid transparent; margin: 0px;}" backButton.setStyleSheet( "background-color: rgba(255, 255, 255, 0.1); padding: 12px;") self.setStyleSheet(style) tab.setStyleSheet("background-color: rgb(117, 160, 252);") p = QPalette() gradient = QLinearGradient(0, 0, 120, 400) gradient.setColorAt(0.0, QColor(117, 160, 252)) gradient.setColorAt(1.0, QColor(193, 203, 253)) p.setBrush(QPalette.Window, QBrush(gradient)) self.setPalette(p) if self.expansion == '1': self.showFullScreen() else: self.setGeometry(0, 30, 800, 600) self.setFixedSize(800, 600) self.setWindowTitle('Menubar') self.show()
class GridWidget(QWidget): def __init__(self, kind, im_width, num_rows=3, num_cols=4, labeler=False): super(GridWidget, self).__init__() self.num_rows = num_rows self.num_cols = num_cols self.page = 1 self.gridLayout = QGridLayout() self.kind = kind #fullname=str(self.model) #self.name= (fullname[fullname.find(":")+2:fullname.find(">")].strip()+'_set').lower() self.images = [None] * (self.num_rows * self.num_cols) self.updated = True self.num_pages = 1 for i in range(self.num_rows): for j in range(self.num_cols): index = i * self.num_cols + j self.images[index] = ImageView(im_width, labeler) self.gridLayout.addWidget(self.images[index], i, j) self.next = QPushButton('Next') self.previous = QPushButton('Previous') self.last = QPushButton('Last') self.first = QPushButton('First') self.of = QLabel('of') self.total = QLabel() self.current = QLineEdit("1") self.current.setValidator(QIntValidator()) self.horizontalLayout = QHBoxLayout() self.horizontalLayout.addWidget(self.first) self.horizontalLayout.addWidget(self.previous) self.horizontalLayout.addWidget(self.current) self.horizontalLayout.addWidget(self.of) self.horizontalLayout.addWidget(self.total) self.horizontalLayout.addWidget(self.next) self.horizontalLayout.addWidget(self.last) self.verticalLayout = QVBoxLayout() self.verticalLayout.addLayout(self.gridLayout, stretch=1) self.verticalLayout.addLayout(self.horizontalLayout, stretch=0) self.labeler = labeler if labeler: self.horizontalLayout2 = QHBoxLayout() self.horizontalLayout2.addLayout(self.verticalLayout) self.refreshLabeler() self.setLayout(self.horizontalLayout2) else: self.setLayout(self.verticalLayout) self.updatePages() self.next.clicked.connect(self.doNext) self.previous.clicked.connect(self.doPrevious) self.last.clicked.connect(self.doLast) self.first.clicked.connect(self.doFirst) self.current.returnPressed.connect(self.doJump) def refreshLabeler(self): if hasattr(self, "labelerGrid"): for i in reversed(range(self.labelerGrid.count())): self.labelerGrid.itemAt(i).widget().deleteLater() self.labelerGrid.deleteLater() self.labelerGrid.setParent(None) self.horizontalLayout2.removeItem(self.labelerGrid) del self.labelerGrid self.labelerGrid = QGridLayout() query = Category.select() i = 0 for cat in query: button = QPushButton(cat.name) button.clicked.connect(self.clickgen(cat)) self.labelerGrid.addWidget(button, i // 2, i % 2) i += 1 button = QPushButton("Delete") button.clicked.connect(self.delete) self.labelerGrid.addWidget(button, i // 2, i % 2) self.horizontalLayout2.addLayout(self.labelerGrid) self.update() def clickgen(self, cat): def labelerClicked(event): for i in range(self.num_rows): for j in range(self.num_cols): index = i * self.num_cols + j ex_label = self.images[index] for label in ex_label.tags: if label.tik.isVisible() and label.tik.checkState(): label.updateLabel(cat) return labelerClicked def delete(self, event): for i in range(self.num_rows): for j in range(self.num_cols): index = i * self.num_cols + j ex_label = self.images[index] for tag in ex_label.tags: if tag.tik.isVisible() and tag.tik.checkState(): tag.setParent(None) ex_label.tags.remove(tag) def updatePages(self): count = Image.select().join(Detection).where( Detection.kind == self.kind.value).count() self.num_pages = (count // (self.num_rows * self.num_cols)) + 1 self.total.setText(str(self.num_pages)) self.current.setText(str(self.page)) if self.page == 1: self.previous.setEnabled(False) else: self.previous.setEnabled(True) if self.page == self.num_pages: self.next.setEnabled(False) else: self.next.setEnabled(True) def doNext(self, event): if self.page <= self.num_pages: self.page += 1 self.updated = True self.showCurrentPage() self.updatePages() def doPrevious(self, event): if self.page > 1: self.page -= 1 self.updated = True self.showCurrentPage() self.updatePages() def doLast(self, event): self.page = self.num_pages self.updated = True self.showCurrentPage() self.updatePages() def doFirst(self, event): self.page = 1 self.updated = True self.showCurrentPage() self.updatePages() def doJump(self): val = int(self.current.text()) if val >= 1 and val <= self.num_pages: self.page = val self.updated = True self.showCurrentPage() else: self.current.setText("1") self.updatePages() def showCurrentPage(self, force=False): if self.labeler: self.refreshLabeler() if self.updated or force: #print("Parent", self.parentWidget().width(), self.parentWidget().height()) self.clear() query = Image.select().join(Detection).where( Detection.kind == self.kind.value).paginate( self.page, self.num_rows * self.num_cols) #print(self.model,self.name,query.sql()) index = 0 for r in query: self.images[index].setSample( r.id, os.path.join('/project/evolvingai/mnorouzz/Serengiti/SER', r.file_name), r.detection_set) index += 1 self.updated = False def clear(self): self.visited = False for i in range(self.num_rows): for j in range(self.num_cols): index = i * self.num_cols + j self.images[index].clear()
def add_tx_stats(self, vbox): hbox_stats = QHBoxLayout() # left column vbox_left = QVBoxLayout() self.tx_desc = TxDetailLabel(word_wrap=True) vbox_left.addWidget(self.tx_desc) self.status_label = TxDetailLabel() vbox_left.addWidget(self.status_label) self.date_label = TxDetailLabel() vbox_left.addWidget(self.date_label) self.amount_label = TxDetailLabel() vbox_left.addWidget(self.amount_label) self.ln_amount_label = TxDetailLabel() vbox_left.addWidget(self.ln_amount_label) fee_hbox = QHBoxLayout() self.fee_label = TxDetailLabel() fee_hbox.addWidget(self.fee_label) self.fee_warning_icon = QLabel() pixmap = QPixmap(icon_path("warning")) pixmap_size = round(2 * char_width_in_lineedit()) pixmap = pixmap.scaled(pixmap_size, pixmap_size, Qt.KeepAspectRatio, Qt.SmoothTransformation) self.fee_warning_icon.setPixmap(pixmap) self.fee_warning_icon.setVisible(False) fee_hbox.addWidget(self.fee_warning_icon) fee_hbox.addStretch(1) vbox_left.addLayout(fee_hbox) vbox_left.addStretch(1) hbox_stats.addLayout(vbox_left, 50) # vertical line separator line_separator = QFrame() line_separator.setFrameShape(QFrame.VLine) line_separator.setFrameShadow(QFrame.Sunken) line_separator.setLineWidth(1) hbox_stats.addWidget(line_separator) # right column vbox_right = QVBoxLayout() self.size_label = TxDetailLabel() vbox_right.addWidget(self.size_label) self.rbf_label = TxDetailLabel() vbox_right.addWidget(self.rbf_label) self.rbf_cb = QCheckBox(_('Replace by fee')) self.rbf_cb.setChecked(bool(self.config.get('use_rbf', True))) vbox_right.addWidget(self.rbf_cb) self.locktime_final_label = TxDetailLabel() vbox_right.addWidget(self.locktime_final_label) locktime_setter_hbox = QHBoxLayout() locktime_setter_hbox.setContentsMargins(0, 0, 0, 0) locktime_setter_hbox.setSpacing(0) locktime_setter_label = TxDetailLabel() locktime_setter_label.setText("LockTime: ") self.locktime_e = LockTimeEdit(self) locktime_setter_hbox.addWidget(locktime_setter_label) locktime_setter_hbox.addWidget(self.locktime_e) locktime_setter_hbox.addStretch(1) self.locktime_setter_widget = QWidget() self.locktime_setter_widget.setLayout(locktime_setter_hbox) vbox_right.addWidget(self.locktime_setter_widget) self.block_height_label = TxDetailLabel() vbox_right.addWidget(self.block_height_label) vbox_right.addStretch(1) hbox_stats.addLayout(vbox_right, 50) vbox.addLayout(hbox_stats) # below columns self.block_hash_label = TxDetailLabel(word_wrap=True) vbox.addWidget(self.block_hash_label) # set visibility after parenting can be determined by Qt self.rbf_label.setVisible(self.finalized) self.rbf_cb.setVisible(not self.finalized) self.locktime_final_label.setVisible(self.finalized) self.locktime_setter_widget.setVisible(not self.finalized)
class Main(QWidget): countlength = 0 wordslist = [] typing = '' typeracermode = False error = 'errorsound.mp3' success = 'success.wav' running = True length = 0 threads = [] count = 0 counter = 0 errorcount = 0 name = None password = None trycount = 0 before = '' def __init__(self): super().__init__() self.disp = QPushButton() self.disp.hide() self.disp.clicked.connect(self.displayall) self.initUI() def initUI(self): self.label = QLabel(self) pixmap = QPixmap('logo.png') pixmap = pixmap.scaledToWidth(200) self.label.setPixmap(pixmap) self.lay = QVBoxLayout() self.label.setAlignment(Qt.AlignCenter) self.hor = QHBoxLayout() # self.lay.setContentsMargins(-1,-1,-1,0) self.Hbox = QHBoxLayout() # self.Hbox.addStretch(1) # self.hor.setAlignment(Qt.AlignCenter) # self.lay.addLayout(self.hor) self.setStyleSheet('QWidget {background-color:white;border:none}') # self.label.setStyleSheet('Q {width:50px;height:auto}') self.height = 60 self.trycount = 0 self.setGeometry(300, 150, 400, 600) self.setWindowTitle('Welcome') self.nameline = QLineEdit() self.passwordline = QLineEdit() self.nameline.setPlaceholderText("Username...") self.passwordline.setPlaceholderText("Password...") self.passwordline.setEchoMode(QLineEdit.Password) self.nameline.setStyleSheet( 'QLineEdit {background-color:#EEE;height:40;border-radius:3px;font-family:Arial;padding:6px}' ) self.passwordline.setStyleSheet( 'QLineEdit {background-color:#EEE;height:40;border-radius:3px;font-family:Arial;padding:6px;}' ) self.status = QLabel() self.status.setStyleSheet("color:red") self.lay.addStretch(1) self.lay.addWidget(self.label) self.lay.addStretch(1) self.lay.addWidget(self.nameline) self.lay.addWidget(self.passwordline) self.lay.addWidget(self.status) self.lay.setAlignment(self.nameline, Qt.AlignBottom) self.lay.addLayout(self.Hbox) # self.lay.addStretch(1) self.signin = QPushButton('Sign in') self.signup = QPushButton('Sign up') self.signin.setStyleSheet( 'QPushButton {background-color:#4990E2;color:white;height:50;font-size:20px;border-radius:3px;font-family:Arial;}' ) self.signup.setStyleSheet( 'QPushButton {background-color:#7FDC89;color:white;height:50;font-size:20px;border-radius:3px;font-family:Arial;}' ) self.signin.clicked.connect(self.authentification) self.signup.clicked.connect(self.authentification) self.Hbox.addWidget(self.signin) self.Hbox.addWidget(self.signup) self.setLayout(self.lay) self.show() def authentification(self): sender = self.sender() self.name = self.nameline.text() password = self.passwordline.text() if self.name == "" and password == "": self.status.setText('Type something') else: self.password = hashlib.md5(password.encode('utf-8')).hexdigest() if self.trycount == 0: self.socket = socket() global SERVER_ADDRESS self.socket.connect((SERVER_ADDRESS, 9090)) self.trycount += 1 sendlist = [sender.text(), self.name, self.password] req = pickle.dumps(sendlist) self.socket.send(req) response = self.socket.recv(2048) response = pickle.loads(response) if response == 'okay': self.startserver() threading.Thread(target=self.accept).start() else: self.status.setText('Incorrect login or password') def startserver(self): self.setGeometry(300, 150, 500, 600) self.setWindowTitle('Chat') clearLayout(self.lay) online = QLabel('Online:') messages = QLabel('Messages:') self.list = QListWidget() self.list.setStyleSheet( "QListWidget{border: none;border-radius:3px;background-color:#EEE}" ) self.active = QListWidget() self.active.setStyleSheet( "QListWidget{border: none;border-radius:3px;background-color:#EEE;height:40}" ) self.line = QLineEdit() self.mesLine = QHBoxLayout() self.send = QPushButton('Send') self.send.setStyleSheet( 'background: #6d84b4;color: white;height:40;width:70px;border-radius:3px' ) self.mesLine.addWidget(self.line) self.mesLine.addWidget(self.send) self.send.clicked.connect(self.sendmessage) self.line.setStyleSheet( "QLineEdit{border: none;border-radius:3px;background-color:#EEE;height:40}" ) self.line.setPlaceholderText("type something ...") self.startmode = QPushButton('Start typing') self.startmode.hide() self.startmode.clicked.connect(self.typeracer) self.lay.addWidget(online) self.lay.addWidget(self.active) self.lay.addWidget(messages) self.lay.addWidget(self.list) self.lay.addLayout(self.mesLine) def typeracer(self): self.setGeometry(300, 150, 400, 650) self.setWindowTitle('Typeracer') if hasattr(self, 'lay'): clearLayout(self.lay) else: self.lay = QVBoxLayout() self.setLayout(self.lay) if not self.typing: self.typing = "Hello WOT!!!" self.wordslist = list(self.typing.split()) self.mainlist = list(self.typing) self.words = len(list(self.typing.split())) self.textline = QTextEdit() self.textline.setText("<font color='blue' size=8>{}</font>".format( self.typing)) self.textline.setReadOnly(True) self.editline = QLineEdit() self.editline.setFixedSize(400, 70) font = self.editline.font() font.setPointSize(18) self.editline.setFont(font) self.editline.textChanged.connect(self.sec) self.stopbtn = QPushButton('Stop the game') self.stopbtn.clicked.connect(self.result) self.stopbtn.hide() self.lay.addWidget(self.textline) self.lay.addWidget(self.editline) self.lay.addWidget(self.stopbtn) self.firtime = time() def sec(self): text1 = self.editline.text() if len(self.before) < len(text1): if text1[-1] == self.mainlist[0]: self.counter += 1 typed = self.typing[:self.counter] future = self.typing[self.counter:] text = '''<font color='blue' size=8>{}</font> <font size=8>{}</font>'''.format(typed, future) self.textline.setText(text) if self.mainlist[0] == ' ': self.editline.setText('') self.before = '' else: self.countlength += 1 self.before = text1 self.mainlist = self.mainlist[1:] if not len(self.mainlist): self.result() else: self.errorcount += 1 self.before = text1 QSound.play(self.success) else: self.before = text1 def result(self): ch = 0 w = 0 for i in self.wordslist: if ch >= self.countlength: break ch += len(i) w += 1 print(w) print(self.countlength) print(ch) clearLayout(self.lay) tosend = [] self.time = time() - self.firtime h = round(self.time) self.time = self.time / 60 self.time = round(w / self.time) tosend.append(self.time) tosend.append(self.name) h = str(h) + ' seconds' tosend.append(h) self.errorcount = str(self.errorcount) + ' errors' tosend.append(self.errorcount) QSound.play(self.success) self.socket.sendall(pickle.dumps(tosend)) ss = [] for i in tosend: i = str(i) label = QLabel(' '.join(ss)) label2 = QLabel('Wait for others, it may take maximum 30 sec') self.lay.addWidget(label) self.lay.addWidget(label2) self.typing = [] def sendmessage(self): mymes = QListWidgetItem('You: {}'.format(self.line.text())) mymes.setTextAlignment(2) self.socket.send(pickle.dumps(self.line.text())) self.list.addItem(mymes) self.line.setText('') def accept(self): while self.running: try: mes = self.socket.recv(4096) mes = pickle.loads(mes) print(mes) if type(mes) == list: if type(mes[0]) == str: if mes[0] == 'to stop': self.stopbtn.click() else: self.active.clear() for i in mes: if i == self.name: i = 'You' a = QListWidgetItem(str(i)) a.setTextAlignment(0x0004) self.active.addItem(a) else: print(mes) self.clientresult = mes self.disp.click() elif type(mes) == dict: self.typing = list(mes.values())[0] self.startmode.click() elif mes == 'Admin: start': self.startmode.click() else: self.list.addItem(QListWidgetItem('{}'.format(mes))) except: pass def displayall(self): clearLayout(self.lay) listof = QListWidget() stat = copy.deepcopy(self.clientresult) stat = sorted(stat) stat = stat[::-1] for i in stat: if type(i[1]) == str: i[1], i[0] = i[0], i[1] i[1] = str(i[1]) + ' WPM' a = ' '.join(i) a = QListWidgetItem(a) listof.addItem(a) self.lay.addWidget(listof) goback = QPushButton('Back to chat') goback.clicked.connect(self.startserver) self.lay.addWidget(goback) self.counter = 0 self.errorcount = 0 self.countlength = 0 self.before = '' self.typing = [] def closeEvent(self, event): os._exit(1)
class Player(QMainWindow): """ Modification of the simple Media Player using VLC and Qt to show the mambo stream The window part of this example was modified from the QT example cited below. VLC requires windows to create and show the video and this was a cross-platform solution. VLC will automatically create the windows in linux but not on the mac. Amy McGovern, [email protected] Qt example for VLC Python bindings https://github.com/devos50/vlc-pyqt5-example Copyright (C) 2009-2010 the VideoLAN team This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA. """ def __init__(self, vlc_player, drone_gui): """ Create a UI window for the VLC player :param vlc_player: the VLC player (created outside the function) """ QMainWindow.__init__(self) self.setWindowTitle("VLC Drone Video Player") # save the media player self.mediaplayer = vlc_player # need a reference to the main drone vision class self.drone_vision = drone_gui # create the GUI self.createUI() def createUI(self): """ Set up the window for the VLC viewer """ self.widget = QWidget(self) self.setCentralWidget(self.widget) # In this widget, the video will be drawn if sys.platform == "darwin": # for MacOS from PyQt5.QtWidgets import QMacCocoaViewContainer self.videoframe = QMacCocoaViewContainer(0) else: self.videoframe = QFrame() self.palette = self.videoframe.palette() self.palette.setColor(QPalette.Window, QColor(0, 0, 0)) self.videoframe.setPalette(self.palette) self.videoframe.setAutoFillBackground(True) self.hbuttonbox = QHBoxLayout() self.playbutton = QPushButton("Run my program") self.hbuttonbox.addWidget(self.playbutton) self.playbutton.clicked.connect( partial(self.drone_vision.run_user_code, self.playbutton)) self.landbutton = QPushButton("Land NOW") self.hbuttonbox.addWidget(self.landbutton) self.landbutton.clicked.connect(self.drone_vision.land) self.stopbutton = QPushButton("Quit") self.hbuttonbox.addWidget(self.stopbutton) self.stopbutton.clicked.connect(self.drone_vision.close_exit) self.vboxlayout = QVBoxLayout() self.vboxlayout.addWidget(self.videoframe) self.vboxlayout.addLayout(self.hbuttonbox) self.widget.setLayout(self.vboxlayout) # the media player has to be 'connected' to the QFrame # (otherwise a video would be displayed in it's own window) # this is platform specific! # you have to give the id of the QFrame (or similar object) to # vlc, different platforms have different functions for this if sys.platform.startswith('linux'): # for Linux using the X Server self.mediaplayer.set_xwindow(self.videoframe.winId()) elif sys.platform == "win32": # for Windows self.mediaplayer.set_hwnd(self.videoframe.winId()) elif sys.platform == "darwin": # for MacOS self.mediaplayer.set_nsobject(int(self.videoframe.winId()))
def _set_up_ui(self): window_size_x = 640 window_size_y = 480 vbox = QVBoxLayout() if self.copy.active: self.book_id = QLabel("ID: " + str(self.copy.CopyID)) else: self.book_id = QLabel("<font color='red'>ID: " + str(self.copy.CopyID) + "</font>") top = QHBoxLayout() top.addStretch(1) top.addWidget(self.book_id) vbox.addLayout(top) self.fields = dict() dic = {'storage': str, 'checked_out': bool} for i in dic: if dic[i] == bool: continue line_item = QLabel(str(getattr(self.copy, i))) self.fields[i] = line_item line_label = QLabel(str(i) + ':') line_label.setFixedWidth(100) hbox = QHBoxLayout() hbox.addWidget(line_label) hbox.addWidget(line_item) vbox.addLayout(hbox) self.table = QTableWidget() self._set_up_table(self.table) vbox.addWidget(self.table) edit_button = QPushButton("Copy edit") edit_button.setFixedWidth(90) edit_button.setFixedHeight(25) edit_button.clicked.connect(self.edit) return_button = QPushButton("Return copy") return_button.setFixedWidth(90) return_button.setFixedHeight(25) return_button.clicked.connect(self.return_book) renew = QPushButton("Renew") renew.setFixedWidth(90) renew.setFixedHeight(25) renew.clicked.connect(self.renew) if self.copy.active: dbtext = "Delete" else: dbtext = "Restore" add_button_layout = QHBoxLayout() add_button_layout.addStretch() self.delete_button = add_button(add_button_layout, dbtext, self.delete_book, Copy.__name__, "remove", 90, 25) add_button_layout.addWidget(edit_button) add_button_layout.addWidget(renew) add_button_layout.addWidget(return_button) vbox.addLayout(add_button_layout) self.setLayout(vbox) self.resize(window_size_x, window_size_y) self.setWindowTitle(self.copy.get_doc().title + "'s copy info") self.show()
def setupUi(self): self.setWindowTitle("DEMO~~~~") self.button_hello = QPushButton() self.button_hello.setText("Start~") self.button_hello.setFont(QtGui.QFont("Times",20,QtGui.QFont.Bold)) self.button_cancel = QPushButton() self.button_cancel.setText("cancel") self.button_cancel.setFont(QtGui.QFont("Times",20,QtGui.QFont.Bold)) self.line_hello = QLineEdit() self.line_hello.setFont(QtGui.QFont("Times",20,QtGui.QFont.Bold)) ## predict label & text box self.label1 = QLabel() self.label1.setText("yes ") self.label1.setFont(QtGui.QFont("Times",20,QtGui.QFont.Bold)) self.label2 = QLabel("no ") self.label2.setFont(QtGui.QFont("Times",20,QtGui.QFont.Bold)) self.label3 = QLabel("up ") self.label3.setFont(QtGui.QFont("Times",20,QtGui.QFont.Bold)) self.label4 = QLabel("down ") self.label4.setFont(QtGui.QFont("Times",20,QtGui.QFont.Bold)) self.label5 = QLabel("left ") self.label5.setFont(QtGui.QFont("Times",20,QtGui.QFont.Bold)) self.label6 = QLabel("right ") self.label6.setFont(QtGui.QFont("Times",20,QtGui.QFont.Bold)) self.label7 = QLabel("on ") self.label7.setFont(QtGui.QFont("Times",20,QtGui.QFont.Bold)) self.label8 = QLabel("off ") self.label8.setFont(QtGui.QFont("Times",20,QtGui.QFont.Bold)) self.label9 = QLabel("stop ") self.label9.setFont(QtGui.QFont("Times",20,QtGui.QFont.Bold)) self.label10 = QLabel("go ") self.label10.setFont(QtGui.QFont("Times",20,QtGui.QFont.Bold)) self.labelfinal = QLabel("Result ") self.labelfinal.setFont(QtGui.QFont("Times",20,QtGui.QFont.Bold)) self.text1 = QLineEdit() self.text1.setFont(QtGui.QFont("Times",20,QtGui.QFont.Bold)) self.text2 = QLineEdit() self.text2.setFont(QtGui.QFont("Times",20,QtGui.QFont.Bold)) self.text3 = QLineEdit() self.text3.setFont(QtGui.QFont("Times",20,QtGui.QFont.Bold)) self.text4 = QLineEdit() self.text4.setFont(QtGui.QFont("Times",20,QtGui.QFont.Bold)) self.text5 = QLineEdit() self.text5.setFont(QtGui.QFont("Times",20,QtGui.QFont.Bold)) self.text6 = QLineEdit() self.text6.setFont(QtGui.QFont("Times",20,QtGui.QFont.Bold)) self.text7 = QLineEdit() self.text7.setFont(QtGui.QFont("Times",20,QtGui.QFont.Bold)) self.text8 = QLineEdit() self.text8.setFont(QtGui.QFont("Times",20,QtGui.QFont.Bold)) self.text9 = QLineEdit() self.text9.setFont(QtGui.QFont("Times",20,QtGui.QFont.Bold)) self.text10 = QLineEdit() self.text10.setFont(QtGui.QFont("Times",20,QtGui.QFont.Bold)) self.textfinal = QLineEdit() self.textfinal.setFont(QtGui.QFont("Times",20,QtGui.QFont.Bold)) form_layout = QFormLayout() form_layout.addRow(self.button_hello, self.line_hello) ## predict label form_layout.addRow(self.label1, self.text1) form_layout.addRow(self.label2, self.text2) form_layout.addRow(self.label3, self.text3) form_layout.addRow(self.label4, self.text4) form_layout.addRow(self.label5, self.text5) form_layout.addRow(self.label6, self.text6) form_layout.addRow(self.label7, self.text7) form_layout.addRow(self.label8, self.text8) form_layout.addRow(self.label9, self.text9) form_layout.addRow(self.label10, self.text10) form_layout.addRow(self.labelfinal, self.textfinal) form_layout.addRow(self.button_cancel) h_layout = QVBoxLayout() h_layout.addLayout(form_layout) self.setLayout(h_layout) self.button_hello.clicked.connect(self.hello) self.button_cancel.clicked.connect(self.cancel)
class SolverSettingsGroupBox(QGroupBox): def __init__(self, preferences): super(SolverSettingsGroupBox, self).__init__() self.setTitle('Solver Options') self.setAlignment(Qt.AlignLeft) self.setStyleSheet( 'GroupBox::title{subcontrol-origin: margin; subcontrol-position: top left;}' ) self.create_widgets() self.set_data(preferences) self.style_widgets() self.create_layout() self.create_signals() def create_widgets(self): self.op_method_label = QLabel('Minimisation Algorithm: ') self.op_method_input = QComboBox() # Default is to use limited-memory BFGS code for optimising rho # See http://users.iems.northwestern.edu/~nocedal/lbfgsb.html for details self.op_method_input.insertItem(0, 'L-BFGS-B') self.op_method_input.insertItem(1, 'SLSQP') self.op_method_input.insertItem(2, 'COBYLA') _app_url = '"https://github.com/bjheinen/LiquidDiffract#density-ρ-refinement"' _text = (f'<a href={_app_url}><span style="color: #0c0263;"><span ' f'lang="zxx"><u>More information...</u></span></span></a>') self.solver_info_link = QLabel(_text) self.solver_info_link.setOpenExternalLinks(True) self.disp_label = QLabel('Output convergence information? ') self.disp_check = QCheckBox() self.maxiter_label = QLabel('Maximum number of iterations: ') self.maxiter_input = QLineEdit() # L-BFGS-B specific options self.maxfun_label = QLabel('Maximum number of function evaluations: ') self.maxfun_input = QLineEdit() self.ftol_label = QLabel('Function convergence limit (ftol): ') self.ftol_input = QLineEdit() # gtol not in slsqp self.gtol_label = QLabel('Gradient convergence limit (gtol): ') self.gtol_input = QLineEdit() self.hline = QFrame() self.hline.setFrameShape(QFrame.HLine) self.hline.setFrameShadow(QFrame.Sunken) self.hline.setObjectName('hline') def set_data(self, preferences): self.op_method_input.setCurrentText(preferences['op_method']) _min_options = preferences['minimisation_options'] self.disp_check.setChecked(_min_options['disp']) self.maxiter_input.setText(np.str(_min_options['maxiter'])) self.ftol_input.setText(np.str(_min_options['ftol'])) # Handle missing maxfun/gtol if op_method!='L-BFGS-B' try: self.maxfun_input.setText(np.str(_min_options['maxfun'])) self.gtol_input.setText(np.str(_min_options['gtol'])) except KeyError: pass def style_widgets(self): self.op_method_label.setAlignment(Qt.AlignVCenter | Qt.AlignLeft) self.op_method_label.setToolTip('Solver to use when refining density.') self.solver_info_link.setAlignment(Qt.AlignVCenter | Qt.AlignLeft) self.disp_label.setAlignment(Qt.AlignVCenter | Qt.AlignLeft) self.disp_label.setToolTip( 'Print solver specific convergence messages?') self.maxiter_label.setAlignment(Qt.AlignVCenter | Qt.AlignLeft) self.maxiter_input.setAlignment(Qt.AlignRight) self.maxiter_input.setValidator(QIntValidator()) self.maxiter_input.setMaximumWidth(70) self.maxfun_label.setAlignment(Qt.AlignVCenter | Qt.AlignLeft) self.maxfun_input.setAlignment(Qt.AlignRight) self.maxfun_input.setValidator(QIntValidator()) self.maxfun_input.setMaximumWidth(70) self.ftol_label.setAlignment(Qt.AlignVCenter | Qt.AlignLeft) _tooltip = ('The function convergence limit is the precision goal for ' 'the function value in the stopping criterion. \nFor the ' 'L-BFGS-B method the iteration stops when ' '(f^k - f^{k+1})/max{|f^k|,|f^{k+1}|,1} <= ftol). \n' 'For the COBYLA method ftol is a lower bound on the trust ' 'region and is not precisely guaranteed.') self.ftol_label.setToolTip(_tooltip) self.ftol_input.setAlignment(Qt.AlignRight) self.ftol_input.setValidator(QDoubleValidator()) self.ftol_input.setMaximumWidth(70) self.gtol_label.setAlignment(Qt.AlignVCenter | Qt.AlignLeft) _tooltip = ('Gradient limit for stopping criterion. \nThe iteration ' 'will stop when max{|proj g_i | i = 1, ..., n} <= gtol \n' 'where pg_i is the i-th component of ' 'the projected gradient.') self.gtol_label.setToolTip(_tooltip) self.gtol_input.setAlignment(Qt.AlignRight) self.gtol_input.setValidator(QDoubleValidator()) self.gtol_input.setMaximumWidth(70) if self.op_method_input.currentText() != 'L-BFGS-B': self.maxfun_label.setEnabled(False) self.maxfun_input.setEnabled(False) self.gtol_label.setEnabled(False) self.gtol_input.setEnabled(False) def create_layout(self): self.main_layout = QVBoxLayout() self.main_layout.setContentsMargins(20, 10, 20, 7) self.main_layout.setSpacing(25) self.grid_layout = QGridLayout() self.grid_layout.setSpacing(15) self.grid_layout.addWidget(self.op_method_label, 0, 0) self.grid_layout.addWidget(self.op_method_input, 0, 1) self.grid_layout.addWidget(self.solver_info_link, 1, 0) self.grid_layout.addWidget(self.hline, 2, 0) self.grid_layout.addWidget(self.disp_label, 3, 0) self.grid_layout.addWidget(self.disp_check, 3, 1) self.grid_layout.addWidget(self.maxiter_label, 4, 0) self.grid_layout.addWidget(self.maxiter_input, 4, 1) self.grid_layout.addWidget(self.maxfun_label, 5, 0) self.grid_layout.addWidget(self.maxfun_input, 5, 1) self.grid_layout.addWidget(self.ftol_label, 6, 0) self.grid_layout.addWidget(self.ftol_input, 6, 1) self.grid_layout.addWidget(self.gtol_label, 7, 0) self.grid_layout.addWidget(self.gtol_input, 7, 1) self.main_layout.addLayout(self.grid_layout) self.setLayout(self.main_layout) def create_signals(self): self.op_method_input.currentIndexChanged.connect( self.op_method_changed) def op_method_changed(self): if self.op_method_input.currentText() == 'L-BFGS-B': self.maxfun_label.setEnabled(True) self.maxfun_input.setEnabled(True) self.gtol_label.setEnabled(True) self.gtol_input.setEnabled(True) # Set default values when the method is changed self.disp_check.setChecked(False) self.maxiter_input.setText('15000') self.maxfun_input.setText('15000') self.ftol_input.setText('2.22e-8') self.gtol_input.setText('1e-10') elif self.op_method_input.currentText() == 'SLSQP': self.maxfun_label.setEnabled(False) self.maxfun_input.setEnabled(False) self.gtol_label.setEnabled(False) self.gtol_input.setEnabled(False) # Set default values when the method is changed self.disp_check.setChecked(False) self.maxiter_input.setText('200') self.ftol_input.setText('1e-6') elif self.op_method_input.currentText() == 'COBYLA': self.maxfun_label.setEnabled(False) self.maxfun_input.setEnabled(False) self.gtol_label.setEnabled(False) self.gtol_input.setEnabled(False) # Set default values when the method is changed self.disp_check.setChecked(False) self.maxiter_input.setText('1000') self.ftol_input.setText('1e-7') else: pass
class _BasePrompt(QWidget): """Base class for all prompts.""" KEY_MODE = usertypes.KeyMode.prompt def __init__(self, question, parent=None): super().__init__(parent) self.question = question self._vbox = QVBoxLayout(self) self._vbox.setSpacing(15) self._key_grid = None def __repr__(self): return utils.get_repr(self, question=self.question, constructor=True) def _init_texts(self, question): assert question.title is not None, question title = '<font size="4"><b>{}</b></font>'.format( html.escape(question.title)) title_label = QLabel(title, self) self._vbox.addWidget(title_label) if question.text is not None: # Not doing any HTML escaping here as the text can be formatted text_label = QLabel(question.text) text_label.setWordWrap(True) text_label.setTextInteractionFlags(Qt.TextSelectableByMouse) self._vbox.addWidget(text_label) def _init_key_label(self): assert self._key_grid is None, self._key_grid self._key_grid = QGridLayout() self._key_grid.setVerticalSpacing(0) all_bindings = config.key_instance.get_reverse_bindings_for( self.KEY_MODE.name) labels = [] for cmd, text in self._allowed_commands(): bindings = all_bindings.get(cmd, []) if bindings: binding = None preferred = ['<enter>', '<escape>'] for pref in preferred: if pref in bindings: binding = pref if binding is None: binding = bindings[0] key_label = QLabel('<b>{}</b>'.format(html.escape(binding))) text_label = QLabel(text) labels.append((key_label, text_label)) for i, (key_label, text_label) in enumerate(labels): self._key_grid.addWidget(key_label, i, 0) self._key_grid.addWidget(text_label, i, 1) spacer = QSpacerItem(0, 0, QSizePolicy.Expanding) self._key_grid.addItem(spacer, 0, 2) self._vbox.addLayout(self._key_grid) def _check_save_support(self, save): if save: raise UnsupportedOperationError("Saving answers is only possible " "with yes/no prompts.") def accept(self, value=None, save=False): raise NotImplementedError def download_open(self, cmdline, pdfjs): """Open the download directly if this is a download prompt.""" utils.unused(cmdline) utils.unused(pdfjs) raise UnsupportedOperationError def item_focus(self, _which): """Switch to next file item if this is a filename prompt..""" raise UnsupportedOperationError def _allowed_commands(self): """Get the commands we could run as response to this message.""" raise NotImplementedError
class LocationRecorder(QWidget): def __init__(self): super(LocationRecorder, self).__init__() self.init_ui() self.robot_record_pose = None self.option = None self.tf_listener = tf.TransformListener() self.show() def init_ui(self): self.layout = QVBoxLayout() self.option_layout = QHBoxLayout() self.up_stair_checkbox = QCheckBox("上台阶") self.down_stair_checkbox = QCheckBox("下台阶") self.crawl_checkbox = QCheckBox("匍匐") self.speed_up_checkbox = QCheckBox("加速") self.option_layout.addWidget(self.up_stair_checkbox) self.option_layout.addWidget(self.down_stair_checkbox) self.option_layout.addWidget(self.speed_up_checkbox) self.option_layout.addWidget(self.crawl_checkbox) self.order_layout = QHBoxLayout() self.order_layout.addWidget(QLabel("位点编号:")) self.order_edit = QLineEdit("") self.order_layout.addWidget(self.order_edit) self.text_content = QTextEdit() self.text_content.setEnabled(False) self.record_layout = QHBoxLayout() self.receive_button = QPushButton("获取位点") self.record_button = QPushButton("记录位点") self.record_layout.addWidget(self.receive_button) self.record_layout.addWidget(self.record_button) self.layout.addLayout(self.option_layout) self.layout.addLayout(self.order_layout) self.layout.addWidget(self.text_content) self.layout.addLayout(self.record_layout) self.setLayout(self.layout) self.record_button.clicked.connect(self.record) self.receive_button.clicked.connect(self.receive) def record(self): order = self.order_edit.text() try: order = int(order) except: return new_record = { "order": order, "robot_pose": self.robot_record_pose, "option": self.option, } data_dir = str(os.path.dirname(os.path.abspath(__file__))) + "/../data" os.system("mkdir -p " + data_dir) data_dir = data_dir + "/%d.json" with open(data_dir % order, "w+") as out: json.dump(new_record, out, indent=4) def listen_tf(self): try: (pos, ori) = self.tf_listener.lookupTransform("map", "base_link", rospy.Duration(0.0)) msg_dict = { "pos_x": pos[0], "pos_y": pos[1], "pos_z": pos[2], "ori_x": ori[0], "ori_y": ori[1], "ori_z": ori[2], "ori_w": ori[3], } self.robot_record_pose = msg_dict return True except tf.Exception as e: print "listen to tf failed" return False def update_option(self): self.option = {} self.option["up_stair"] = self.up_stair_checkbox.isChecked() self.option["down_stair"] = self.down_stair_checkbox.isChecked() self.option["speed_up"] = self.speed_up_checkbox.isChecked() self.option["crawl"] = self.crawl_checkbox.isChecked() def receive(self): while not self.listen_tf(): rospy.sleep(1.0) self.update_option() display_msg = "Robot:\n" + json.dumps(self.robot_record_pose, indent=4) + "\n" display_msg += "Option:\n" + json.dumps(self.option, indent=4) + "\n" self.text_content.setText(display_msg)
class GlobalMinSettingsGroupBox(QGroupBox): def __init__(self, preferences): super(GlobalMinSettingsGroupBox, self).__init__() self.setTitle('Global Minimisation?') self.setAlignment(Qt.AlignLeft) self.setStyleSheet( 'GroupBox::title{subcontrol-origin: margin; subcontrol-position: top left;}' ) self.setCheckable(True) self.create_widgets() self.set_data(preferences) self.style_widgets() self.create_layout() def create_widgets(self): self.disp_label = QLabel('Output convergence information? ') self.disp_check = QCheckBox() self.niter_basin_label = QLabel('Number of basin-hopping iterations: ') self.niter_basin_input = QLineEdit() self.temp_basin_label = QLabel( 'Basin-hopping temperature parameter (T): ') self.temp_basin_input = QLineEdit() self.stepsize_basin_label = QLabel( 'Initial step size for basin-hopping algorithm: ') self.stepsize_basin_input = QLineEdit() self.interval_basin_label = QLabel('Update interval: ') self.interval_basin_input = QLineEdit() def set_data(self, preferences): self.setChecked(preferences['global_minimisation']) _global_min_options = preferences['global_min_options'] self.disp_check.setChecked(_global_min_options['disp']) self.niter_basin_input.setText(np.str(_global_min_options['niter'])) self.temp_basin_input.setText(np.str(_global_min_options['T'])) self.stepsize_basin_input.setText( np.str(_global_min_options['stepsize'])) self.interval_basin_input.setText( np.str(_global_min_options['interval'])) def style_widgets(self): self.disp_label.setAlignment(Qt.AlignVCenter | Qt.AlignLeft) self.disp_label.setToolTip('Print basin-hopping status messages?') self.niter_basin_label.setAlignment(Qt.AlignVCenter | Qt.AlignLeft) self.niter_basin_input.setAlignment(Qt.AlignRight) self.niter_basin_input.setValidator(QIntValidator()) self.niter_basin_input.setMaximumWidth(70) self.temp_basin_label.setAlignment(Qt.AlignVCenter | Qt.AlignLeft) self.temp_basin_input.setAlignment(Qt.AlignRight) self.temp_basin_input.setValidator(QDoubleValidator()) self.temp_basin_input.setMaximumWidth(70) self.stepsize_basin_label.setAlignment(Qt.AlignVCenter | Qt.AlignLeft) self.stepsize_basin_input.setAlignment(Qt.AlignRight) self.stepsize_basin_input.setValidator(QDoubleValidator()) self.stepsize_basin_input.setMaximumWidth(70) self.interval_basin_label.setAlignment(Qt.AlignVCenter | Qt.AlignLeft) self.interval_basin_input.setAlignment(Qt.AlignRight) self.interval_basin_input.setValidator(QIntValidator()) self.interval_basin_input.setMaximumWidth(70) def create_layout(self): self.main_layout = QVBoxLayout() self.main_layout.setContentsMargins(20, 10, 20, 7) self.main_layout.setSpacing(25) self.grid_layout = QGridLayout() self.grid_layout.setSpacing(15) self.grid_layout.addWidget(self.disp_label, 0, 0) self.grid_layout.addWidget(self.disp_check, 0, 1) self.grid_layout.addWidget(self.niter_basin_label, 1, 0) self.grid_layout.addWidget(self.niter_basin_input, 1, 1) self.grid_layout.addWidget(self.temp_basin_label, 2, 0) self.grid_layout.addWidget(self.temp_basin_input, 2, 1) self.grid_layout.addWidget(self.stepsize_basin_label, 3, 0) self.grid_layout.addWidget(self.stepsize_basin_input, 3, 1) self.grid_layout.addWidget(self.interval_basin_label, 4, 0) self.grid_layout.addWidget(self.interval_basin_input, 4, 1) self.main_layout.addLayout(self.grid_layout) self.setLayout(self.main_layout)
class SearchMSTitle(QMdiSubWindow): def __init__(self, main, type): """ Search movie or series by title. :param main: Reference for main windows. :param type: String if is "movie" then search for movie if not search by "series". """ super(SearchMSTitle, self).__init__() self.session = DB.get_session() self.type = type self.main = main self.row_select = -1 if self.type == 'movie': self.obj = self.session.query(Movie).order_by(Movie.name) name = texts.movie_p else: self.obj = self.session.query(Series).order_by(Series.name) name = texts.series_p windows_title = texts.search + ' ' + name + ' ' + texts.for_ \ + ' ' + texts.title_p self.setWindowTitle(windows_title) self.width = int(0.9 * main.frameSize().width()) self.height = int(0.9 * main.frameSize().height()) self.setGeometry(0, 0, self.width, self.height) self.subwindow = QWidget() p = self.palette() p.setColor(self.backgroundRole(), QColor(230, 230, 250)) self.setPalette(p) self.setWidget(self.subwindow) self.vbox_main = QVBoxLayout(self.subwindow) self.vbox_main.setContentsMargins(20, 20, 20, 20) # Title self.lb_title = QLabel(texts.title_s) self.lb_title.setMaximumSize(QSize(100, 25)) self.cb_title = cb_create() self.cb_title.addItem('', 0) for ms in self.obj: self.cb_title.addItem(ms.name, ms.id) # Words text = texts.or_s + ' ' + texts.with_the_p + ' ' + texts.term_p self.lb_term = QLabel(text) self.le_term = le_create(30, texts.with_term_tt) self.le_term.setPlaceholderText('pressione enter') # # HBoxSearch self.hbox_search = hbox_create( [self.lb_title, self.cb_title, self.lb_term, self.le_term]) spacer = QSpacerItem(40, 20, QSizePolicy.Expanding, QSizePolicy.Minimum) self.hbox_search.addItem(spacer) self.vbox_main.addLayout(self.hbox_search) # total self.lb_total = QLabel(texts.lb_total) self.le_total = le_create(255) self.le_total.setMaximumWidth(100) # Buttons self.pb_clear = pb_create(texts.pb_clear, 11, 30) self.pb_clear.setMaximumWidth(100) self.pb_clear.setShortcut('Ctrl+L') # self.pb_clear.clicked.connect(self.clear) self.pb_leave = pb_create(texts.pb_leave, 11, 30) self.pb_leave.setMaximumWidth(100) self.pb_leave.setShortcut('Ctrl+Q') self.pb_leave.clicked.connect(self.close) # Hbox_result self.hbox_result = hbox_create( [self.lb_total, self.le_total, self.pb_clear, self.pb_leave]) spacer = QSpacerItem(40, 20, QSizePolicy.Expanding, QSizePolicy.Minimum) self.hbox_result.addItem(spacer) self.vbox_main.addLayout(self.hbox_result) # Table self.table = QTableWidget() self.table.setObjectName('table-search') self.rows = 0 self.clear_table() self.set_table(self.obj) self.vbox_main.addWidget(self.table) self.cb_title.currentIndexChanged.connect(self.query_title) self.le_term.editingFinished.connect(self.query_term) # Clear Table def clear_table(self): """ Clear all tables values. """ self.table.clear() self.table.setRowCount(0) self.table.setColumnCount(6) self.rows = 0 if self.type == 'movie': headers = [ texts.title_s, texts.original_title_s, texts.lb_time, texts.media_s, texts.year_s, 'id' ] else: headers = [ texts.title_s, texts.original_title_s, texts.season_p, texts.media_s, texts.year_s, 'id' ] self.table.setHorizontalHeaderLabels(headers) col_width = self.width - 70 self.table.setColumnWidth(0, 0.35 * col_width) self.table.setColumnWidth(1, 0.35 * col_width) self.table.setColumnWidth(2, 0.10 * col_width) self.table.setColumnWidth(3, 0.10 * col_width) self.table.setColumnWidth(4, 0.10 * col_width) self.table.setColumnWidth(5, 0) self.table.verticalHeader().setVisible(False) self.table.setStyleSheet('background-color: #FFFFFF;') self.table.setSortingEnabled(True) # Resize Event def resizeEvent(self, event): """ Resize actors and character combobox in table cast if windows resize. :param event: Window. """ self.width = event.size().width() col_width = self.width - 70 self.table.setColumnWidth(0, 0.35 * col_width) self.table.setColumnWidth(1, 0.35 * col_width) self.table.setColumnWidth(2, 0.10 * col_width) self.table.setColumnWidth(3, 0.10 * col_width) self.table.setColumnWidth(4, 0.10 * col_width) self.table.setColumnWidth(5, 0) # Important don't delete it QMdiSubWindow.resizeEvent(self, event) # View Movie def view_obj(self, row, col): """ When clicked a cell table who has title show the html view of movie. :param row: The number of the row on which the cell was clicked. :param col: The number of the column on which the cell was clicked. """ if self.row_select != row and col == 0: obj_id = self.table.item(row, 5).text() if self.type == 'movie': obj = self.session.query(Movie).get(obj_id) else: obj = self.session.query(Series).get(obj_id) if obj.view: self.main.view_html(obj.view, obj.name) self.row_select = row # Set Table def set_table(self, objs): """ Set table with all movies. :param query: The movies values. """ self.clear_table() for o in objs: self.table.insertRow(self.rows) self.table.setItem(self.rows, 0, QTableWidgetItem(o.name)) font = QFont() font.setUnderline(True) self.table.item(self.rows, 0).setForeground(QColor(55, 34, 243)) self.table.item(self.rows, 0).setFont(font) self.table.setItem(self.rows, 1, QTableWidgetItem(o.original_name)) if self.type == 'movie': self.table.setItem(self.rows, 2, QTableWidgetItem(o.time)) else: self.table.setItem(self.rows, 2, QTableWidgetItem(o.seasons)) if o.media_id: self.table.setItem(self.rows, 3, QTableWidgetItem(o.media.name)) else: self.table.setItem(self.rows, 3, QTableWidgetItem('')) self.table.setItem(self.rows, 4, QTableWidgetItem(o.year)) self.table.setItem(self.rows, 5, QTableWidgetItem(str(o.id))) for i in range(6): if self.table.item(self.rows, i): self.table.item(self.rows, i).setFlags(Qt.ItemIsSelectable | Qt.ItemIsEnabled) self.table.cellDoubleClicked.connect(self.view_obj) self.rows += 1 self.table.setAlternatingRowColors(True) self.table.setStyleSheet( "alternate-background-color: #F0FAE4;; background-color: #FFFFFF;") self.le_total.setText(str(self.rows)) # Set Query Title def set_table_title(self, obj): """ Set table with movies values search in database. :param obj: The movies values from a database search. """ self.clear_table() self.table.insertRow(self.rows) self.table.setItem(self.rows, 0, QTableWidgetItem(obj.name)) font = QFont() font.setUnderline(True) self.table.item(self.rows, 0).setForeground(QColor(55, 34, 243)) self.table.item(self.rows, 0).setFont(font) self.table.setItem(self.rows, 1, QTableWidgetItem(obj.original_name)) if self.type == 'movie': self.table.setItem(self.rows, 2, QTableWidgetItem(obj.time)) else: self.table.setItem(self.rows, 2, QTableWidgetItem(obj.seasons)) if obj.media: self.table.setItem(self.rows, 3, QTableWidgetItem(obj.media.name)) else: self.table.setItem(self.rows, 3, QTableWidgetItem('')) self.table.setItem(self.rows, 4, QTableWidgetItem(obj.year)) self.table.setItem(self.rows, 5, QTableWidgetItem(str(obj.id))) self.table.cellClicked.connect(self.view_obj) self.rows += 1 self.table.setAlternatingRowColors(True) self.table.setStyleSheet( "alternate-background-color: #F0FAE4; background-color: #ffffff;") self.le_total.setText(str(self.rows)) # Query Title def query_title(self): """ Search movie by selected title in QCombobox. """ id, name = get_combobox_info(self.cb_title) if self.type == 'movie': query = self.session.query(Movie).get(id) else: query = self.session.query(Series).get(id) self.set_table_title(query) def query_term(self): """ Search movie by words in title. """ words = self.le_term.text().split() queries = [] for word in words: word = '%{0}%'.format(word) if self.type == 'movie': query = self.session.query(Movie)\ .filter(Movie.name.ilike(word)).all() else: query = self.session.query(Series) \ .filter(Series.name.ilike(word)).all() queries += query self.set_table(queries) def clear(self): """ Clear all values in windows. """ self.cb_title.currentIndexChanged.disconnect() self.cb_title.setCurrentIndex(0) self.clear_table() self.set_table(self.obj) self.cb_title.currentIndexChanged.connect(self.query_title) # Close Event def closeEvent(self, event): self.session.close()
class DataSettingsGroupBox(QGroupBox): def __init__(self, preferences): super(DataSettingsGroupBox, self).__init__() self.setTitle('Data Treatment Options') self.setAlignment(Qt.AlignLeft) self.setStyleSheet( 'GroupBox::title{subcontrol-origin: margin; subcontrol-position: top left;}' ) self.create_widgets() self.set_data(preferences) self.style_widgets() self.create_layout() def create_widgets(self): self.data_units_label = QLabel('Data file Q units: ') self.data_units_input = QComboBox() self.data_units_input.insertItem(0, '1/Angstroms') self.data_units_input.insertItem(1, '1/nano-metres') self.smoothing_label = QLabel( 'Savitsky-golay filter parameters (Data smoothing): ') self.window_length_label = QLabel('Window size') self.window_length_input = QLineEdit() self.poly_order_label = QLabel('Poly order') self.poly_order_input = QLineEdit() self.rescale_AL_label = QLabel( 'Plot rescaled Ashcroft-Langreth S(Q) & g(r)') self.rescale_AL_input = QCheckBox() self.fft_label = QLabel('FFT Options:') self.fft_N_label = QLabel( '<b><i>N</i></b> | Size of padded array for FFT = 2^N: ') self.fft_N_input = QSpinBox() def set_data(self, preferences): self.data_units_input.setCurrentIndex(preferences['data_units']) self.window_length_input.setText(np.str(preferences['window_length'])) self.poly_order_input.setText(np.str(preferences['poly_order'])) self.rescale_AL_input.setChecked(preferences['rescale_AL']) self.fft_N_input.setValue(preferences['fft_N']) def style_widgets(self): self.data_units_label.setAlignment(Qt.AlignVCenter | Qt.AlignLeft) self.data_units_input.setMaximumWidth(100) self.smoothing_label.setAlignment(Qt.AlignVCenter | Qt.AlignLeft) self.window_length_label.setAlignment(Qt.AlignVCenter | Qt.AlignLeft) self.window_length_input.setAlignment(Qt.AlignRight) self.window_length_input.setValidator(QIntValidator()) self.window_length_input.setMaximumWidth(70) self.poly_order_label.setAlignment(Qt.AlignVCenter | Qt.AlignLeft) self.poly_order_input.setAlignment(Qt.AlignRight) self.poly_order_input.setValidator(QIntValidator()) self.poly_order_input.setMaximumWidth(70) self.rescale_AL_label.setAlignment(Qt.AlignVCenter | Qt.AlignLeft) self.fft_label.setAlignment(Qt.AlignVCenter | Qt.AlignLeft) self.fft_N_label.setAlignment(Qt.AlignVCenter | Qt.AlignLeft) self.fft_N_input.setAlignment(Qt.AlignRight) self.fft_N_input.setRange(1, 20) self.fft_N_input.setMaximumWidth(70) def create_layout(self): self.main_layout = QVBoxLayout() self.main_layout.setContentsMargins(20, 10, 20, 7) self.main_layout.setSpacing(25) self.grid_layout = QGridLayout() self.grid_layout.setSpacing(15) self.grid_layout.addWidget(self.data_units_label, 0, 0) self.grid_layout.addWidget(self.data_units_input, 0, 1) self.grid_layout.addWidget(self.smoothing_label, 1, 0) self.grid_layout.addWidget(self.window_length_label, 2, 0) self.grid_layout.addWidget(self.window_length_input, 2, 1) self.grid_layout.addWidget(self.poly_order_label, 3, 0) self.grid_layout.addWidget(self.poly_order_input, 3, 1) self.grid_layout.addWidget(self.rescale_AL_label, 4, 0) self.grid_layout.addWidget(self.rescale_AL_input, 4, 1) self.grid_layout.addWidget(self.fft_label, 5, 0) self.grid_layout.addWidget(self.fft_N_label, 6, 0) self.grid_layout.addWidget(self.fft_N_input, 6, 1) self.main_layout.addLayout(self.grid_layout) self.setLayout(self.main_layout)