def append_widget( layout: QtWidgets.QLayout, widgets: Tuple[QtWidgets.QWidget] = None) -> Tuple[QtWidgets.QWidget]: for widget in widgets: layout.addWidget(widget) return widgets
def add_layout_items(layout: QLayout, items: Iterable[Union[QWidget, QLayout]]): for item in items: if isinstance(item, QWidget): layout.addWidget(item) else: layout.addLayout(item)
def makeLabelIn(parent: QtWidgets.QLayout, text, alignFlag: QtCore.Qt.AlignmentFlag): label = QtWidgets.QLabel(text) label.setAlignment(alignFlag) parent.addWidget(label) return label
def create_collapsible_box_add_to_parent_layout( title: str, parent_layout: QLayout, title_backgroup_color="") -> CollapsibleBox: collapsible_box = CollapsibleBox( title, title_backgroup_color=title_backgroup_color) parent_layout.addWidget(collapsible_box) return collapsible_box
def add_widget_to_layout(widget: QWidget, layout: QLayout, name: str) -> None: """Adds a widget that belongs to a spacific layout :param widget: The widget being inserted :param layout: Layout to which widget is inserted :param name: Name of widget :return: None """ widget.setObjectName(name) layout.addWidget(widget)
def add_button(parent: QLayout, title: str, on_click, cls: str=None, mtd: str=None, width: int=30, height: int=None) -> QPushButton: tr = QPushButton(title) tr.setFixedHeight(width) if height is not None: tr.setFixedHeight(height) tr.clicked.connect(on_click) parent.addWidget(tr) if cls is not None and mtd is not None: if not Auth.get_access(cls, mtd): tr.setEnabled(False) tr.setStyleSheet("background-color: grey;") return tr
def add_create_section(self, layout: QtWidgets.QLayout): self._w_create_gb = QtWidgets.QGroupBox("Create", self) create_gb_layout = QtWidgets.QHBoxLayout(self._w_create_gb) self._w_create_gb.setLayout(create_gb_layout) self._cbb_create_user = QtWidgets.QComboBox(self) self._cbb_create_user.setEditable(True) self._cbb_create_user.setMinimumWidth(150) create_gb_layout.addWidget(self._cbb_create_user) self._le_create_chars = QtWidgets.QLineEdit(self) create_gb_layout.addWidget(self._le_create_chars) self._pb_create = QtWidgets.QPushButton("Добавить", self) create_gb_layout.addWidget(self._pb_create) layout.addWidget(self._w_create_gb) self._pb_create.clicked.connect(self.handle_create)
def create_collapsible_box_with_sub_form_layout_and_add_to_parent_layout( title: str, parent_layout: QLayout, fold: bool = True, title_backgroup_color="") -> Tuple[CollapsibleBox, QFormLayout]: collapsible_box = CollapsibleBox( title, title_backgroup_color=title_backgroup_color) parent_layout.addWidget(collapsible_box) form_layout = QFormLayout() collapsible_box.setContentLayout(form_layout) collapsible_box.set_fold(fold) return collapsible_box, form_layout
def add_remove_section(self, layout: QtWidgets.QLayout): self._w_remove_gb = QtWidgets.QGroupBox("Remove", self) remove_gb_layout = QtWidgets.QHBoxLayout(self._w_remove_gb) self._w_remove_gb.setLayout(remove_gb_layout) self._cbb_remove_user = QtWidgets.QComboBox(self) self._cbb_remove_user.setMinimumWidth(150) self._cbb_remove_user.setEditable(False) remove_gb_layout.addWidget(self._cbb_remove_user) self._le_remove_chars = QtWidgets.QLineEdit(self) remove_gb_layout.addWidget(self._le_remove_chars) self._pb_remove = QtWidgets.QPushButton("Удалить", self) remove_gb_layout.addWidget(self._pb_remove) layout.addWidget(self._w_remove_gb) self._w_remove_gb.setEnabled(False) self._pb_remove.clicked.connect(self.handle_remove)
def initScatter(self, layout: QLayout): cos_scatter = CosScatter() gauss_scatter = GaussScatter() self.image_calculator.scatter = gauss_scatter sca_box = QCheckBox("Установить рассеивающую пластинку") self.sca_box = sca_box def change_state(state: bool): if state: self.image_calculator.scatter = cos_scatter else: self.image_calculator.scatter = gauss_scatter self.updateCanvas() sca_box.stateChanged.connect(change_state) layout.addWidget(sca_box)
def create_strategy_inputs(parameters: List[Union[int, tuple]], strategyName: str, groupBoxLayout: QLayout) -> Tuple[list, list]: """ This function will create strategy slots and labels based on the parameters provided to the layout. :param parameters: Parameters to add to strategy GUI slots. These are fetched from get_param_types() in strategies. :param strategyName: Name of strategy. :param groupBoxLayout: Layout to add the slots to. :return: Tuple of labels and values lists. """ labels = [] values = [] for paramIndex, parameter in enumerate(parameters): if type(parameter) == tuple: label = QLabel(parameter[0]) parameter = parameter[ 1:] # Set parameter to just the last element so we can use this later. elif parameter == int: label = QLabel(f'{strategyName} input {paramIndex + 1}') parameter = [parameter] else: raise TypeError( "Please make sure your function get_param_types() only has ints or tuples." ) if parameter[0] == int: value = QSpinBox() value.setRange(1, 500) elif parameter[0] == float: value = QDoubleSpinBox() elif parameter[0] == str: value = QLineEdit() elif parameter[0] == tuple: elements = parameter[1] value = QComboBox() value.addItems(elements) else: raise TypeError("Invalid type of parameter provided.") labels.append(label) values.append(value) groupBoxLayout.addRow(label, value) line = get_h_line() labels.append(line) groupBoxLayout.addWidget(line) return values, labels
def _build_refining_ui(self, layout: QtWidgets.QLayout) -> None: self.box_refining_lower = self._make_spin_box() layout.addWidget(self.box_refining_lower) layout.setStretchFactor(self.box_refining_lower, 1) layout.addWidget(self._make_divider()) self.box_refining_randomise = self._make_randomise_box() layout.addWidget(self.box_refining_randomise) layout.setStretchFactor(self.box_refining_randomise, 0) layout.addWidget(self._make_divider()) self.box_refining_upper = self._make_spin_box() layout.addWidget(self.box_refining_upper) layout.setStretchFactor(self.box_refining_upper, 1)
def add_control_element(self, layout: QLayout, config_object: ConfigObject, option_name: str, note_type_id=None, deck_id=None): """Adds a control element to a layout. Takes a ConfigObject as input and determines the type of the option. Then, a suitable control element is placed in the layout. """ # Add title and description label = QLabel(f"<b>{config_object.friendly}</b><br/><small>{config_object.description}</small>") label.setWordWrap(True) label.adjustSize() label.setContentsMargins(0, 10, 0, 0) layout.addWidget(label) # Add control element (dropdown, checkbox, etc.) if config_object.type is OptionType.BOOLEAN: checkbox = QCheckBox(config_object.name) checkbox.setChecked(config_object.value) checkbox.stateChanged.connect(lambda new: self.update_state(option_name, bool(new), note_type_id, deck_id)) checkbox.setContentsMargins(50, 0, 50, 0) layout.addWidget(checkbox) elif config_object.type is OptionType.LANG: language_select = QComboBox() [language_select.addItem(lang["English name"], lang["Code"]) for lang in self.language_list] language_select.setEditable(True) language_select.setCurrentIndex(next(i for i, x in enumerate(self.language_list) if x["Code"] == config_object.value)) language_select.currentIndexChanged.connect(lambda new: self.update_state(option_name, language_select.itemData(new), note_type_id, deck_id)) layout.addWidget(language_select) elif config_object.type is OptionType.COUNTRY: pass # CountryListControl(config_object.name, config_object, layout, self, lambda new: self.update_state(option_name, new, note_type_id, deck_id), self.country_list) elif config_object.type is OptionType.TEXT: control = QLineEdit(config_object.value) layout.addWidget(control) control.textChanged.connect(lambda new: self.update_state(option_name, new, note_type_id, deck_id)) elif config_object.type is OptionType.STRINGLIST: StringListControl(config_object.name, config_object, layout, self, lambda new: self.update_state(option_name, new, note_type_id, deck_id)) elif config_object.type is OptionType.CHOICE: dropdown = QComboBox() dropdown.addItems(config_object.options) dropdown.setCurrentIndex(next(i for i, x in enumerate(config_object.options) if x == config_object.value)) layout.addWidget(dropdown) dropdown.currentIndexChanged.connect(lambda new: self.update_state(option_name, new, note_type_id, deck_id)) dropdown.currentTextChanged.connect(lambda new: self.update_state(option_name, new, note_type_id, deck_id))
def stat_window(window: SimpleGui, main_layout: QLayout): """This function repaint main window from statistic table""" children: list = window.children() hide_all_children(window) return_button = QPushButton("Вернуться") with Database() as base: _, cursor = base statistic = get_statistic(cursor) table = QTableWidget() table.setColumnCount(4) table.setRowCount(len(statistic)) minimal_width = 40 for col in range(len(statistic[0]) - 1): table.setHorizontalHeaderItem( col, QTableWidgetItem(statistics_table[col])) for row in range(len(statistic)): for col in range(1, len(statistic[0])): table.setItem(row, col - 1, QTableWidgetItem(str(statistic[row][col]))) table.resizeColumnsToContents() table.verticalHeader().setVisible(False) for col in range(len(statistic[0]) - 1): minimal_width = minimal_width + table.columnWidth(col) window.setFixedWidth(minimal_width) window.center() main_layout.addWidget(table) def return_function(): """This function delete all new widgets and repair old""" return_button.hide() main_layout.removeWidget(return_button) table.hide() main_layout.removeWidget(table) show_all_children_in_list(children) return_button.setParent(None) table.setParent(None) window.set_starting_size() return_button.clicked.connect(return_function) main_layout.addWidget(return_button)
def add_grant_section(self, layout: QtWidgets.QLayout): self._w_gb_grant = QtWidgets.QGroupBox("Grant", self) grant_gb_layout = QtWidgets.QHBoxLayout(self._w_gb_grant) self._w_gb_grant.setLayout(grant_gb_layout) self._cbb_grant_user_1 = QtWidgets.QComboBox(self) self._cbb_grant_user_1.setMinimumWidth(100) self._cbb_grant_user_1.setEditable(False) grant_gb_layout.addWidget(self._cbb_grant_user_1) self._cbb_grant_user_2 = QtWidgets.QComboBox(self) self._cbb_grant_user_2.setMinimumWidth(100) self._cbb_grant_user_2.setEditable(False) grant_gb_layout.addWidget(self._cbb_grant_user_2) self._le_grant_chars = QtWidgets.QLineEdit(self) grant_gb_layout.addWidget(self._le_grant_chars) self._pb_grant = QtWidgets.QPushButton("Передать", self) grant_gb_layout.addWidget(self._pb_grant) layout.addWidget(self._w_gb_grant) self._pb_grant.clicked.connect(self.handle_grant)
def _add_slider(self, parent: qtw.QLayout, callback, smin: int, smax: int, sfac: float = 1.0, initial: float = None, label: str = None): """ Utility method to easily add sliders """ qlabel = None slider = qtw.QSlider(qtc.Qt.Horizontal, self) slider.setFocusPolicy(qtc.Qt.NoFocus) slider.setMinimum(smin) slider.setMaximum(smax) if initial is not None: slider.setValue(initial * sfac) # proxies the slider-released-event to update the label # containing the current value and applying the factor # before invoking the provided callback def proxy(): val = slider.value() / sfac if qlabel is not None: qlabel.setText(str(val)) callback(val) slider.sliderReleased.connect(proxy) if label is not None: layout = qtw.QHBoxLayout() layout.addWidget(qtw.QLabel(label)) qlabel = qtw.QLabel(str(initial or "")) layout.addWidget(qlabel) parent.addLayout(layout) parent.addWidget(slider)
def addItemToLayout(self, layout: QLayout, isType: str, name: str) -> None: item = MediaWidget(self.control, isType, name) item.setFixedSize(160, 195) itemLayout = QVBoxLayout() item.setLayout(itemLayout) label = QLabel() label.setFixedSize(150, 150) label.setPixmap(QPixmap(self.pixmaps[isType])) label.setScaledContents(True) itemLayout.addWidget(label) label = QLabel(name) label.setFixedWidth(150) label.setStyleSheet("color:#afafaf;" "font-size: 12px;" "font-weight: bold;") label.setAlignment(Qt.AlignCenter) label.setWordWrap(True) itemLayout.addWidget(label) layout.addWidget(item)
def _build_list_ui(self, layout: QtWidgets.QLayout) -> None: class Validator(QtGui.QValidator): def validate(self, input, pos): try: [float(f) for f in _parse_list_pyon(input)] return QtGui.QValidator.Acceptable, input, pos except Exception: return QtGui.QValidator.Intermediate, input, pos self.box_list_pyon = QtWidgets.QLineEdit() self.box_list_pyon.setValidator(Validator(self)) layout.addWidget(self.box_list_pyon) layout.addWidget(self._make_divider()) self.box_list_randomise = self._make_randomise_box() layout.addWidget(self.box_list_randomise) layout.setStretchFactor(self.box_list_randomise, 0)
def addWidget(self,widget:QWidget, layout:QLayout): layout.addWidget(widget, self.position, 0) self.position+=1
def add_buttons_to_layout(self, layout: QLayout) -> None: for button in self.buttons: layout.addWidget(button)
def _build_linear_ui(self, layout: QtWidgets.QLayout) -> None: self.box_linear_start = self._make_spin_box() layout.addWidget(self.box_linear_start) layout.setStretchFactor(self.box_linear_start, 1) layout.addWidget(self._make_divider()) self.box_linear_points = QtWidgets.QSpinBox() self.box_linear_points.setMinimum(2) self.box_linear_points.setMaximum( 2**16) # A gratuitous, but probably generous restriction self.box_linear_points.setSuffix(" pts") layout.addWidget(self.box_linear_points) layout.setStretchFactor(self.box_linear_points, 0) self.box_linear_randomise = self._make_randomise_box() layout.addWidget(self.box_linear_randomise) layout.setStretchFactor(self.box_linear_randomise, 0) layout.addWidget(self._make_divider()) self.box_linear_stop = self._make_spin_box() layout.addWidget(self.box_linear_stop) layout.setStretchFactor(self.box_linear_stop, 1)
def workers(window: SimpleGui, main_layout: QLayout) -> None: """This function repaint main window to workers-information window""" children: list = window.children() hide_all_children(window) return_button = QPushButton("Вернуться") with Database() as base: _, cursor = base all_workers = get_all_workers(cursor) table = QTableWidget() columns_count = len(workers_table) + 2 table.setColumnCount(columns_count) table.setRowCount(len(all_workers)) minimal_width = 40 invert_button_list = list() edit_button_list = list() def update_row(id_worker: str, number_row: int) -> None: """Function update row in table after update information in database""" with Database() as base_local: _, cursor_local = base_local worker_info = get_info_from_worker(cursor_local, id_worker) for col_number in range(len(worker_info)): table.setItem(number_row, col_number, QTableWidgetItem(str(worker_info[col_number]))) def invert_function(worker_id: str, row_number: int) -> Callable[[str, int], None]: """this function create new sub-function from invert worker-status in table""" def inner_function() -> None: """This function is anonymous function from buttons in table""" reverse_status(worker_id, row_number) def reverse_status(id_worker: str, number_row: int) -> None: """This function reverse status from selected worker""" with Database() as base_local: connection, cursor_local = base_local invert_worker_status(cursor_local, id_worker) connection.commit() update_row(id_worker, number_row) return inner_function def edit_function(worker_id: str, row_number: int) -> Callable[[str, int], None]: """this function create new sub-function from edit worker-data in table""" def inner_function() -> None: """this function is anonymous function from button in table""" edit_data(worker_id, row_number) def edit_data(id_worker: str, number_row: int) -> None: """this function call new window from edit worker-data""" worker_edit(window, main_layout, children, id_worker, lambda: update_row(id_worker, number_row)) return inner_function for col in range(len(workers_table)): table.setHorizontalHeaderItem(col, QTableWidgetItem(workers_table[col])) table.setHorizontalHeaderItem(columns_count - 2, QTableWidgetItem("Изменить статус")) table.setHorizontalHeaderItem(columns_count - 1, QTableWidgetItem("Редактировать")) for row in range(len(all_workers)): invert_button_list.append(list()) invert_button_list[-1].append(QPushButton("Принять/Уволить")) (invert_button_list[-1]).append(invert_function(str(all_workers[row][0]), row)) (invert_button_list[-1][0]).clicked.connect(invert_button_list[-1][1]) edit_button_list.append(list()) edit_button_list[-1].append(QPushButton("Изменить")) (edit_button_list[-1]).append(edit_function(str(all_workers[row][0]), row)) (edit_button_list[-1][0]).clicked.connect(edit_button_list[-1][1]) for col in range(len(all_workers[0])): table.setItem(row, col, QTableWidgetItem(str(all_workers[row][col]))) table.setCellWidget(row, columns_count - 2, invert_button_list[row][0]) table.setCellWidget(row, columns_count - 1, edit_button_list[row][0]) table.resizeColumnsToContents() table.verticalHeader().setVisible(False) for col in range(columns_count): minimal_width = minimal_width + table.columnWidth(col) window.setFixedWidth(minimal_width) window.center() main_layout.addWidget(table) def return_function() -> None: """This function delete all new widgets and repair old""" return_button.hide() main_layout.removeWidget(return_button) table.hide() main_layout.removeWidget(table) show_all_children_in_list(children) return_button.setParent(None) table.setParent(None) window.set_starting_size() return_button.clicked.connect(return_function) main_layout.addWidget(return_button)
def _build_fixed_ui(self, layout: QtWidgets.QLayout) -> None: self.box_value = self._make_spin_box() layout.addWidget(self.box_value)
def setLayout(self, layout: QtWidgets.QLayout) -> None: layout.addWidget(self.getCanvas().native) super().setLayout(layout)
def _build_linear_ui(self, layout: QtWidgets.QLayout) -> None: self.box_linear_start = self._make_spin_box() layout.addWidget(self.box_linear_start) layout.setStretchFactor(self.box_linear_start, 1) layout.addWidget(self._make_divider()) self.box_linear_points = QtWidgets.QSpinBox() self.box_linear_points.setMinimum(2) self.box_linear_points.setValue(21) # Somewhat gratuitously restrict the number of scan points for sizing, and to # avoid the user accidentally pasting in millions of points, etc. self.box_linear_points.setMaximum(0xffff) self.box_linear_points.setSuffix(" pts") layout.addWidget(self.box_linear_points) layout.setStretchFactor(self.box_linear_points, 0) self.box_linear_randomise = self._make_randomise_box() layout.addWidget(self.box_linear_randomise) layout.setStretchFactor(self.box_linear_randomise, 0) layout.addWidget(self._make_divider()) self.box_linear_stop = self._make_spin_box() layout.addWidget(self.box_linear_stop) layout.setStretchFactor(self.box_linear_stop, 1)
def worker_edit(window: SimpleGui, main_layout: QLayout, no_show_children: List[QWidget], worker_id: str, callback_funct: Callable) -> None: """This function repaint main window to BUG-information window""" children: list = window.children() hide_all_children(window) old_size = window.size() new_widget = list() return_button = QPushButton("Вернуться") edit_button = QPushButton("Применить изменения") with Database() as base: _, cursor = base worker_info = get_info_from_worker(cursor, worker_id) minimal_width = 200 family_area = QLineEdit(worker_info[1]) new_widget.append(family_area) name_area = QLineEdit(worker_info[2]) new_widget.append(name_area) phone_area = QLineEdit(worker_info[3]) new_widget.append(phone_area) grade_box = QComboBox() posts = get_all_posts(cursor) current_index = 0 for post in posts: grade_box.addItem(post[1], post[0]) if post[1] == worker_info[5]: grade_box.setCurrentIndex(current_index) else: current_index += 1 new_widget.append(grade_box) label = QLabel("Пароль администратора") new_widget.append(label) pw = QLineEdit() pw.setEchoMode(QLineEdit.Password) new_widget.append(pw) window.setFixedWidth(minimal_width) window.center() def done_edit() -> None: """This function update new worker-data elements""" result_ok: bool = True if is_superuser_password(pw.text()): result_ok = result_ok and (False not in [ elem.isalpha() for elem in family_area.text() ]) result_ok = result_ok and (family_area.text() != "") result_ok = result_ok and (False not in [ elem.isalpha() for elem in name_area.text() ]) result_ok = result_ok and (name_area.text() != "") result_ok = result_ok and (False not in [ elem.isdigit() or elem == ' ' or elem == '-' or elem == '+' for elem in phone_area.text() ]) result_ok = result_ok and (phone_area.text() != "") if not result_ok: err_message_box("Некорректные данные!") else: result_ok = family_area.text() != worker_info[1] or\ name_area.text() != worker_info[2] or\ phone_area.text() != worker_info[3] or\ grade_box.currentText() != worker_info[5] if not result_ok: err_message_box("Данные не изменены!") else: with Database() as base: connection, local_cursor = base update_worker_info( local_cursor, worker_id, name_area.text(), family_area.text(), phone_area.text(), str(posts[grade_box.currentIndex()][0])) connection.commit() else: err_message_box("Неверный пароль администратора!") result_ok = False if result_ok: return_function() else: return def err_message_box(msg: str) -> None: """Create universal error message box""" msgbox = QMessageBox() msgbox.setText(msg) msgbox.setWindowTitle("Ошибка") msgbox.setStandardButtons(QMessageBox.Ok) msgbox.exec_() def return_function() -> None: """This function delete all new widgets and repair old""" for elem in new_widget: elem.hide() main_layout.removeWidget(elem) elem.setParent(None) show_selected_children_in_list(children, no_show_children) window.setFixedWidth(old_size.width()) window.setFixedHeight(old_size.height()) callback_funct() return_button.clicked.connect(return_function) edit_button.clicked.connect(done_edit) new_widget.append(edit_button) new_widget.append(return_button) for widget in new_widget: main_layout.addWidget(widget)
def add_buttons_to_layout(self, layout: QLayout) -> None: for button in self.buttons: layout.addWidget(button)