class IccTableEditorYearSpecificView(IccTableEditorView): """ Eine von IccTableEditorView abgeleitete Klasse, die in der Toolbar neben dem Speichern-Button eine Jahr-Combobox hat. Sie wird mit den Methoden addJahr, addJahre, setCurrentJahr und clearJahre bedient. Wird das Jahr geändert, wird ein yearChanged-Signal gesendet. """ yearChanged = Signal(int) def __init__(self, model: XBaseTableModel = None): IccTableEditorView.__init__(self, model) self._cboYear = QComboBox() self._cboYear.setFont(QFont("Arial", 14, weight=QFont.Bold)) self._cboYear.currentTextChanged.connect(self.onCurrentYearChanged) self.addTool(self._cboYear) def addJahr(self, jahr: int): self._cboYear.addItem(str(jahr)) def addJahre(self, jahre: List[int]): self._cboYear.addItems([str(j) for j in jahre]) def setCurrentJahr(self, jahr: int): self._cboYear.setCurrentText(str(jahr)) def clearJahre(self): self._cboYear.clear() def onCurrentYearChanged(self, sJahrNeu: str): self.yearChanged.emit(int(sJahrNeu))
def _create_resource_type_combo( current_resource_type: ResourceType, parent: QWidget, resource_database: ResourceDatabase) -> QComboBox: """ :param current_resource_type: :param parent: :return: """ resource_type_combo = QComboBox(parent) for resource_type in iterate_enum(ResourceType): try: count_elements = len(resource_database.get_by_type(resource_type)) except ValueError: count_elements = 0 if count_elements == 0: continue resource_type_combo.addItem(resource_type.name, resource_type) if resource_type is current_resource_type: resource_type_combo.setCurrentIndex(resource_type_combo.count() - 1) return resource_type_combo
def add_supplier_list_to_combo(self, combo: QComboBox): # clear QComboBox combo.clear() combo.clearEditText() if self.parent.sheets is None: combo.setEnabled(False) return if self.db is None: self.flag_db = False combo.setEnabled(False) return # DB Query and update QConboBox sql = "SELECT name_supplier_short FROM supplier;" out = self.db.get(sql) for supplier in out: combo.addItem(supplier[0]) name = self.get_supplier_name() index = combo.findText(name) if index >= 0: combo.setCurrentIndex(index) combo.setEnabled(False) else: combo.setEnabled(True)
def setup_translators_elements(self): randomizer_data = default_data.decode_randomizer_data() self.always_up_gfmc_compound_check.stateChanged.connect( functools.partial(self._on_always_up_check_changed, "fixed_gfmc_compound")) self.always_up_torvus_temple_check.stateChanged.connect( functools.partial(self._on_always_up_check_changed, "fixed_torvus_temple")) self.always_up_great_temple_check.stateChanged.connect( functools.partial(self._on_always_up_check_changed, "fixed_great_temple")) self.translator_randomize_all_button.clicked.connect(self._on_randomize_all_gates_pressed) self.translator_vanilla_actual_button.clicked.connect(self._on_vanilla_actual_gates_pressed) self.translator_vanilla_colors_button.clicked.connect(self._on_vanilla_colors_gates_pressed) self._combo_for_gate = {} for i, gate in enumerate(randomizer_data["TranslatorLocationData"]): label = QLabel(self.translators_scroll_contents) label.setText(gate["Name"]) self.translators_layout.addWidget(label, 3 + i, 0, 1, 1) combo = QComboBox(self.translators_scroll_contents) combo.gate = TranslatorGate(gate["Index"]) for item in LayoutTranslatorRequirement: combo.addItem(item.long_name, item) combo.currentIndexChanged.connect(functools.partial(self._on_gate_combo_box_changed, combo)) self.translators_layout.addWidget(combo, 3 + i, 1, 1, 2) self._combo_for_gate[combo.gate] = combo
class QFlightStartType(QGroupBox): def __init__(self, package_model: PackageModel, flight: Flight): super().__init__() self.package_model = package_model self.flight = flight self.layout = QVBoxLayout() self.main_row = QHBoxLayout() self.start_type_label = QLabel("Start type:") self.start_type = QComboBox() for start_type in StartType: self.start_type.addItem(start_type.value, start_type) self.start_type.setCurrentText(flight.start_type.value) self.start_type.currentTextChanged.connect( self._on_start_type_selected) self.main_row.addWidget(self.start_type_label) self.main_row.addWidget(self.start_type) self.layout.addLayout(self.main_row) self.layout.addWidget( QLabel( "Any option other than Cold will make this flight non-targetable " + "by OCA/Aircraft missions. This will affect game balance.")) self.setLayout(self.layout) def _on_start_type_selected(self): selected = self.start_type.currentData() self.flight.start_type = selected self.package_model.update_tot()
def __init__(self, editor: PresetEditor): super().__init__() self.setupUi(self) self._editor = editor randomizer_data = default_data.decode_randomizer_data() self.translators_layout.setAlignment(QtCore.Qt.AlignTop) self.translator_randomize_all_button.clicked.connect( self._on_randomize_all_gates_pressed) self.translator_vanilla_actual_button.clicked.connect( self._on_vanilla_actual_gates_pressed) self.translator_vanilla_colors_button.clicked.connect( self._on_vanilla_colors_gates_pressed) self._combo_for_gate = {} for i, gate in enumerate(randomizer_data["TranslatorLocationData"]): label = QtWidgets.QLabel(self.translators_scroll_contents) label.setText(gate["Name"]) self.translators_layout.addWidget(label, 3 + i, 0, 1, 1) combo = QComboBox(self.translators_scroll_contents) combo.gate = TranslatorGate(gate["Index"]) for item in iterate_enum(LayoutTranslatorRequirement): combo.addItem(item.long_name, item) combo.currentIndexChanged.connect( functools.partial(self._on_gate_combo_box_changed, combo)) self.translators_layout.addWidget(combo, 3 + i, 1, 1, 2) self._combo_for_gate[combo.gate] = combo
class QChooseAirbase(QGroupBox): selected_airbase_changed = Signal(str) def __init__(self, game: Game, title=""): super(QChooseAirbase, self).__init__(title) self.game = game self.layout = QHBoxLayout() self.depart_from_label = QLabel("Airbase : ") self.depart_from = QComboBox() for i, cp in enumerate([ b for b in self.game.theater.controlpoints if b.captured and b.id in self.game.planners ]): self.depart_from.addItem(str(cp.name), cp) self.depart_from.setCurrentIndex(0) self.depart_from.currentTextChanged.connect(self._on_airbase_selected) self.layout.addWidget(self.depart_from_label) self.layout.addWidget(self.depart_from) self.setLayout(self.layout) def _on_airbase_selected(self): selected = self.depart_from.currentText() self.selected_airbase_changed.emit(selected)
class AutomatonStateManager(QWidget): signalStateIdsRequest = Signal() signalSetStartingStateRequest = Signal(str) signalSetCurrentStateRequest = Signal(str) def __init__(self, parent): super(AutomatonStateManager, self).__init__(parent) self.startingStateButton = QPushButton('Set starting state: ', self) self.startingStateButton.clicked.connect(self.setStartingState) self.startingSelect = QComboBox(self) self.currentStateButton = QPushButton('Set current state: ', self) self.currentStateButton.clicked.connect(self.setCurrentState) self.currentSelect = QComboBox(self) self.signalStateIdsRequest.emit() layout = QHBoxLayout() layout.addWidget(self.startingStateButton) layout.addWidget(self.startingSelect) layout.addWidget(self.currentStateButton) layout.addWidget(self.currentSelect) layout.setSizeConstraint(QLayout.SetMaximumSize) self.setLayout(layout) @Slot(list) def populateStateSelect(self, stateIds): self.startingSelect.clear() self.currentSelect.clear() for stateId in stateIds: self.startingSelect.addItem('q{}'.format(stateIds.index(stateId)), stateId) self.currentSelect.addItem('q{}'.format(stateIds.index(stateId)), stateId) self.startingSelect.setCurrentIndex(0) self.currentSelect.setCurrentIndex(0) @Slot() def setStartingState(self): stateId = self.startingSelect.currentData() self.signalSetStartingStateRequest.emit(stateId) @Slot() def setCurrentState(self): stateId = self.currentSelect.currentData() self.signalSetCurrentStateRequest.emit(stateId) @Slot() def disableEdit(self): self.startingSelect.setDisabled(True) self.startingStateButton.setDisabled(True) self.currentSelect.setDisabled(True) self.currentStateButton.setDisabled(True) @Slot() def enableEdit(self): self.startingSelect.setDisabled(False) self.startingStateButton.setDisabled(False) self.currentSelect.setDisabled(False) self.currentStateButton.setDisabled(False)
class TemplateDialog(QDialog): def __init__(self, *args, **kwargs): super(TemplateDialog, self).__init__(*args, **kwargs) self.initUI() def initUI(self): mainLayout = QGridLayout(self) mainLayout.setAlignment(Qt.AlignLeft | Qt.AlignTop) mainLayout.setColumnStretch(0, 0) mainLayout.setColumnStretch(1, 1) mainLayout.setColumnStretch(2, 1) self.setLayout(mainLayout) line = 0 nameText = QLabel('Name:') nameText.setAlignment(Qt.AlignRight) self.nameIn = QLineEdit() mainLayout.addWidget(nameText, line, 0) mainLayout.addWidget(self.nameIn, line, 1, 1, 2) line += 1 tempText = QLabel('Template:') tempText.setAlignment(Qt.AlignRight) self.tempCombo = QComboBox() self.tempCombo.addItem('[NO TEMPLATE]', 0) self._read_templates() mainLayout.addWidget(tempText, line, 0) mainLayout.addWidget(self.tempCombo, line, 1, 1, 2) line += 1 okBtn = QPushButton("Create") okBtn.clicked.connect(self.accept) cancelBtn = QPushButton("Cancel") cancelBtn.clicked.connect(self.reject) mainLayout.addWidget(okBtn, line, 1, 1, 1) mainLayout.addWidget(cancelBtn, line, 2, 1, 1) self.setWindowTitle("New Picker Interface Information") self.setWindowFlags(Qt.WindowStaysOnTopHint) def _read_templates(self): template_dir = get_PMTemplateDir() if os.path.exists(template_dir): files = os.walk(template_dir).next()[2] for each in files: if each.lower().endswith(".pii"): self.tempCombo.addItem(each, each) def get_raw(self): name = self.nameIn.text() template_dir = get_PMTemplateDir() template = self.tempCombo.currentText() data = {} if template != "[NO TEMPLATE]": path = os.path.join(template_dir, template) with open(path, 'r') as outfile: data = json.load(outfile) return {'name': name, 'data': data} Raw = property(get_raw)
def add_channel(self, name: str) -> None: if name in self._channels: return self._channels[name] = Channel(name, self) channel = QLabel(f"{name.capitalize()}:", self) volume = QSlider(Qt.Horizontal) volume.setMaximum(100) volume.setValue(100) def volume_changed() -> None: self.on_channel_volume_changed(name, volume.value()) # noinspection PyUnresolvedReferences volume.valueChanged.connect(volume_changed) threshold = QComboBox(self) for member in PlaybackThreshold: threshold.addItem(member.name, member) # noinspection PyCallingNonCallable @QtCore.Slot(int) # type: ignore def threshold_changed(index: int) -> None: self.on_channel_threshold_changed(name, index, threshold) # noinspection PyUnresolvedReferences threshold.currentIndexChanged.connect(threshold_changed) row = self.ui.layout.rowCount() self.ui.layout.setColumnStretch(1, 1) self.ui.layout.setColumnStretch(2, 0) self.ui.layout.addWidget(channel, row=row, column=0) self.ui.layout.addWidget(volume, row=row, column=1) self.ui.layout.addWidget(threshold, row=row, column=2)
def set_shell_layout(self): """Sets the layout which can execute shell commands.""" self._current_layout = "Shell" self._clear_layout() command_type_label = QLabel("Command type: ") command_type_combobox = QComboBox() command_type_combobox.addItem("Shell") command_type_combobox.addItem("Module") command_label = QLabel("Command:") command_input = QLineEdit() run_button = QPushButton("Run") run_button.setMaximumWidth(250) run_button.setMinimumHeight(25) command_type_combobox.currentTextChanged.connect(self._on_command_type_change) run_button.pressed.connect(lambda: self._on_command_run(command_input)) self._layout.addWidget(command_type_label, 0, 0) self._layout.addWidget(command_type_combobox, 0, 1) self._layout.addWidget(command_label, 1, 0) self._layout.addWidget(command_input, 1, 1) self._sub_layout.addWidget(QLabel("")) self._sub_layout.addWidget(run_button) self._sub_layout.setContentsMargins(0, 15, 0, 0) self._layout.addLayout(self._sub_layout, self._layout.rowCount() + 2, 0, 1, 2)
class MyDialog(QDialog): def __init__(self, parent=None): super().__init__() self.resize(400, 50) self.engine = 'dot' self.comboBox = QComboBox(self) self.engines = [('dot', 'for drawing directed graphs'), ('neato', 'for drawing undirected graphs'), ('twopi', 'for radial layouts of graphs'), ('circo', 'for circular layout of graphs'), ('fdp', 'for drawing undirected graphs'), ('sfdp', 'for drawing large undirected graphs'), ('patchwork', 'for squarified tree maps'), ('osage', 'for array-based layouts')] for name, desc in self.engines: self.comboBox.addItem(name) self.comboBox.activated[str].connect(self.my_method) def my_method(self, engine_name): index = self.comboBox.currentIndex() self.setWindowTitle(self.engines[index][1]) self.engine = engine_name print(self.engine)
class Config(SignalNode.Config): """Config widget displayed for LSLInput.""" def __init__(self, parent=None): super().__init__(parent=parent) self.data_source = QComboBox() for source in LSLInput.data_sources: self.data_source.addItem(source.name) self.data_source.currentTextChanged.connect(self._adjust) self.channel_count = QLabel() self.channel_count.setFrameStyle(QFrame.Panel | QFrame.Sunken) self.channel_count.setAlignment(Qt.AlignCenter) self.channel_count.setMargin(5) self.frequency = QLabel() self.frequency.setFrameStyle(QFrame.Panel | QFrame.Sunken) self.frequency.setAlignment(Qt.AlignCenter) self.frequency.setMargin(5) layout = QFormLayout() self.setLayout(layout) layout.addRow("Data source:", self.data_source) layout.addRow("Channel count:", self.channel_count) layout.addRow("Frequency:", self.frequency) self._adjust() def _adjust(self): """Adjust displayed values after a change.""" # Sync changes with the node self.updateModel() # Find the data_source with the selected name for data_source in LSLInput.data_sources: if data_source.name == self.data_source.currentText(): break else: data_source = None # Update displays to show new information self.channel_count.setText(str(data_source.channel_count)) self.frequency.setText(str(data_source.frequency) + " Hz") def updateModel(self): n = self.node() if n is None: return n.setDataSource(self.data_source.currentText()) def updateView(self): n = self.node() if n is None: return self.data_source.blockSignals(True) self.data_source.setCurrentText(n.dataSource()) self.data_source.blockSignals(False)
class ComboboxTreeItemDelegate(QStyledItemDelegate): def __init__(self, adapter, *args): super().__init__(*args) self.adapter = adapter self.combobox = None ## Create the combobox and fill it with labels def createEditor(self, parent, option, index): self.combobox = QComboBox(parent) for sft in [4, 5, 6]: self.combobox.addItem(mode_labels[1 << sft], 1 << sft) return self.combobox ## Render the editor based on the data in the model def setEditorData(self, editor, index): val = index.model().data(index, role=Qt.UserRole) self.combobox.setCurrentText(mode_labels[val]) ## Write back newly selected items into the model def setModelData(self, editor, model, index): model.setData(index, self.combobox.currentData(), role=Qt.UserRole) model.setData(index, self.combobox.currentText()) self.adapter.update(model.data(index, role=Qt.UserRole + 1), mode=self.combobox.currentData())
class MainWindow(QWidget): def __init__(self, parent=None): super(MainWindow, self).__init__(parent) self.game = GameWidget(self) self.box = QComboBox() maps = [elem for elem in os.listdir() if '.l' in elem] for elem in maps: self.box.addItem(elem) self.buttonRandom = QPushButton('Random') self.buttonRandom.clicked.connect(self.random) self.buttonLoad = QPushButton('Load') self.buttonLoad.clicked.connect(self.load) self.buttonStep = QPushButton("Step") self.buttonStep.clicked.connect(self.game.step) self.buttonRun = QPushButton("Run") self.buttonRun.clicked.connect(self.game.run) self.buttonStop = QPushButton("Stop") self.buttonStop.clicked.connect(self.game.stop) self.child = QWidget(self) childLayout = QHBoxLayout() layout = QVBoxLayout() layout.addWidget(self.game) childLayout.addWidget(self.buttonRun) childLayout.addWidget(self.buttonStop) childLayout.addWidget(self.buttonStep) self.child.setLayout(childLayout) layout.addWidget(self.child) layout.addWidget(self.box) layout.addWidget(self.buttonLoad) layout.addWidget(self.buttonRandom) self.setLayout(layout) self.setWindowTitle('LIFE') self.setFixedSize(1500, 1000) def load(self): item = self.box.currentText() f = open(item, 'r') self.game.load(f) f.close() self.game.drawUniverse() def random(self): self.game.universe.generate_random_map() self.game.drawUniverse() def showEvent(self, event): self.game.drawUniverse()
class ThresholdingGui(QWidget): image: np.ndarray titles = ['Original Image', 'THRESH_BINARY + cv2.THRESH_OTSU'] def __init__(self): super(ThresholdingGui, self).__init__() self.setWindowTitle('Otsu\'s Thresholding') open_image_btn = QPushButton('Open Image', self) open_image_btn.clicked.connect(self.open_image) self.method_combobox = QComboBox() for title in self.titles: self.method_combobox.addItem(title) self.method_combobox.currentIndexChanged.connect(self.update_preview) self.threshold_label = QLabel('Threshold calculated: -') self.image_label = QLabel() self.image = np.tile( np.arange(256, dtype=np.uint8).repeat(2), (512, 1)) q_img = QImage(self.image.data, 512, 512, 512, QImage.Format_Indexed8) self.image_label.setPixmap(QPixmap.fromImage(q_img)) # Create layout and add widgets layout = QVBoxLayout() layout.addWidget(open_image_btn) layout.addWidget(self.method_combobox) layout.addWidget(self.threshold_label) layout.addWidget(self.image_label) # Set dialog layout self.setLayout(layout) def open_image(self): image_path, _ = QFileDialog.getOpenFileName( self, "Load Image", filter="Image Files (*.tiff *.png *.jpeg *.jpg *.bmp)") if image_path: self.image = cv2.imread(image_path, 0) self.update_preview() def update_preview(self): method_idx = self.method_combobox.currentIndex() if method_idx == 0: ret, th = '-', self.image elif method_idx == 1: ret, th = cv2.threshold(self.image, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU) self.threshold_label.setText(f"Threshold calculated: {ret}") image_h, image_w = th.shape q_img = QImage(th.data, image_w, image_h, image_w, QImage.Format_Indexed8) self.image_label.setPixmap(QPixmap.fromImage(q_img))
def _fill_combo(item_database: ItemDatabase, combo: QtWidgets.QComboBox): items = [] items.extend(item.name for item in item_database.major_items.values()) items.extend(item.name for item in item_database.ammo.values()) items.extend(f"Energy Cell {i}" for i in range(1, 10)) for item in sorted(items): combo.addItem(item, item)
def _create_ammo_combo(): combo = QComboBox(self.beam_configuration_group) combo.addItem("None", -1) combo.addItem("Power Bomb", 43) combo.addItem("Missile", 44) combo.addItem("Dark Ammo", 45) combo.addItem("Light Ammo", 46) return combo
def create_combobox(self, service, method_name): combo = QComboBox() values = getattr(service, method_name)() for value in values: combo.addItem(value) return combo
class DelegateKeepsReferenceToEditor(QAbstractItemDelegate): def __init__(self, parent=None): QAbstractItemDelegate.__init__(self, parent) self.comboBox = QComboBox() self.comboBox.addItem(id_text) def createEditor(self, parent, option, index): self.comboBox.setParent(parent) return self.comboBox
class DatatypeSelector(QGroupBox): def __init__(self, title: str, datatype_to_widget, parent: "QWidget" = None): super().__init__(title, parent) # Maps a datatype with its respective widget. The widget is optional self._datatype_to_widget = datatype_to_widget self._datatype_combobox = QComboBox() self._stacked_widgets = QStackedWidget() for (i, (name, datatype_factory)) in enumerate( DataTypeContainer.providers.items()): datatype_instance = datatype_factory() self._datatype_combobox.addItem(name, datatype_instance) if datatype_factory in self._datatype_to_widget: self._stacked_widgets.insertWidget( i, self._datatype_to_widget[datatype_factory]( datatype_instance)) self._main_layout = QVBoxLayout() self._main_layout.addWidget(self._datatype_combobox) self._main_layout.addWidget(self._stacked_widgets) self.setLayout(self._main_layout) self._datatype_combobox.currentIndexChanged[int].connect( self._change_active_widget) @property def selected_datatype(self): return self._datatype_combobox.currentData() def change_current_datatype(self, new_datatype_dict: dict): index = self._datatype_combobox.findText(new_datatype_dict["class"]) if index != -1: self._datatype_combobox.setCurrentIndex(index) self._datatype_combobox.currentData().from_dict(new_datatype_dict) self._stacked_widgets.currentWidget().reload() def _change_active_widget(self, index): self._stacked_widgets.setCurrentIndex(index) # Hide the `stacked_widgets` when the current datatype doesn't needs to display # a widget if self._stacked_widgets.currentIndex() != index: self._stacked_widgets.setVisible(False) else: self._stacked_widgets.setVisible(True) def to_dict(self): return self.selected_datatype.to_dict()
class NodeOutput(QWidget): def __init__(self, content_widget): super(NodeOutput, self).__init__() self.content_widget = content_widget # create UI # create all layouts self.grid_layout = QGridLayout(self) # move buttons self.up_button = QPushButton(self, '') self.down_button = QPushButton(self, '') # type and label self.type_combo_box = QComboBox(self) self.type_combo_box.addItem('exec') self.type_combo_box.addItem('data') self.label_line_edit = QLineEdit(self) self.label_line_edit.setPlaceholderText('Label') # del button self.del_button = QPushButton(self) self.del_button.setText(' Del ') self.del_button.clicked.connect(self.delete_clicked) # merge layouts self.grid_layout.addWidget(self.up_button, 0, 0) self.grid_layout.addWidget(self.down_button, 1, 0) self.grid_layout.addWidget(self.type_combo_box, 0, 1) self.grid_layout.addWidget(self.label_line_edit, 1, 1) self.grid_layout.addWidget(self.type_combo_box, 0, 1) self.grid_layout.addWidget(self.del_button, 0, 2, 2, 1) def get_type(self): return self.type_combo_box.currentText() def get_label(self): return self.label_line_edit.text() def set_type(self, new_type): self.type_combo_box.setCurrentText(new_type) def set_label(self, new_label): self.label_line_edit.setText(new_label) def delete_clicked(self): ret = QMessageBox.warning( self, 'Output', 'Do you really want to delete this input? All changes' 'will be lost.', QMessageBox.Yes, QMessageBox.No) if ret == QMessageBox.Yes: self.content_widget.delete_output(self)
def init_font_families_widget(text_item): families_combo_box = QComboBox() families_list = QFontDatabase().families() for family in families_list: families_combo_box.addItem(family) families_combo_box.setCurrentText(text_item.font().family()) families_combo_box.currentTextChanged.connect(lambda x: set_font_family( x, text_item)) return families_combo_box
def get_profiles_dropdown(self): """ :return: A dropdown menu widget that lists all profiles including the default profile from the OCI config file When index changes, it will call the change_profile signal function :rtype: :class: 'Qt.QtWidgets.QComboBox' """ dropdown = QComboBox() dropdown.addItems(['DEFAULT'] + self.config.sections()) dropdown.addItem("Add New Profile...") dropdown.currentIndexChanged.connect(self.change_profile_signal) return dropdown
def generateCollationsField(server): """ @rtype: QComboBox """ collations = server.getCollations() field = QComboBox() field.addItem('') for collation in collations: field.addItem(collation['Collation']) return field
class NodeOutput(QWidget): def __init__(self, content_widget): super(NodeOutput, self).__init__() self.content_widget = content_widget # create UI # create all layouts self.grid_layout = QGridLayout(self) # # move buttons TODO move buttons # self.up_button = QPushButton(self, '') # self.down_button = QPushButton(self, '') # type and label self.type_combo_box = QComboBox(self) self.type_combo_box.addItem('exec') self.type_combo_box.addItem('data') self.label_line_edit = QLineEdit(self) self.label_line_edit.setPlaceholderText('Label') # del button self.del_button = QPushButton(self) self.del_button.setText(' Del ') self.del_button.clicked.connect(self.delete_clicked) # merge layouts # self.grid_layout.addWidget(self.up_button, 0, 0) # self.grid_layout.addWidget(self.down_button, 1, 0) self.grid_layout.addWidget(self.type_combo_box, 0, 1) self.grid_layout.addWidget(self.label_line_edit, 1, 1) self.grid_layout.addWidget(self.type_combo_box, 0, 1) self.grid_layout.addWidget(self.del_button, 0, 2, 2, 1) def get_type(self): return self.type_combo_box.currentText() def get_label(self): return self.label_line_edit.text() def set_type(self, new_type): self.type_combo_box.setCurrentText(new_type) def set_label(self, new_label): self.label_line_edit.setText(new_label) def delete_clicked(self): self.content_widget.delete_output(self)
class MainWindow(QMainWindow): def __init__(self): super(MainWindow, self).__init__() centralWidget = QWidget() self.setCentralWidget(centralWidget) layout = QFormLayout(centralWidget) textLayout = QHBoxLayout() self.text = QLineEdit('Hello, PySide2') self.text.setClearButtonEnabled(True) textLayout.addWidget(self.text) self.sayButton = QPushButton('Say') textLayout.addWidget(self.sayButton) self.text.returnPressed.connect(self.sayButton.animateClick) self.sayButton.clicked.connect(self.say) layout.addRow('Text:', textLayout) self.voiceCombo = QComboBox() layout.addRow('Voice:', self.voiceCombo) self.volumeSlider = QSlider(Qt.Horizontal) self.volumeSlider.setMinimum(0) self.volumeSlider.setMaximum(100) self.volumeSlider.setValue(100) layout.addRow('Volume:', self.volumeSlider) self.engine = None engineNames = QTextToSpeech.availableEngines() if len(engineNames) > 0: engineName = engineNames[0] self.engine = QTextToSpeech(engineName) self.engine.stateChanged.connect(self.stateChanged) self.setWindowTitle( 'QTextToSpeech Example ({})'.format(engineName)) self.voices = [] for voice in self.engine.availableVoices(): self.voices.append(voice) self.voiceCombo.addItem(voice.name()) else: self.setWindowTitle('QTextToSpeech Example (no engines available)') self.sayButton.setEnabled(False) def say(self): self.sayButton.setEnabled(False) self.engine.setVoice(self.voices[self.voiceCombo.currentIndex()]) self.engine.setVolume(float(self.volumeSlider.value()) / 100) self.engine.say(self.text.text()) def stateChanged(self, state): if (state == QTextToSpeech.State.Ready): self.sayButton.setEnabled(True)
def create_editor(self, parent, option, index): editor = QComboBox(parent) current_value = index.model().data(index, Qt.EditRole) current_index = 0 for idx, value in enumerate(self.ext_values): if current_value == value: current_index = idx editor.addItem(value) editor.setCurrentIndex(current_index) return editor
def add_combobox_for(self, row: int, name: str, description: ChoicesOption) -> None: combobox = QComboBox() def on_changed(index: int) -> None: self.settings.__dict__[name] = combobox.itemData(index) for text, value in description.choices.items(): combobox.addItem(text, value) combobox.setCurrentText( description.text_for_value(self.settings.__dict__[name]) ) combobox.currentIndexChanged.connect(on_changed) self.addWidget(combobox, row, 1, Qt.AlignRight)
def _init_widgets(self): if self._state.am_none(): return layout = QVBoxLayout() input_layout = QHBoxLayout() symbol_name = QLineEdit(self) symbol_type = QComboBox(self) symbol_type.addItem("As Bytes", bytes) symbol_type.addItem("As Int", int) symbol_butt = QPushButton(self, text="Go") input_layout.addWidget(symbol_name) input_layout.addWidget(symbol_type) input_layout.addWidget(symbol_butt) def symbol_solve(): name = symbol_name.text() tmp = [ symbol for symbol in self.workspace.instance.symbols if symbol.args[0].split('_')[0] == name ] if len(tmp) != 1: QMessageBox.critical(self, "Symbol Not found", "Invalid Symbol Name") return typ_name = symbol_type.currentText() typ = symbol_type.currentData() res = self.solver(tmp[0], typ) row = self.table.rowCount() self.table.insertRow(row) self.table.setItem(row, 0, QTableWidgetItem(name)) self.table.setItem(row, 1, QTableWidgetItem(typ_name)) self.table.setItem(row, 2, QTableWidgetItem(str(res))) symbol_butt.clicked.connect(symbol_solve) table = QTableWidget(self) table.setColumnCount(len(self.COLUMNS)) table.setHorizontalHeaderLabels(self.COLUMNS) self.table = table layout.addLayout(input_layout) layout.addWidget(table) layout.setSpacing(0) layout.addStretch(0) layout.setContentsMargins(2, 2, 2, 2) self.setLayout(layout)
def createOptionsGroupBox(self): self.optionsGroupBox = QGroupBox("Options") buttonsOrientationLabel = QLabel("Orientation of buttons:") buttonsOrientationComboBox = QComboBox() buttonsOrientationComboBox.addItem("Horizontal", Qt.Horizontal) buttonsOrientationComboBox.addItem("Vertical", Qt.Vertical) buttonsOrientationComboBox.currentIndexChanged[int].connect(self.buttonsOrientationChanged) self.buttonsOrientationComboBox = buttonsOrientationComboBox optionsLayout = QGridLayout() optionsLayout.addWidget(buttonsOrientationLabel, 0, 0) optionsLayout.addWidget(self.buttonsOrientationComboBox, 0, 1) optionsLayout.setColumnStretch(2, 1) self.optionsGroupBox.setLayout(optionsLayout)
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))
def createEditor(self, parent, option, index): comboBox = QComboBox(parent) comboBox.addItem(id_text) return comboBox
class AudioTest(QMainWindow): PUSH_MODE_LABEL = "Enable push mode" PULL_MODE_LABEL = "Enable pull mode" SUSPEND_LABEL = "Suspend playback" RESUME_LABEL = "Resume playback" DurationSeconds = 1 ToneSampleRateHz = 600 DataSampleRateHz = 44100 def __init__(self): super(AudioTest, self).__init__() self.m_device = QAudioDeviceInfo.defaultOutputDevice() self.m_output = None self.initializeWindow() self.initializeAudio() def initializeWindow(self): layout = QVBoxLayout() self.m_deviceBox = QComboBox() self.m_deviceBox.activated[int].connect(self.deviceChanged) for deviceInfo in QAudioDeviceInfo.availableDevices(QAudio.AudioOutput): self.m_deviceBox.addItem(deviceInfo.deviceName(), deviceInfo) layout.addWidget(self.m_deviceBox) self.m_modeButton = QPushButton() self.m_modeButton.clicked.connect(self.toggleMode) self.m_modeButton.setText(self.PUSH_MODE_LABEL) layout.addWidget(self.m_modeButton) self.m_suspendResumeButton = QPushButton( clicked=self.toggleSuspendResume) self.m_suspendResumeButton.setText(self.SUSPEND_LABEL) layout.addWidget(self.m_suspendResumeButton) volumeBox = QHBoxLayout() volumeLabel = QLabel("Volume:") self.m_volumeSlider = QSlider(Qt.Horizontal, minimum=0, maximum=100, singleStep=10) self.m_volumeSlider.valueChanged.connect(self.volumeChanged) volumeBox.addWidget(volumeLabel) volumeBox.addWidget(self.m_volumeSlider) layout.addLayout(volumeBox) window = QWidget() window.setLayout(layout) self.setCentralWidget(window) def initializeAudio(self): self.m_pullTimer = QTimer(self) self.m_pullTimer.timeout.connect(self.pullTimerExpired) self.m_pullMode = True self.m_format = QAudioFormat() self.m_format.setSampleRate(self.DataSampleRateHz) self.m_format.setChannelCount(1) self.m_format.setSampleSize(16) self.m_format.setCodec('audio/pcm') self.m_format.setByteOrder(QAudioFormat.LittleEndian) self.m_format.setSampleType(QAudioFormat.SignedInt) info = QAudioDeviceInfo(QAudioDeviceInfo.defaultOutputDevice()) if not info.isFormatSupported(self.m_format): qWarning("Default format not supported - trying to use nearest") self.m_format = info.nearestFormat(self.m_format) self.m_generator = Generator(self.m_format, self.DurationSeconds * 1000000, self.ToneSampleRateHz, self) self.createAudioOutput() def createAudioOutput(self): self.m_audioOutput = QAudioOutput(self.m_device, self.m_format) self.m_audioOutput.notify.connect(self.notified) self.m_audioOutput.stateChanged.connect(self.handleStateChanged) self.m_generator.start() self.m_audioOutput.start(self.m_generator) self.m_volumeSlider.setValue(self.m_audioOutput.volume() * 100) def deviceChanged(self, index): self.m_pullTimer.stop() self.m_generator.stop() self.m_audioOutput.stop() self.m_device = self.m_deviceBox.itemData(index) self.createAudioOutput() def volumeChanged(self, value): if self.m_audioOutput is not None: self.m_audioOutput.setVolume(value / 100.0) def notified(self): qWarning("bytesFree = %d, elapsedUSecs = %d, processedUSecs = %d" % ( self.m_audioOutput.bytesFree(), self.m_audioOutput.elapsedUSecs(), self.m_audioOutput.processedUSecs())) def pullTimerExpired(self): if self.m_audioOutput is not None and self.m_audioOutput.state() != QAudio.StoppedState: chunks = self.m_audioOutput.bytesFree() // self.m_audioOutput.periodSize() for _ in range(chunks): data = self.m_generator.read(self.m_audioOutput.periodSize()) if data is None or len(data) != self.m_audioOutput.periodSize(): break self.m_output.write(data) def toggleMode(self): self.m_pullTimer.stop() self.m_audioOutput.stop() if self.m_pullMode: self.m_modeButton.setText(self.PULL_MODE_LABEL) self.m_output = self.m_audioOutput.start() self.m_pullMode = False self.m_pullTimer.start(20) else: self.m_modeButton.setText(self.PUSH_MODE_LABEL) self.m_pullMode = True self.m_audioOutput.start(self.m_generator) self.m_suspendResumeButton.setText(self.SUSPEND_LABEL) def toggleSuspendResume(self): if self.m_audioOutput.state() == QAudio.SuspendedState: qWarning("status: Suspended, resume()") self.m_audioOutput.resume() self.m_suspendResumeButton.setText(self.SUSPEND_LABEL) elif self.m_audioOutput.state() == QAudio.ActiveState: qWarning("status: Active, suspend()") self.m_audioOutput.suspend() self.m_suspendResumeButton.setText(self.RESUME_LABEL) elif self.m_audioOutput.state() == QAudio.StoppedState: qWarning("status: Stopped, resume()") self.m_audioOutput.resume() self.m_suspendResumeButton.setText(self.SUSPEND_LABEL) elif self.m_audioOutput.state() == QAudio.IdleState: qWarning("status: IdleState") stateMap = { QAudio.ActiveState: "ActiveState", QAudio.SuspendedState: "SuspendedState", QAudio.StoppedState: "StoppedState", QAudio.IdleState: "IdleState"} def handleStateChanged(self, state): qWarning("state = " + self.stateMap.get(state, "Unknown"))