class ValueEdit(QWidget): def __init__(self, title, unit, number_type='double', parent=None): super(ValueEdit, self).__init__(parent) self.title = QLabel(title) self.title.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed) self.unit = QLabel(unit) self.unit.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed) if number_type == 'double': self.edit = QDoubleSpinBox() elif number_type == 'int': self.edit = QSpinBox() else: raise ValueError( 'Editor can either be for double or integer values') self.edit.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Fixed) self.edit.setKeyboardTracking(False) self.edit.setAlignment(Qt.AlignRight) self.edit.setButtonSymbols(QAbstractSpinBox.NoButtons) def set_range_decimals(self, min, max, decimals=3): self.edit.setRange(min, max) if isinstance(self.edit, QDoubleSpinBox): self.edit.setDecimals(decimals) def set_single_step_size(self, step=.1): self.edit.setSingleStep(step) def value(self): return self.edit.value() @Slot(float) def setValue(self, value): self.edit.setValue(value)
class StatInitDialog(QDialog): def __init__(self, stats): QDialog.__init__(self) self.stats = stats self.setWindowTitle("Initialization") self.setMinimumWidth(200) self.layout = QFormLayout() self.kill_spinbox = QSpinBox() self.death_spinbox = QSpinBox() self.kill_spinbox.setRange(0,1000000) self.death_spinbox.setRange(0,1000000) self.layout.addRow(QLabel("Kills"), self.kill_spinbox) self.layout.addRow(QLabel("Deaths"), self.death_spinbox) self.buttonBox = QDialogButtonBox(QDialogButtonBox.Cancel | QDialogButtonBox.Ok) self.layout.addWidget(self.buttonBox) self.setLayout(self.layout) self.buttonBox.accepted.connect(self.ok) self.buttonBox.rejected.connect(self.cancel) def ok(self): kills = self.kill_spinbox.value() deaths = self.death_spinbox.value() self.stats.set_initial_stats(kills, deaths) self.accept() def cancel(self): print("Cancelling the stat initialization") self.reject()
def add_row(self, grid, choice, name): grid.addWidget(QLabel(str(name)), 0) spin_box = QSpinBox() spin_box.setRange(0, 10) cb = partial(self.spin_box_changed, choice, name) spin_box.valueChanged.connect(cb) if choice not in self.spin_boxes.keys(): self.spin_boxes[choice] = {name: spin_box} else: self.spin_boxes[choice].update({name: spin_box}) slider = QSlider(Qt.Orientation.Horizontal) slider.setTickPosition(QSlider.TicksBelow) slider.setMaximum(10) slider.setPageStep(1) slider.setTracking(True) cb = partial(self.slider_changed, choice, name) slider.valueChanged.connect(cb) if choice not in self.sliders.keys(): self.sliders[choice] = {name: slider} else: self.sliders[choice].update({name: slider}) grid.addWidget(spin_box, 1) grid.addWidget(slider, 2)
def _layout(self): layout = QFormLayout(self) self.setLayout(layout) tooltip_label = QLabel("Display tooltips as", self) tooltip_field = QComboBox(self) tooltip_field.insertItem(0, "Disabled") tooltip_field.insertItem(1, "Notification") # XXX: Check support tooltip_field.insertItem(2, "Cursor tooltip") tooltip_field.currentIndexChanged.connect(self.preview_tooltip) layout.addRow(tooltip_label, tooltip_field) border_field = QCheckBox("Styled window border", self) border_field.setDisabled(sys.platform == "darwin") border_field.setChecked(sys.platform != "darwin") layout.addRow(None, border_field) # I think this doesn't belong to "Interface" # either rename it to settings or make separate game tab capturei_label = QLabel("Capture interval", self) capturei_layout = QHBoxLayout() capturei_field = QSpinBox(self) capturei_field.setRange(100, 2000) capturei_field.setSingleStep(100) capturei_field.setValue(100) capturei_layout.addWidget(capturei_field, 1) capturei_unit = QLabel("ms", self) capturei_layout.addWidget(capturei_unit, 0) layout.addRow(capturei_label, capturei_layout)
class ToolsWidget(QWidget): def __init__(self, parent=None): super(ToolsWidget, self).__init__(parent) self.initUI() pass def initUI(self): self.contour_epsilon=QSpinBox() self.generate_contour=QPushButton(); self.generate_contour.setText("generate") self.contour_epsilon.setRange(3,20) self.contour_epsilon.setValue(10) l1=QHBoxLayout() l2=QVBoxLayout() self.b2=QPushButton("插点"); self.b3=QPushButton(); self.b4=QPushButton(); l1.addWidget(self.contour_epsilon) l1.addSpacing(30) l1.addWidget(self.generate_contour) l1.setStretchFactor(self.contour_epsilon,1) l1.setStretchFactor(self.generate_contour,1) l2.addLayout(l1) l2.addWidget(self.b2) l2.addWidget(self.b3) l2.addWidget(self.b4) self.setLayout(l2) #面板属性设置 # self.resize(200,800) # self.setAutoFillBackground(True) # palette = QPalette() # palette.setColor(QPalette.Background, QColor(255, 0, 0)) pass
class LabeledSpinBox(QWidget): valueChanged = Signal(int) def __init__(self, label_string, minimum=1, maximum=100, starting_value=0): super(LabeledSpinBox, self).__init__() self.spinbox = QSpinBox() self.spinbox.setRange(minimum, maximum) self.spinbox.setSuffix('/{}'.format(maximum)) self.spinbox.setValue(starting_value) self.spinbox.valueChanged.connect(self._valueChanged) self.label = QLabel() self.label.setText(label_string) SpinBoxLayout = QHBoxLayout(self) SpinBoxLayout.addWidget(self.label) SpinBoxLayout.addWidget(self.spinbox) def setValue(self, value, quiet=False): if quiet: self.spinbox.blockSignals(True) self.spinbox.setValue(value) self.spinbox.blockSignals(False) else: self.spinbox.setValue(value) def value(self): return self.spinbox.value() def setRange(self, minimum, maximum): self.spinbox.setRange(minimum, maximum) self.spinbox.setSuffix("/{}".format(maximum)) def _valueChanged(self, value): self.valueChanged.emit(value)
def initializePage(self): self.parent_wizard.next_button.setDisabled(True) self.sliders = [] self.spin_boxes = [] # FIXME: backing too much the returning breaks this # Seems to remember values, but visually breaks for i, name in enumerate(self.collection()): self.grid.addWidget(QLabel(str(name)), i, 0) spin_box = QSpinBox() spin_box.setRange(0, 10) cb = partial(self.spin_box_changed, i) spin_box.valueChanged.connect(cb) self.spin_boxes.append(spin_box) slider = QSlider(Qt.Orientation.Horizontal) slider.setTickPosition(QSlider.TicksBelow) slider.setMaximum(10) slider.setPageStep(1) slider.setTracking(True) cb = partial(self.slider_changed, i) slider.valueChanged.connect(cb) self.sliders.append(slider) self.grid.addWidget(spin_box, i, 1) self.grid.addWidget(slider, i, 2) self.fix_tab_order() for idx, criterion in enumerate(self.collection()): value = self.parent_wizard.main_parent.matrix.df.loc['Weight', criterion] if str(value) != 'nan': self.spin_boxes[idx].setValue(value)
class ChangeChannel(QDialog): change_channel = Signal(int, bool) """Allows the user to change the channel.""" def __init__(self): super(ChangeChannel, self).__init__() self.setModal(True) self.stop_recording = QCheckBox(self) self.channel = QSpinBox(self) self.channel.setRange(0, 9999) self.button_boxes = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel) self.button_boxes.accepted.connect(self.accepted) self.button_boxes.rejected.connect(lambda: self.close()) self.layout = QFormLayout(self) self.layout.addRow("Channel:", self.channel) self.layout.addRow("Stop recording if in progress:", self.stop_recording) self.layout.addRow(self.button_boxes) self.setWindowTitle("Change TiVo channel") self.resize(320, 100) @Slot() def accepted(self): self.change_channel.emit(self.channel.value(), self.stop_recording.isChecked()) self.close()
def __init__(self, target_properties: List[str], parent=None): super().__init__(parent) self.target_properties = target_properties self.target = None layout = QGridLayout() for i in range(0, 8): label = QLabel(text=_EDITOR_LABELS[i]) layout.addWidget(label, 0, i + 1) self.editors = [] for i in range(0, len(target_properties)): self.editors.append([]) label = QLabel(target_properties[i]) label.setFixedWidth(80) layout.addWidget(label, i + 1, 0) for j in range(0, 8): editor = QSpinBox() editor.setRange(-128, 127) editor.setMaximumWidth(60) layout.addWidget(editor, row=i + 1, column=j + 1) self.editors[-1].append(editor) editor.valueChanged.connect(lambda v=None, e=editor, r=i, c=j: self._on_edit(v, e, r, c)) self.setLayout(layout) self.setFixedHeight(200)
class ElaWidget(ToolWidget): def __init__(self, image, parent=None): super(ElaWidget, self).__init__(parent) params_layout = QHBoxLayout() params_layout.addWidget(QLabel(self.tr('Quality:'))) self.quality_spin = QSpinBox() self.quality_spin.setRange(0, 100) self.quality_spin.setSuffix(self.tr(' %')) self.quality_spin.valueChanged.connect(self.process) params_layout.addWidget(self.quality_spin) params_layout.addWidget(QLabel(self.tr('Scale:'))) self.scale_spin = QSpinBox() self.scale_spin.setRange(1, 100) self.scale_spin.valueChanged.connect(self.process) params_layout.addWidget(self.scale_spin) self.equalize_check = QCheckBox(self.tr('Equalized')) self.equalize_check.stateChanged.connect(self.process) params_layout.addWidget(self.equalize_check) params_layout.addStretch() default_button = QPushButton(self.tr('Default')) default_button.clicked.connect(self.default) params_layout.addWidget(default_button) self.image = image self.viewer = ImageViewer(self.image, self.image) self.default() self.process() main_layout = QVBoxLayout() main_layout.addLayout(params_layout) main_layout.addWidget(self.viewer) self.setLayout(main_layout) def process(self): equalize = self.equalize_check.isChecked() self.scale_spin.setEnabled(not equalize) start = time() quality = self.quality_spin.value() scale = self.scale_spin.value() compressed = compress_jpeg(self.image, quality) if not equalize: ela = cv.convertScaleAbs(cv.subtract(compressed, self.image), None, scale) else: ela = cv.merge([ cv.equalizeHist(c) for c in cv.split(cv.absdiff(compressed, self.image)) ]) self.viewer.update_processed(ela) self.info_message.emit( self.tr('Error Level Analysis = {}'.format(elapsed_time(start)))) def default(self): self.quality_spin.setValue(75) self.scale_spin.setValue(20)
class ParamSlider(QWidget): valueChanged = Signal(int) def __init__(self, interval, ticks=10, reset=0, suffix=None, label=None, bold=False, parent=None): super(ParamSlider, self).__init__(parent) self.slider = QSlider(Qt.Horizontal) self.slider.setRange(interval[0], interval[1]) self.slider.setTickPosition(QSlider.TicksBelow) self.slider.setTickInterval((interval[1] - interval[0] + 1) / ticks) self.slider.setSingleStep(1) self.slider.setPageStep(1) self.slider.setValue(reset) self.slider.mouseDoubleClickEvent = self.doubleClicked self.spin = QSpinBox() self.spin.setRange(interval[0], interval[1]) self.spin.setValue(reset) self.spin.setSuffix(suffix) self.spin.setFixedWidth(50) self.reset = reset self.slider.valueChanged.connect(self.spin.setValue) self.spin.valueChanged.connect(self.slider.setValue) self.slider.valueChanged.connect(self.valueChanged) layout = QHBoxLayout() if label is not None: lab = QLabel(label) modify_font(lab, bold=bold) layout.addWidget(lab) layout.addWidget(self.slider) layout.addWidget(self.spin) self.setLayout(layout) self.setMaximumWidth(200) def doubleClicked(self, _): self.slider.setValue(self.reset) self.spin.setValue(self.reset) def value(self): return self.slider.value() def setValue(self, value): self.spin.setValue(value) self.slider.setValue(value) self.valueChanged.emit(value) def sync(self): self.spin.setValue(self.slider.value()) self.slider.setValue(self.spin.value()) self.valueChanged.emit(self.slider.value())
class EchoWidget(ToolWidget): def __init__(self, image, parent=None): super(EchoWidget, self).__init__(parent) self.radius_spin = QSpinBox() self.radius_spin.setRange(1, 15) self.radius_spin.setSuffix(self.tr(' px')) self.radius_spin.setValue(2) self.radius_spin.setToolTip(self.tr('Laplacian filter radius')) self.contrast_spin = QSpinBox() self.contrast_spin.setRange(0, 100) self.contrast_spin.setSuffix(self.tr(' %')) self.contrast_spin.setValue(85) self.contrast_spin.setToolTip(self.tr('Output tonality compression')) self.gray_check = QCheckBox(self.tr('Grayscale')) self.gray_check.setToolTip(self.tr('Desaturated output mode')) self.image = image self.viewer = ImageViewer(self.image, self.image, None) self.process() self.radius_spin.valueChanged.connect(self.process) self.contrast_spin.valueChanged.connect(self.process) self.gray_check.stateChanged.connect(self.process) params_layout = QHBoxLayout() params_layout.addWidget(QLabel(self.tr('Radius:'))) params_layout.addWidget(self.radius_spin) params_layout.addWidget(QLabel(self.tr('Contrast:'))) params_layout.addWidget(self.contrast_spin) params_layout.addWidget(self.gray_check) params_layout.addStretch() main_layout = QVBoxLayout() main_layout.addLayout(params_layout) main_layout.addWidget(self.viewer) self.setLayout(main_layout) def process(self): start = time() kernel = 2 * self.radius_spin.value() + 1 contrast = int(self.contrast_spin.value() / 100 * 255) lut = create_lut(0, contrast) laplace = [] for channel in cv.split(self.image): deriv = np.fabs(cv.Laplacian(channel, cv.CV_64F, None, kernel)) deriv = cv.normalize(deriv, None, 0, 255, cv.NORM_MINMAX, cv.CV_8UC1) laplace.append(cv.LUT(deriv, lut)) result = cv.merge(laplace) if self.gray_check.isChecked(): result = bgr_to_gray3(result) self.viewer.update_processed(result) self.info_message.emit('Echo Edge Filter = {}'.format( elapsed_time(start)))
class MainWindow(QMainWindow): def __init__(self): super().__init__() form = QFormLayout() self.track_id = QSpinBox() self.track_id.setDisabled(True) self.name = QLineEdit() self.album = QComboBox() self.media_type = QComboBox() self.genre = QComboBox() self.composer = QLineEdit() self.milliseconds = QSpinBox() self.milliseconds.setRange(0, 2147483647) # <1> self.milliseconds.setSingleStep(1) self.bytes = QSpinBox() self.bytes.setRange(0, 2147483647) self.bytes.setSingleStep(1) self.unit_price = QDoubleSpinBox() self.unit_price.setRange(0, 999) self.unit_price.setSingleStep(0.01) self.unit_price.setPrefix("$") form.addRow(QLabel("Track ID"), self.track_id) form.addRow(QLabel("Track name"), self.name) form.addRow(QLabel("Composer"), self.composer) form.addRow(QLabel("Milliseconds"), self.milliseconds) form.addRow(QLabel("Bytes"), self.bytes) form.addRow(QLabel("Unit Price"), self.unit_price) self.model = QSqlTableModel(db=db) self.mapper = QDataWidgetMapper() # <2> self.mapper.setModel(self.model) self.mapper.addMapping(self.track_id, 0) # <3> self.mapper.addMapping(self.name, 1) self.mapper.addMapping(self.composer, 5) self.mapper.addMapping(self.milliseconds, 6) self.mapper.addMapping(self.bytes, 7) self.mapper.addMapping(self.unit_price, 8) self.model.setTable("Track") self.model.select() # <4> self.mapper.toFirst() # <5> self.setMinimumSize(QSize(400, 400)) widget = QWidget() widget.setLayout(form) self.setCentralWidget(widget)
def _property_spinbox(self, property_name, range_=(0, 99), parent=None): def wrapped(value: int): if type(value) == str: return setattr(self.model, property_name, value) spin_box = QSpinBox(parent) spin_box.setRange(*range_) spin_box.setValue(getattr(self.model, property_name)) spin_box.valueChanged.connect(wrapped) return spin_box
def add_labels_and_spinboxes_for_advanced_options(self, elements, group_box, nexus_to_spinner): for nexus_string in elements: label = QLabel(nexus_string) spinner = QSpinBox() spinner.setRange(self.minimum_spinbox_value, self.maximum_spinbox_value) group_box.layout().addRow(label, spinner) nexus_to_spinner[nexus_string] = spinner
def __init__(self): super().__init__() widget = QSpinBox() # QDoubleSpinBox() widget.setRange(-10, 10) widget.setPrefix("$") widget.setSuffix("c") widget.setSingleStep(1) # 0.1 widget.valueChanged.connect(self.value_changed) widget.valueChanged[str].connect(self.value_changed_str) self.setCentralWidget(widget)
class CoordinateWidget(QWidget, PropertyWidget): position_changed = Signal(int, int) def __init__(self, target_property_name): QWidget.__init__(self) PropertyWidget.__init__(self, target_property_name) self.layout = QHBoxLayout() self.x_spinbox = QSpinBox() self.y_spinbox = QSpinBox() self.x_spinbox.setRange(-128, 127) self.y_spinbox.setRange(-128, 127) self.x_spinbox.setFixedWidth(60) self.y_spinbox.setFixedWidth(60) self.layout.addWidget(self.x_spinbox) self.layout.addWidget(self.y_spinbox) self.layout.setAlignment(QtGui.Qt.AlignLeft) self.setLayout(self.layout) self.x_spinbox.valueChanged.connect(lambda v: self._on_edit(v, 0)) self.y_spinbox.valueChanged.connect(lambda v: self._on_edit(v, 1)) self.is_disable_write_back = False def _on_edit(self, value, index): if self.target: buffer = self.target[self.target_property_name].value if buffer[index] != value: if not self.is_disable_write_back: buffer[index] = self._signed_to_unsigned(value) self.position_changed.emit(self.x_spinbox.value(), self.y_spinbox.value()) def _on_target_changed(self): if self.target: buffer = self.target[self.target_property_name].value self.x_spinbox.setValue(self._unsigned_to_signed(buffer[0])) self.y_spinbox.setValue(self._unsigned_to_signed(buffer[1])) else: self.x_spinbox.setValue(0) self.y_spinbox.setValue(0) @staticmethod def _unsigned_to_signed(value): packed = ctypes.c_byte(value) return packed.value @staticmethod def _signed_to_unsigned(value): packed = ctypes.c_ubyte(value) return packed.value def set_disable_write_back(self, is_disabled: bool): self.is_disable_write_back = is_disabled
class Window(QWidget): def __init__(self): super().__init__() self.threadpool = QThreadPool() self.totalTickets = QSpinBox() self.totalTickets.setRange(0, 500) self.serviceTickets = QSpinBox() self.serviceTickets.setRange(0, 250) self.incidentTickets = QSpinBox() self.incidentTickets.setRange(0, 250) self.unassignedTickets = QSpinBox() self.unassignedTickets.setRange(0, 200) self.reasonOne = QLineEdit() self.reasonTwo = QLineEdit() self.reasonThree = QLineEdit() self.additionalNotes = QTextEdit() self.generate_btn = QPushButton("Generate PDF") self.generate_btn.pressed.connect(self.generate) layout = QFormLayout() layout.addRow("Number of tickets today", self.totalTickets) layout.addRow("Service tickets", self.serviceTickets) layout.addRow("Incident tickets", self.incidentTickets) layout.addRow("Unassigned tickets", self.unassignedTickets) layout.addRow("Reason for most tickets", self.reasonOne) layout.addRow("Second reason for most tickets", self.reasonTwo) layout.addRow("Third reason for most tickets", self.reasonThree) layout.addRow("additionalNotes", self.additionalNotes) layout.addRow(self.generate_btn) self.setLayout(layout) def generate(self): self.generate_btn.setDisabled(True) data = { 'totalTickets': str(self.totalTickets.value()), 'serviceTickets': str(self.serviceTickets.value()), 'incidentTickets': str(self.incidentTickets.value()), 'unassignedTickets': str(self.unassignedTickets.value()), 'reasonOne': self.reasonOne.text(), 'reasonTwo': self.reasonTwo.text(), 'reasonThree': self.reasonThree.text(), 'additionalNotes': self.additionalNotes.toPlainText() } g = Generator(data) g.signals.file_saved_as.connect(self.generated) g.signals.error.connect(print) # Print errors to console. self.threadpool.start(g) def generated(self, outfile): self.generate_btn.setDisabled(False) try: os.startfile(outfile) except Exception: # If startfile not available, show dialog. QMessageBox.information(self, "Finished", "PDF has been generated")
def create_label_and_spinbox_for_advanced_option(self, nexus_string: str, group_box: QGroupBox): """ Creates a SpinBox with a label and adds them to GroupBox then returns the SpinBox. :param nexus_string: The nexus string label for the SpinBox. :param group_box: The GroupBox that the label and SpinBox should be added to. :return: The newly created SpinBox. """ label = QLabel(nexus_string) spinner = QSpinBox() spinner.setRange(self.minimum_spinbox_value, self.maximum_spinbox_value) group_box.layout().addRow(label, spinner) return spinner
class IntEditor(QWidget): def __init__(self, minval, maxval, stepsize=1, parent=None): super(IntEditor, self).__init__(parent) # Editfield self.edit = QSpinBox(self) self.edit.setKeyboardTracking(False) self.edit.setRange(minval, maxval) self.edit.setSingleStep(stepsize) self.edit.setMinimumWidth(70) # Slider self.slider = QSlider(orientation=Qt.Vertical, parent=self) self.slider.setRange(minval, maxval) self.slider.setSingleStep(stepsize) self.slider.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Expanding) # Ticks q_ticks = QSlider.TicksBelow self.slider.setTickPosition(q_ticks) tick_amount = 6 tick_interval = int(np.floor((maxval - minval) / tick_amount)) self.slider.setTickInterval(tick_interval) # ...labels font = QFont() font.setPointSize(8) tick_str1 = QLabel('{:d}'.format(minval), self) tick_str2 = QLabel('{:d}'.format(maxval), self) tick_str1.setFont(font) tick_str2.setFont(font) slider_tick_layout = QGridLayout() tick_str1.setAlignment(Qt.AlignBottom | Qt.AlignLeft) tick_str2.setAlignment(Qt.AlignTop | Qt.AlignLeft) slider_tick_layout.addWidget(self.slider, 0, 0, tick_amount, 1) slider_tick_layout.addWidget(tick_str2, 0, 1, 1, 1) slider_tick_layout.addWidget(tick_str1, tick_amount - 1, 1, 1, 1) # Layout layout = QVBoxLayout() layout.addLayout(slider_tick_layout) layout.addWidget(self.edit) self.setLayout(layout) # Signals and slots self.edit.valueChanged.connect(self.slider.setValue) self.slider.valueChanged.connect(self.edit.setValue)
def initializePage(self): self.parent_wizard.next_button.setDisabled(True) # grid # |----> groupbox 1 (for choice 1) # |----> vertical_layout 1 # |----> inner_grid 1 (for criteria 1) # |----> label1 # |----> value_spin_box 1 # |----> inner_grid 2 (for criteria 2) # |----> label2 # |----> rating_spin_box 2 # |----> groupbox 2 (for choice 2) # |-... # TODO: consider extracting out common code with # AbstractSliderPage for choice in self.parent_wizard.main_parent.matrix.df.index[1:]: groupbox = QGroupBox(choice) vertical_layout = QVBoxLayout(groupbox) self.grid.addWidget(groupbox) self.spin_boxes[choice] = [] self.sliders[choice] = [] for row, criterion in enumerate( self.parent_wizard.main_parent.matrix.criteria): rating_spin_box = QSpinBox() rating_spin_box.setRange(0, 10) self.spin_boxes[choice].append(rating_spin_box) slider = QSlider(Qt.Orientation.Horizontal) slider.setTickPosition(QSlider.TicksBelow) slider.setMaximum(10) slider.setPageStep(1) slider.setTracking(True) self.sliders[choice].append(slider) cb = partial(self.spin_box_changed, row, choice, criterion) rating_spin_box.valueChanged.connect(cb) cb = partial(self.slider_changed, row, choice, criterion) slider.valueChanged.connect(cb) spin_box_and_slider = QHBoxLayout() spin_box_and_slider.addWidget(rating_spin_box) spin_box_and_slider.addWidget(slider) inner_form = QFormLayout() inner_form.addRow(QLabel(criterion), spin_box_and_slider) vertical_layout.addLayout(inner_form)
class SeedWidget(QGroupBox): def __init__(self, *args, **kwargs): super().__init__("Seed", *args, **kwargs) self.seed_spin = QSpinBox() self.seed_spin.setRange(0, _MAX_SEED) randomize_btn = QPushButton("Randomize") randomize_btn.clicked.connect(self.randomize_seed) layout = QFormLayout() layout.addRow("Seed:", self.seed_spin) layout.addRow("", randomize_btn) self.setLayout(layout) def randomize_seed(self): self.seed_spin.setValue(random.randint(0, _MAX_SEED))
def make_ui(self): """Create and lay out UI elements.""" filter = QSpinBox() filter.setRange(1, 6) self.widgets['filter'] = filter btn_start = QPushButton() btn_start.setText('Start') btn_start.clicked.connect(self.run) self.widgets['btn_start'] = btn_start side_panel = QGridLayout() side_panel.setColumnStretch(0, 0) side_panel.setColumnStretch(1, 1) side_panel.setColumnStretch(2, 1) side_panel.setRowStretch(6, 1) # shove everything to the top side_panel.addWidget(QLabel('<h2>Controls</h2>'), 0, 0, 1, 2) side_panel.addWidget(QLabel('Filter:'), 1, 0) side_panel.addWidget(filter, 1, 1) side_panel.addWidget(btn_start, 2, 0, 1, 2) graph = FigureCanvas(Figure(tight_layout=True)) graph_toolbar = NavigationToolBar(graph, None) graph_toolbar.setObjectName('GraphToolBar') self.widgets['graph'] = graph axis = graph.figure.subplots() axis.grid() axis.set_xlim(0, 100) axis.set_ylim(0, 10) self.widgets['axis'] = axis vbox = QVBoxLayout() vbox.addWidget(graph) vbox.addWidget(graph_toolbar) hbox = QHBoxLayout() hbox.addLayout(side_panel) hbox.addLayout(vbox, 1) main_widget = QFrame() main_widget.setLayout(hbox) return main_widget
def init_letter_spacing_widget(text_item): letter_spacing_layout = QVBoxLayout() letter_spacing_type_combo_box = QComboBox() letter_spacing_value_input = QSpinBox() letter_spacing_value_input.setRange(-10000, 10000) letter_spacing_types = {QFont.PercentageSpacing: "Percentage spacing", QFont.AbsoluteSpacing: "Absolute spacing"} for letter_spacing_type in letter_spacing_types.values(): letter_spacing_type_combo_box.addItem(letter_spacing_type) current_spacing_type = text_item.font().letterSpacingType() letter_spacing_type_combo_box.setCurrentText( letter_spacing_types[current_spacing_type]) letter_spacing_type_combo_box.currentTextChanged.connect(lambda x: set_letter_spacing_type( text_item, x, letter_spacing_value_input, units_label)) letter_spacing_layout.addWidget(letter_spacing_type_combo_box) current_spacing = int(text_item.font().letterSpacing()) if current_spacing_type == QFont.PercentageSpacing and \ current_spacing == 0: letter_spacing_value_input.setValue(100) else: letter_spacing_value_input.setValue(current_spacing) letter_spacing_value_input.valueChanged.connect(lambda: set_letter_spacing_value( text_item, letter_spacing_type_combo_box, letter_spacing_value_input)) letter_spacing_value_input_layout = QHBoxLayout() letter_spacing_value_input_layout.addWidget(letter_spacing_value_input) units_label = QLabel() if current_spacing_type == QFont.PercentageSpacing: units_label.setText("%") else: units_label.setText("px") letter_spacing_value_input_layout.addWidget(units_label) letter_spacing_layout.addLayout(letter_spacing_value_input_layout) letter_spacing_group_box = QGroupBox("Letter spacing") letter_spacing_group_box.setLayout(letter_spacing_layout) return letter_spacing_group_box
class MillerArrayTableForm(QDialog): def __init__(self, parent=None): super(MillerArrayTableForm, self).__init__(parent.window) self.setWindowFlag(Qt.WindowContextHelpButtonHint, False) self.setWindowTitle("Tabulated Reflection Data") self.precision_spinBox = QSpinBox() self.precision_spinBox.setSingleStep(1) self.precision_spinBox.setRange(1, 20) self.precision_spinBox.setValue(3) self.precision_spinBox.valueChanged.connect(parent.onPrecisionChanged) precision_labeltxt = QLabel() precision_labeltxt.setText("Precision:") self.SortComboBox = QComboBox() self.SortComboBox.activated.connect(parent.onSortComboBoxSelchange) sort_labeltxt = QLabel() sort_labeltxt.setText("Sort according to:") self.sortChkbox = QCheckBox() self.sortChkbox.setCheckState(Qt.Unchecked) self.sortChkbox.setText("Ascending order") self.sortChkbox.clicked.connect(parent.onSortChkbox) self.myGroupBox = QGroupBox() self.layout = QGridLayout() self.layout.addWidget(precision_labeltxt, 0, 0, 1, 1) self.layout.addWidget(self.precision_spinBox, 0, 1, 1, 1) self.layout.addWidget(sort_labeltxt, 0, 2, 1, 1) self.layout.addWidget(self.SortComboBox, 0, 3, 1, 1) self.layout.addWidget(self.sortChkbox, 0, 4, 1, 1) self.layout.addWidget(parent.millerarraytable, 1, 0, 1, 5) self.layout.setColumnStretch(0, 0) self.layout.setColumnStretch(1, 0) self.layout.setColumnStretch(2, 0) self.layout.setColumnStretch(3, 0) self.layout.setColumnStretch(4, 1) self.myGroupBox.setLayout(self.layout) self.mainLayout = QGridLayout() self.mainLayout.addWidget(self.myGroupBox, 0, 0) self.setLayout(self.mainLayout) def eventFilter(self, source, event): if (event.type() == QEvent.KeyPress and event.matches(QKeySequence.Copy)): self.parent().parent.millerarraytable.copySelection() return True return super(MillerArrayTableForm, self).eventFilter(source, event)
class DaemonIntervalControls(QWidget): def __init__(self, tool): QWidget.__init__(self) self.tool = tool self.layout = QBoxLayout(QBoxLayout.LeftToRight) self.layout.addWidget(QLabel("Update interval: ")) self.period_select = QSpinBox() self.period_select.setRange(100, 1000 * 60 * 240) # 240 seconds max self.period_select.setSingleStep(100) self.layout.addWidget(self.period_select) self.layout.addWidget(QLabel("ms")) self.layout.setStretch(1, 1) self.setLayout(self.layout)
def create_rating_ticker(self, i, rating): """Creates the rating ticker that is displayed on the Local Storage View tab's QTableView. Each QSpinBox is mapped to a row, representing the rating of the patch. i: The current row the buttons are being created for. rating: The current rating associated with the selected patch. """ if rating < 0 or rating > 5: raise errors.SortingError(rating, 901) rate_tkr = QSpinBox() rate_tkr.setValue(rating) rate_tkr.setRange(0, 5) rate_tkr.setSingleStep(1) rate_tkr.valueChanged.connect(self.update_rating) rate_tkr.setFont(self.ui.table_PS.horizontalHeader().font()) self.ui.table_local.setCellWidget(i, 4, rate_tkr)
class EditSlider(QWidget): def __init__(self, parent=None): super().__init__(parent) hlayout = QHBoxLayout() hlayout.setContentsMargins(0, 0, 0, 0) hlayout.setSpacing(2) self.edit = QSpinBox() self.edit.setMinimumWidth(40) self.edit.setButtonSymbols(QAbstractSpinBox.NoButtons) self.slider = QSlider(Qt.Horizontal) hlayout.addWidget(self.edit) hlayout.addWidget(self.slider) self.setLayout(hlayout) self.slider.valueChanged.connect(self.setValue) self.edit.valueChanged.connect(self.setValue) def setRange(self, min_val, max_val): self.edit.setRange(min_val, max_val) self.slider.setRange(min_val, max_val) def value(self) -> int: return self.edit.value() def setValue(self, value: int): if self.sender() != self.slider and self.sender() != self.edit: self.edit.setValue(value) self.slider.setValue(value) return if self.sender() == self.slider: self.edit.setValue(value) if self.sender() == self.edit: self.slider.setValue(value)
def add_row(self, criterion, deleteable=True): # The last row for this criterion index = self.rows_for_each_criteria[criterion] value_spin_box = QSpinBox() value_spin_box.setRange(0, 100) self.value_spin_boxes[criterion].append(value_spin_box) score_spin_box = QSpinBox() score_spin_box.setRange(0, 100) self.score_spin_boxes[criterion].append(score_spin_box) delete_button = QPushButton('&Delete') cb = partial(self.delete, criterion, index) delete_button.clicked.connect(cb) size_policy = QSizePolicy() size_policy.setRetainSizeWhenHidden(True) delete_button.setSizePolicy(size_policy) cb = partial(self.value_changed, criterion, index) value_spin_box.valueChanged.connect(cb) cb = partial(self.score_changed, criterion, index) score_spin_box.valueChanged.connect(cb) inner_grid = QGridLayout() inner_grid.addWidget(value_spin_box, index, 0) inner_grid.addWidget(QLabel('then score should be '), index, 1) inner_grid.addWidget(score_spin_box, index, 2) inner_grid.addWidget(delete_button, index, 3) if not deleteable: delete_button.hide() form = QFormLayout() form.addRow(QLabel('If ' + str(criterion) + ' is '), inner_grid) pos = self.vertical_layouts[criterion].count() - 1 self.vertical_layouts[criterion].insertLayout(pos, form) # Increment the row number self.rows_for_each_criteria[criterion] += 1
class IntegerFilterWidget(AbstractFilterWidget): def __init__(self, field: str, parent=None): super().__init__(parent) self.field = field vlayout = QVBoxLayout() vlayout.setContentsMargins(0, 0, 0, 0) self.edit = QSpinBox() vlayout.addWidget(self.edit) self.setLayout(vlayout) self.edit.valueChanged.connect(self.changed) def setup(self, conn: sqlite3.Connection): field_min, field_max = sql.get_field_range(conn, self.field) self.edit.setRange(field_min, field_max) def get_filters(self): name = self.field value = self.edit.value() return f"({name} == {value})"
class Window(QWidget): def __init__(self): super(Window, self).__init__() self.renderArea = RenderArea() self.shapeComboBox = QComboBox() self.shapeComboBox.addItem("Polygon", RenderArea.Polygon) self.shapeComboBox.addItem("Rectangle", RenderArea.Rect) self.shapeComboBox.addItem("Rounded Rectangle", RenderArea.RoundedRect) self.shapeComboBox.addItem("Ellipse", RenderArea.Ellipse) self.shapeComboBox.addItem("Pie", RenderArea.Pie) self.shapeComboBox.addItem("Chord", RenderArea.Chord) self.shapeComboBox.addItem("Path", RenderArea.Path) self.shapeComboBox.addItem("Line", RenderArea.Line) self.shapeComboBox.addItem("Polyline", RenderArea.Polyline) self.shapeComboBox.addItem("Arc", RenderArea.Arc) self.shapeComboBox.addItem("Points", RenderArea.Points) self.shapeComboBox.addItem("Text", RenderArea.Text) self.shapeComboBox.addItem("Pixmap", RenderArea.Pixmap) shapeLabel = QLabel("&Shape:") shapeLabel.setBuddy(self.shapeComboBox) self.penWidthSpinBox = QSpinBox() self.penWidthSpinBox.setRange(0, 20) self.penWidthSpinBox.setSpecialValueText("0 (cosmetic pen)") penWidthLabel = QLabel("Pen &Width:") penWidthLabel.setBuddy(self.penWidthSpinBox) self.penStyleComboBox = QComboBox() self.penStyleComboBox.addItem("Solid", Qt.SolidLine) self.penStyleComboBox.addItem("Dash", Qt.DashLine) self.penStyleComboBox.addItem("Dot", Qt.DotLine) self.penStyleComboBox.addItem("Dash Dot", Qt.DashDotLine) self.penStyleComboBox.addItem("Dash Dot Dot", Qt.DashDotDotLine) self.penStyleComboBox.addItem("None", Qt.NoPen) penStyleLabel = QLabel("&Pen Style:") penStyleLabel.setBuddy(self.penStyleComboBox) self.penCapComboBox = QComboBox() self.penCapComboBox.addItem("Flat", Qt.FlatCap) self.penCapComboBox.addItem("Square", Qt.SquareCap) self.penCapComboBox.addItem("Round", Qt.RoundCap) penCapLabel = QLabel("Pen &Cap:") penCapLabel.setBuddy(self.penCapComboBox) self.penJoinComboBox = QComboBox() self.penJoinComboBox.addItem("Miter", Qt.MiterJoin) self.penJoinComboBox.addItem("Bevel", Qt.BevelJoin) self.penJoinComboBox.addItem("Round", Qt.RoundJoin) penJoinLabel = QLabel("Pen &Join:") penJoinLabel.setBuddy(self.penJoinComboBox) self.brushStyleComboBox = QComboBox() self.brushStyleComboBox.addItem("Linear Gradient", Qt.LinearGradientPattern) self.brushStyleComboBox.addItem("Radial Gradient", Qt.RadialGradientPattern) self.brushStyleComboBox.addItem("Conical Gradient", Qt.ConicalGradientPattern) self.brushStyleComboBox.addItem("Texture", Qt.TexturePattern) self.brushStyleComboBox.addItem("Solid", Qt.SolidPattern) self.brushStyleComboBox.addItem("Horizontal", Qt.HorPattern) self.brushStyleComboBox.addItem("Vertical", Qt.VerPattern) self.brushStyleComboBox.addItem("Cross", Qt.CrossPattern) self.brushStyleComboBox.addItem("Backward Diagonal", Qt.BDiagPattern) self.brushStyleComboBox.addItem("Forward Diagonal", Qt.FDiagPattern) self.brushStyleComboBox.addItem("Diagonal Cross", Qt.DiagCrossPattern) self.brushStyleComboBox.addItem("Dense 1", Qt.Dense1Pattern) self.brushStyleComboBox.addItem("Dense 2", Qt.Dense2Pattern) self.brushStyleComboBox.addItem("Dense 3", Qt.Dense3Pattern) self.brushStyleComboBox.addItem("Dense 4", Qt.Dense4Pattern) self.brushStyleComboBox.addItem("Dense 5", Qt.Dense5Pattern) self.brushStyleComboBox.addItem("Dense 6", Qt.Dense6Pattern) self.brushStyleComboBox.addItem("Dense 7", Qt.Dense7Pattern) self.brushStyleComboBox.addItem("None", Qt.NoBrush) brushStyleLabel = QLabel("&Brush Style:") brushStyleLabel.setBuddy(self.brushStyleComboBox) otherOptionsLabel = QLabel("Other Options:") self.antialiasingCheckBox = QCheckBox("&Antialiasing") self.transformationsCheckBox = QCheckBox("&Transformations") self.shapeComboBox.activated.connect(self.shapeChanged) self.penWidthSpinBox.valueChanged.connect(self.penChanged) self.penStyleComboBox.activated.connect(self.penChanged) self.penCapComboBox.activated.connect(self.penChanged) self.penJoinComboBox.activated.connect(self.penChanged) self.brushStyleComboBox.activated.connect(self.brushChanged) self.antialiasingCheckBox.toggled.connect(self.renderArea.setAntialiased) self.transformationsCheckBox.toggled.connect(self.renderArea.setTransformed) mainLayout = QGridLayout() mainLayout.setColumnStretch(0, 1) mainLayout.setColumnStretch(3, 1) mainLayout.addWidget(self.renderArea, 0, 0, 1, 4) mainLayout.setRowMinimumHeight(1, 6) mainLayout.addWidget(shapeLabel, 2, 1, Qt.AlignRight) mainLayout.addWidget(self.shapeComboBox, 2, 2) mainLayout.addWidget(penWidthLabel, 3, 1, Qt.AlignRight) mainLayout.addWidget(self.penWidthSpinBox, 3, 2) mainLayout.addWidget(penStyleLabel, 4, 1, Qt.AlignRight) mainLayout.addWidget(self.penStyleComboBox, 4, 2) mainLayout.addWidget(penCapLabel, 5, 1, Qt.AlignRight) mainLayout.addWidget(self.penCapComboBox, 5, 2) mainLayout.addWidget(penJoinLabel, 6, 1, Qt.AlignRight) mainLayout.addWidget(self.penJoinComboBox, 6, 2) mainLayout.addWidget(brushStyleLabel, 7, 1, Qt.AlignRight) mainLayout.addWidget(self.brushStyleComboBox, 7, 2) mainLayout.setRowMinimumHeight(8, 6) mainLayout.addWidget(otherOptionsLabel, 9, 1, Qt.AlignRight) mainLayout.addWidget(self.antialiasingCheckBox, 9, 2) mainLayout.addWidget(self.transformationsCheckBox, 10, 2) self.setLayout(mainLayout) self.shapeChanged() self.penChanged() self.brushChanged() self.antialiasingCheckBox.setChecked(True) self.setWindowTitle("Basic Drawing") def shapeChanged(self): shape = self.shapeComboBox.itemData(self.shapeComboBox.currentIndex(), IdRole) self.renderArea.setShape(shape) def penChanged(self): width = self.penWidthSpinBox.value() style = Qt.PenStyle(self.penStyleComboBox.itemData( self.penStyleComboBox.currentIndex(), IdRole)) cap = Qt.PenCapStyle(self.penCapComboBox.itemData( self.penCapComboBox.currentIndex(), IdRole)) join = Qt.PenJoinStyle(self.penJoinComboBox.itemData( self.penJoinComboBox.currentIndex(), IdRole)) self.renderArea.setPen(QPen(Qt.blue, width, style, cap, join)) def brushChanged(self): style = Qt.BrushStyle(self.brushStyleComboBox.itemData( self.brushStyleComboBox.currentIndex(), IdRole)) if style == Qt.LinearGradientPattern: linearGradient = QLinearGradient(0, 0, 100, 100) linearGradient.setColorAt(0.0, Qt.white) linearGradient.setColorAt(0.2, Qt.green) linearGradient.setColorAt(1.0, Qt.black) self.renderArea.setBrush(QBrush(linearGradient)) elif style == Qt.RadialGradientPattern: radialGradient = QRadialGradient(50, 50, 50, 70, 70) radialGradient.setColorAt(0.0, Qt.white) radialGradient.setColorAt(0.2, Qt.green) radialGradient.setColorAt(1.0, Qt.black) self.renderArea.setBrush(QBrush(radialGradient)) elif style == Qt.ConicalGradientPattern: conicalGradient = QConicalGradient(50, 50, 150) conicalGradient.setColorAt(0.0, Qt.white) conicalGradient.setColorAt(0.2, Qt.green) conicalGradient.setColorAt(1.0, Qt.black) self.renderArea.setBrush(QBrush(conicalGradient)) elif style == Qt.TexturePattern: self.renderArea.setBrush(QBrush(QPixmap(':/images/brick.png'))) else: self.renderArea.setBrush(QBrush(Qt.green, style))