def _initialize(self): ## self.paramTPerm = self.field("paramTPerm") self.tabs.clear() self.total_answers = 0 self.radioGroups = {} filas = self.paramNPerm for x in range(filas): mygroupbox = QScrollArea() mygroupbox.setWidget(QWidget()) mygroupbox.setWidgetResizable(True) myform = QHBoxLayout(mygroupbox.widget()) cols = self.paramNCols.split(',') ansID = 0 radioGroupList = {} for col in cols: mygroupboxCol = QGroupBox() myformCol = QFormLayout() mygroupboxCol.setLayout(myformCol) for y in range(int(col)): ansID += 1 radioGroupList[ansID] = QButtonGroup() layoutRow = QHBoxLayout() for j in range(self.paramNAlts): myradio = QRadioButton(chr(97+j).upper()) layoutRow.addWidget(myradio) radioGroupList[ansID].addButton(myradio) self.total_answers += 1 myformCol.addRow(str(ansID), layoutRow) myform.addWidget(mygroupboxCol) self.radioGroups[chr(97+x).upper()] = radioGroupList self.tabs.addTab(mygroupbox, _('Model ') + chr(97+x).upper())
def __init__(self): super().__init__() self.setWindowTitle('Phone Book.') self.name = QLineEdit() self.number = QLineEdit() entry = QFormLayout() entry.addRow(QLabel('Name'), self.name) entry.addRow(QLabel('Number'), self.number) buttons = QHBoxLayout() button = QPushButton('&Add') button.clicked.connect(self._addEntry) buttons.addWidget(button) button = QPushButton('&Update') button.clicked.connect(self._updateEntry) buttons.addWidget(button) button = QPushButton('&Delete') button.clicked.connect(self._deleteEntry) buttons.addWidget(button) dataDisplay = QTableView() dataDisplay.setModel(PhoneDataModel()) layout = QVBoxLayout() layout.addLayout(entry) layout.addLayout(buttons) layout.addWidget(dataDisplay) self.setLayout(layout) self.show()
def setup_path_widgets(self): path_layout = QFormLayout() path_layout.addRow("Root:", self.widgets['path/project_root']) path_layout.addRow("Maps from:", self.widgets['path/path_mapping']) self.path_group = QGroupBox("Path") self.path_group.setLayout(path_layout)
def __init__(self, message, title): super(ErrorMessage, self).__init__() self.message = message # self.setWindowTitle(title) self.setStyleSheet(style.style_loader.stylesheet) self.label = QLabel(str(self.message), self) self.label_widget = QWidget(self) label_layout = QBoxLayout(QBoxLayout.LeftToRight) label_layout.addWidget(self.label) self.label_widget.setLayout(label_layout) self.submit_btn = QPushButton('OK', self) self.submit_btn.clicked.connect(self.submit) self.submit_btn_widget = QWidget(self) submit_btn_layout = QBoxLayout(QBoxLayout.LeftToRight) submit_btn_layout.addWidget(self.submit_btn) self.submit_btn_widget.setLayout(submit_btn_layout) layout = QFormLayout() layout.addRow(self.label_widget) layout.addRow(self.submit_btn_widget) self.setLayout(layout) self.show() self.setFixedHeight(self.height()) self.setFixedWidth(self.width()) self.close()
def create_config(self): box0 = QGroupBox('History') self.index['max_dataset_history'] = FormInt() self.index['recording_dir'] = FormStr() form_layout = QFormLayout() form_layout.addRow('Max History Size', self.index['max_dataset_history']) form_layout.addRow('Directory with recordings', self.index['recording_dir']) box0.setLayout(form_layout) box1 = QGroupBox('Default values') self.index['y_distance_presets'] = FormList() self.index['y_scale_presets'] = FormList() self.index['window_length_presets'] = FormList() form_layout = QFormLayout() form_layout.addRow('Signal scaling, presets', self.index['y_scale_presets']) form_layout.addRow('Distance between signals, presets', self.index['y_distance_presets']) form_layout.addRow('Window length, presets', self.index['window_length_presets']) box1.setLayout(form_layout) main_layout = QVBoxLayout() main_layout.addWidget(box0) main_layout.addWidget(box1) main_layout.addStretch(1) self.setLayout(main_layout)
def __init__(self, parent=None): super(LocationFilterPage, self).__init__(parent) self.xSpinBox = QDoubleSpinBox() self.xSpinBox.setMinimum(float('-inf')) self.xSpinBox.setMaximum(float('inf')) self.xSpinBox.setDecimals(6) self.ySpinBox = QDoubleSpinBox() self.ySpinBox.setMinimum(float('-inf')) self.ySpinBox.setMaximum(float('inf')) self.ySpinBox.setDecimals(6) self.tolSpinBox = QDoubleSpinBox() self.tolSpinBox.setMinimum(0) self.tolSpinBox.setMaximum(float('inf')) self.tolSpinBox.setDecimals(6) groupLayout = QFormLayout() groupLayout.addRow("X:", self.xSpinBox) groupLayout.addRow("Y:", self.ySpinBox) groupLayout.addRow("Tolerance:", self.tolSpinBox) self.group = QGroupBox("Lokace") self.group.setCheckable(True) self.group.setChecked(False) self.group.setLayout(groupLayout) layout = QVBoxLayout() layout.addWidget(self.group) layout.addStretch(1) self.setLayout(layout)
def __populate_groupbox(self): """ """ layout = QVBoxLayout() self.groupbox.setLayout(layout) first_line = QHBoxLayout() self.visibility_label = QLabel("Show ROI:") first_line.addWidget(self.visibility_label) self.visibility_checkbox = QCheckBox(self) self.visibility_checkbox.setCheckable(True) self.visibility_checkbox.toggled.connect(self.__checkbox_cb) first_line.addWidget(self.visibility_checkbox) self.select_button = QPushButton("+", self) self.select_button.setToolTip("Select ROI with the mouse") self.select_button.clicked.connect(self.activate_selection) first_line.addWidget(self.select_button) layout.addLayout(first_line) form_layout = QFormLayout() layout.addLayout(form_layout) for prop in self.group.properties: form_layout.addRow(prop.prop.name, prop)
class QtFormView(QWidget): def __init__(self, parent=None): super(QtFormView, self).__init__(parent) self.form_layout = QFormLayout() self.setLayout(self.form_layout) def add_row(self, label, widget): self.form_layout.addRow(label, widget)
def __init__(self, *args, **kwargs): # Add the layout. layout = QFormLayout() super().__init__("Create a new task", layout, *args, **kwargs) # Add the input fields. self.input_title = QLineEdit() layout.addRow("Title:", self.input_title) self.input_description = QPlainTextEdit() layout.addRow("Description:", self.input_description)
def __init__(self, settings, directory, check_id_fct, annotations_path, parent=None): super().__init__(parent) # FIXME Delayed refactoring of check_id_fct and annotations_path. # Variables section. library_id = settings["libraryID"] library_type = settings["libraryType"] api_key = settings["apiKey"] self._zotero = ZoteroWrap(library_id, library_type, api_key, directory) # Widgets section. model = ZoteroTableModel(self._zotero, check_id_fct, annotations_path) model.load() proxy_model = QSortFilterProxyModel() proxy_model.setSourceModel(model) proxy_model.setDynamicSortFilter(True) proxy_model.setFilterCaseSensitivity(Qt.CaseInsensitive) proxy_model.setFilterKeyColumn(-1) # NB: All columns. self.view = QTableView(self) self.view.setModel(proxy_model) self.view.setCornerButtonEnabled(False) self.view.setEditTriggers(QAbstractItemView.NoEditTriggers) self.view.setSelectionBehavior(QAbstractItemView.SelectRows) self.view.setSelectionMode(QAbstractItemView.SingleSelection) # NB: Triggers a call to sortByColumn() which sorts by the first column. self.view.setSortingEnabled(True) self.view.setWordWrap(False) self.view.verticalHeader().hide() self.filter_edit = FilterEdit(self.view) # NB: The thread does not begin executing until start() is called. self.refresh_thread = ZoteroRefreshThread(model, self) # Layouts section. header_layout = QFormLayout() header_layout.addRow("Filter:", self.filter_edit) header_layout.setFieldGrowthPolicy(QFormLayout.AllNonFixedFieldsGrow) utils.configure_form_layout(header_layout) main_layout = QVBoxLayout() main_layout.addLayout(header_layout) main_layout.addWidget(self.view) self.setLayout(main_layout) # Signals section. self.filter_edit.textChanged.connect(proxy_model.setFilterFixedString) self.refresh_thread.started.connect(self.refresh_started) self.refresh_thread.finished.connect(self.refresh_finished)
def __init__(self): super().__init__() self.setTitle(_('Selection of correct answers')) self.setSubTitle(_('Select the correct answers for each exam model')) layout = QFormLayout() self.setLayout(layout) self.tabs = QTabWidget() layout.addRow(self.tabs) self.paramNAlts = None self.paramNCols = None self.paramNPerm = None
def widget_download(self): self.form_download_urls = QGroupBox("Download subscribed threads") layout = QFormLayout() self.button_download = self.createButton("Normal Update", self.click_process_download) layout.addRow(self.button_download) self.label_download_debug = QLabel("Press the button above to download updates to the threads you've subscribed to.") layout.addRow(self.label_download_debug) self.form_download_urls.setLayout(layout)
def define_section2(self): """defining section 2: Specify allele details """ mywidget = QWidget(self) layout = QGridLayout() mywidget.setLayout(layout) a1_new = False self.allele1_sec = AlleleSection("Allele 1:", self) layout.addWidget(self.allele1_sec,0,0) a2_new = False self.allele2_sec = AlleleSection("Allele 2:", self) layout.addWidget(self.allele2_sec,0,1) #ToDo: add closest alleles! button_widget = QFrame(self) # contains both-checkbox & proceed-button layout2 = QFormLayout() button_widget.setLayout(layout2) # self.both_cbx = QCheckBox(self) # self.both_cbx.clicked.connect(self.select_both) # self.both_lbl = QLabel("Both alleles?") # self.both_lbl.setStyleSheet(general.label_style_main) # layout2.addRow(self.both_lbl, self.both_cbx) # self.msg = QLabel("When selecting this option, please ensure\nyou have entered details for both alleles.") # self.msg.setStyleSheet(general.label_style_normal) # layout2.addRow(self.msg) layout2.addRow(QLabel("\n\n")) if a1_new: self.allele1_sec.checkbox.setChecked(True) if a2_new: self.allele2_sec.checkbox.setChecked(True) elif a2_new: self.allele2_sec.checkbox.setChecked(True) # self.allele1_sec.checkbox.clicked.connect(self.unselect_both_cbx) self.allele1_sec.checkbox.clicked.connect(self.unselect_other_box) self.allele2_sec.checkbox.clicked.connect(self.unselect_other_box) # self.allele2_sec.checkbox.clicked.connect(self.unselect_both_cbx) self.ok_btn = ProceedButton("Proceed", [self.allele1_sec.checkbox, self.allele2_sec.checkbox], self.log, only1 = True) self.ok_btn.check_ready() self.ok_btn.clicked.connect(self.make_ENA_file) self.allele1_sec.selection_changed.connect(self.ok_btn.check_ready) self.allele2_sec.selection_changed.connect(self.ok_btn.check_ready) layout2.addRow(self.ok_btn) layout.addWidget(button_widget, 0 ,3) layout.setColumnStretch(0,1) layout.setColumnStretch(1,1) layout.setColumnStretch(2,0) self.sections.append(("(2) Specify allele details:", mywidget))
def createFormGroupBox(self): self.formGroupBox = QGroupBox("Entrée") simple = QCheckBox("Simplifier (pas de lignes intermédiaires)") # bool à basculer simple.clicked.connect(self._simple) self.expression = QLineEdit(str(self.tableau.expr)) layout = QFormLayout() layout.addRow(QLabel("(fraction rationnelle):"), self.expression) valid = QPushButton("Valider") valid.clicked.connect(self._createTableau) layout.addWidget(valid) layout.addWidget(simple) self.formGroupBox.setLayout(layout)
def widget_register_url(self): self.form_register_url = QGroupBox("Register new URL") layout = QFormLayout() self.text_input_new_url = QLineEdit() self.button_register_url = self.createButton("Register", self.click_process_new_url) layout.addRow(self.button_register_url, self.text_input_new_url) self.label_new_url_debug = QLabel("Enter URLs here and press 'Register' to add them to your subscriptions.") layout.addRow(self.label_new_url_debug) self.form_register_url.setLayout(layout)
def _templates_forms(templates_widgets): """Return the edition forms for the dict {type: {field: widget}}.""" forms = [] for type_widgets in templates_widgets.values(): form = QWidget() layout = QFormLayout() for field, widget in type_widgets.items(): layout.addRow(field + ":", widget) layout.setFieldGrowthPolicy(QFormLayout.ExpandingFieldsGrow) utils.configure_form_layout(layout) form.setLayout(layout) forms.append(form) return forms
def init_UI(self): self.log.debug("Opening ChangeExtIdDialog...") layout = QFormLayout() self.setLayout(layout) self.title = "Change a sample's external sample ID" self.sample_ext_field = QLineEdit(self) self.sample_ext_field.setText(self.sample_id_ext) layout.addRow(QLabel("New External Sample-ID:"), self.sample_ext_field) self.ok_btn = QPushButton("Save", self) layout.addRow(self.ok_btn) self.ok_btn.clicked.connect(self.on_clicked)
def __init__(self): super(QWidget, self).__init__() layout = QFormLayout() self.setLayout(layout) self.buildDependencies = QPlainTextEdit() self.buildDependencies.textChanged.connect(self.buildDependenciesChanged) self.buildDependencies.setMinimumHeight(70) layout.addRow('Build Dependencies', self.buildDependencies) self.runDependencies = QPlainTextEdit() self.runDependencies.textChanged.connect(self.runDependenciesChanged) self.runDependencies.setMinimumHeight(70) layout.addRow('Run Dependencies', self.runDependencies)
def initinformationpanel(self): self.mselabel = QLabel('No image selected') infoform = QFormLayout() infoform.addRow('MSE:', self.mselabel) imagebox = QGroupBox('Image') imagebox.setLayout(infoform) information = QDockWidget('Information') information.setFeatures(QDockWidget.DockWidgetFloatable) information.setFeatures(QDockWidget.DockWidgetMovable) information.setWidget(imagebox) self.addDockWidget(Qt.RightDockWidgetArea, information)
def __init__(self, *args, **kwargs): super(LanguagePage, self).__init__(*args, **kwargs) self.setTitle(self.tr("Language")) layout = QFormLayout() self.language = QLineEdit() layout.addRow(self.tr("Language as called in it's language"), self.language) self.setLayout(layout) self.registerField("language*", self.language)
def __init__(self): super().__init__() self.setTitle(_('Configuration of exam params')) self.setSubTitle(_('Enter the configuration parameters of the exam')) layout = QFormLayout(self) self.setLayout(layout) self.paramNEIDs = widgets.InputInteger( initial_value=8, min_value=0, max_value=16) self.registerField("paramNEIDs", self.paramNEIDs) self.paramNAlts = widgets.InputInteger(initial_value=3) self.registerField("paramNAlts", self.paramNAlts) self.paramNCols = widgets.InputCustomPattern(fixed_size=250, regex=r'[1-9][0-9]?(\,[1-9][0-9]?)+', placeholder=_('num,num,...')) self.registerField("paramNCols", self.paramNCols) self.paramNPerm = widgets.InputInteger(min_value=1, initial_value=2) self.registerField("paramNPerm", self.paramNPerm) ## self.paramTPerm = widgets.CustomComboBox(parent=self) ## self.paramTPerm.set_items([ ## _('No (recommended)'), ## _('Yes (experimental)'), ## ]) ## self.paramTPerm.setCurrentIndex(0) ## self.registerField("paramTPerm", self.paramTPerm) layout.addRow(_('Number of digits of the student ID ' '(0 to not scan IDs)'), self.paramNEIDs) layout.addRow(_('Number of choices per question'), self.paramNAlts) layout.addRow(_('Number of questions per answer box'), self.paramNCols) layout.addRow(_('Number of models of the exam'), self.paramNPerm)
def _setup_keybindings_ui(self): """ Create everything related to the keybindings tab """ layout = QFormLayout() self.keybinding_fullscreen_label = QLabel("Toggle Fullscreen:") self.keybinding_fullscreen = QKeySequenceEdit() layout.addRow(self.keybinding_fullscreen_label, self.keybinding_fullscreen) self.keybinding_save_image_label = QLabel("Save image:") self.keybinding_save_image = QKeySequenceEdit(QKeySequence(self.settings.keybinding_save_image)) layout.addRow(self.keybinding_save_image_label, self.keybinding_save_image) self.keybinding_trigger_image_label = QLabel("Trigger images via softwaretrigger:") self.keybinding_trigger_image = QKeySequenceEdit(QKeySequence(self.settings.keybinding_trigger_image)) layout.addRow(self.keybinding_trigger_image_label, self.keybinding_trigger_image) self.keybinding_open_dialog_label = QLabel("Open device dialog:") self.keybinding_open_dialog = QKeySequenceEdit(QKeySequence(self.settings.keybinding_open_dialog)) layout.addRow(self.keybinding_open_dialog_label, self.keybinding_open_dialog) self.keybindings_widget.setLayout(layout)
def __init__(self, parent=None): super(BasicFilterPage, self).__init__(parent) self.blockCombo = QComboBox() self.deviceCombo = QComboBox() self.unitCombo = QComboBox() self.combos = {'block': self.blockCombo, \ 'device': self.deviceCombo, \ 'unit': self.unitCombo} groupLayout = QFormLayout() groupLayout.addRow("Skupina měření:", self.blockCombo) groupLayout.addRow("Přístroj:", self.deviceCombo) groupLayout.addRow("Veličina:", self.unitCombo) filterGroup = QGroupBox("Základní filtry") filterGroup.setLayout(groupLayout) self.deviatedValuesCheckbox = QCheckBox() valuesLayout = QFormLayout() valuesLayout.addRow("Mimo odchylku:", self.deviatedValuesCheckbox) valuesGroup = QGroupBox("Hodnoty") valuesGroup.setLayout(valuesLayout) layout = QVBoxLayout() layout.addWidget(filterGroup) layout.addSpacing(12) layout.addWidget(valuesGroup) layout.addStretch(1) self.setLayout(layout)
class EdgeInfo(AbstractInfo): """ This class implements the information box for generic edges. """ def __init__(self, mainwindow, parent=None): """ Initialize the generic edge information box. :type mainwindow: MainWindow :type parent: QWidget """ super().__init__(mainwindow, parent) self.h1 = Header('General', self) self.typeKey = Key('Type', self) self.typeField = Str(self) self.typeField.setReadOnly(True) self.sourceKey = Key('Source', self) self.sourceField = Str(self) self.sourceField.setReadOnly(True) self.targetKey = Key('Target', self) self.targetField = Str(self) self.targetField.setReadOnly(True) self.generalLayout = QFormLayout() self.generalLayout.setSpacing(0) self.generalLayout.addRow(self.typeKey, self.typeField) self.generalLayout.addRow(self.sourceKey, self.sourceField) self.generalLayout.addRow(self.targetKey, self.targetField) self.mainLayout = QVBoxLayout(self) self.mainLayout.setAlignment(Qt.AlignTop) self.mainLayout.setContentsMargins(0, 0, 0, 0) self.mainLayout.setSpacing(0) self.mainLayout.addWidget(self.h1) self.mainLayout.addLayout(self.generalLayout) def updateData(self, edge): """ Fetch new information and fill the widget with data. :type edge: AbstractEdge """ self.sourceField.setValue(edge.source.id) self.targetField.setValue(edge.target.id) self.typeField.setValue(edge.shortname.capitalize()) self.typeField.home(True) self.typeField.deselect()
def createSolutionBox(self): self.solGroupBox = QGroupBox("Ensemble des solutions d'inéquation") self.solution = QLineEdit() layout = QFormLayout() choix = QComboBox() # for x in ["<=0","<0", ">=0",">0"] for x in self.inequations.keys(): choix.addItem(x) self.choixIneq = choix # associer le signal de changement d'inéquation au slot de self.solution.setText self.choixIneq.currentTextChanged.connect(self._fillbis) self.choixIneq.currentTextChanged.emit(self.choixIneq.currentText()) layout.addRow(QLabel("Inéquation de la forme f(x)"), self.choixIneq) layout.addRow(QLabel("ens. des solutions:"), self.solution) self.solGroupBox.setLayout(layout)
def __init__(self): super().__init__() self.setTitle(_('Scores for correct and incorrect answers')) self.setSubTitle(_('Enter the scores of correct and incorrect ' 'answers. The program will compute scores based ' 'on them. Setting these scores is optional.')) form_widget = QWidget(parent=self) table_widget = QWidget(parent=self) main_layout = QVBoxLayout(self) form_layout = QFormLayout(form_widget) table_layout = QVBoxLayout(table_widget) self.setLayout(main_layout) form_widget.setLayout(form_layout) table_widget.setLayout(table_layout) main_layout.addWidget(form_widget) main_layout.addWidget(table_widget) main_layout.setAlignment(table_widget, Qt.AlignHCenter) self.combo = widgets.CustomComboBox(parent=self) self.combo.set_items([ _('No scores'), _('Same score for all the questions'), _('Base score plus per-question weight'), ]) self.combo.currentIndexChanged.connect(self._update_combo) self.correct_score = widgets.InputScore(is_positive=True) correct_score_label = QLabel(_('Score for correct answers')) incorrect_score_label = QLabel(_('Score for incorrect answers')) blank_score_label = QLabel(_('Score for blank answers')) self.incorrect_score = widgets.InputScore(is_positive=False) self.blank_score = widgets.InputScore(is_positive=False) self.button_reset = QPushButton(_('Reset question weights')) button_defaults = QPushButton(_('Compute default scores')) self.weights_table = widgets.CustomTableView() weights_table_label = QLabel(_('Per-question score weights:')) form_layout.addRow(self.combo) form_layout.addRow(correct_score_label, self.correct_score) form_layout.addRow(incorrect_score_label, self.incorrect_score) form_layout.addRow(blank_score_label, self.blank_score) table_layout.addWidget(weights_table_label) table_layout.addWidget(self.weights_table) table_layout.addWidget(self.button_reset) table_layout.addWidget(button_defaults) table_layout.setAlignment(weights_table_label, Qt.AlignHCenter) table_layout.setAlignment(self.weights_table, Qt.AlignHCenter) table_layout.setAlignment(self.button_reset, Qt.AlignHCenter) table_layout.setAlignment(button_defaults, Qt.AlignHCenter) self.button_reset.clicked.connect(self._reset_weights) button_defaults.clicked.connect(self._compute_default_values) self.base_score_widgets = [ self.correct_score, correct_score_label, self.incorrect_score, incorrect_score_label, self.blank_score, blank_score_label, button_defaults, ] self.weights_widgets = [ self.weights_table, weights_table_label, ] self.current_mode = None
def to_editor(self, modify_callback, current_name): box = QGroupBox() szp = box.sizePolicy() szp.setVerticalPolicy(QSizePolicy.Maximum) box.setSizePolicy(szp) layout = QFormLayout() box.setLayout(layout) for n in self._v: editor_widget = n.to_editor(modify_callback, current_name + "." + n._name) if n._is_container: editor_widget.setTitle(n._name) layout.addRow(editor_widget) else: layout.addRow(n._name, editor_widget) return box
def __init__(self, parent=None): super(EditView, self).__init__(parent) self._layout = QBoxLayout(QBoxLayout.LeftToRight) self.setLayout(self._layout) self.setWindowTitle('Edit configuration') self._configurationTreeWidget = TreeWidget() self._configurationTreeWidget.setColumnCount(2) self._configurationTreeWidget.setHeaderLabels(["Configuration name", "Print amount"]) self._materialTreeWidget = TreeWidget() self._materialTreeWidget.setColumnCount(2) self._materialTreeWidget.setHeaderLabels(["Material name", "Print amount"]) self._initialize_material_model() self._currentConfiguration = None # type: Configuration config_widget = QWidget() self._configLayout = QBoxLayout(QBoxLayout.TopToBottom) self._nameField = QLineEdit() self._nameField.setEnabled(False) name_form_layout = QFormLayout() name_form_layout.addRow('Name:', self._nameField) self._configLayout.addLayout(name_form_layout) self._configLayout.addWidget(QLabel('List of configurations')) self._configLayout.addWidget(self._configurationTreeWidget) config_widget.setLayout(self._configLayout) self._saveButton = QPushButton("Save") material_widget = QWidget() self._materialLayout = QBoxLayout(QBoxLayout.TopToBottom) self._materialLayout.addWidget(self._saveButton) self._materialLayout.addWidget(QLabel('List of materials')) self._materialLayout.addWidget(self._materialTreeWidget) material_widget.setLayout(self._materialLayout) self._layout.addWidget(config_widget) self._layout.addWidget(material_widget) # add event listener for selection change self._configurationTreeWidget.setEditTriggers(self._configurationTreeWidget.NoEditTriggers) self._materialTreeWidget.setEditTriggers(self._materialTreeWidget.NoEditTriggers) self._configurationTreeWidget.itemDoubleClicked.connect(self._check_edit_configuration) self._materialTreeWidget.itemDoubleClicked.connect(self._check_edit_material) self._materialTreeWidget.expanded.connect(self._resize_columns) self._materialTreeWidget.collapsed.connect(self._resize_columns) self._materialTreeWidget.itemChecked.connect(self._on_toggle) self._saveButton.clicked.connect(self._save)
class ErgebnissVorlage(QWidget): def __init__(self, parent=None): super(ErgebnissVorlage, self).__init__(parent) self.auswahlAlter = QComboBox() self.auswahlAlter.addItem("Bitte auswählen") for i in range(3, 18): self.auswahlAlter.addItem("{} Jahre / Jahrgang {}".format(i, date.today().year - i)) self.auswahlGeschlecht = QComboBox() self.auswahlGeschlecht.addItem("Bitte auswählen") self.auswahlGeschlecht.addItem("Männlich") self.auswahlGeschlecht.addItem("Weiblich") self.printerProgress = QProgressBar() self.printerProgress.hide() self.mainLayout = QFormLayout() self.mainLayout.addRow(QLabel("Alter:"),self.auswahlAlter) self.mainLayout.addRow(QLabel("Geschlecht:"),self.auswahlGeschlecht) self.mainLayout.addRow(self.printerProgress) self._drucken = QPushButton("Drucken") self._drucken.clicked.connect(self.drucken) self.mainLayout.addRow(self._drucken) self.setLayout(self.mainLayout) def queryUsers(self,Alter:int, Geschlecht:bool)->list: return QueryTool().fetchAllByWhere("LG_NGD",WieAlt=Alter,Geschlecht=Geschlecht) def drucken(self): self.printerProgress.show() if (self.auswahlAlter.currentIndex() is 0) and (self.auswahlGeschlecht.currentIndex() is 0): Alter = range(3,18) Geschlecht = range(0,2) else: Alter = self.auswahlAlter.currentIndex()+2 Alter = range(Alter,Alter+1) Geschlecht = self.auswahlGeschlecht.currentIndex()-1 Geschlecht = range(Geschlecht,Geschlecht+1) self.printerProgress.setMaximum(len(Alter)*len(Geschlecht)*10) self.printerProgress.setValue(0) prog = 0 for a in Alter: for g in Geschlecht: for d in range(10): ErgebnissVorlagenDrucker(a,g,d) self.printerProgress.setValue(prog) prog +=1 self.printerProgress.hide()
def setupUi(self, MnStatusDlg): MnStatusDlg.setModal(True) layout = QVBoxLayout(MnStatusDlg) layout.setContentsMargins(10, 15, 10, 10) name = QLabel("<b><i>%s</i></b>" % self.mnAlias) name.setAlignment(Qt.AlignCenter) layout.addWidget(name) body = QFormLayout() body.setLabelAlignment(Qt.AlignRight) body.setVerticalSpacing(20) body.setContentsMargins(25, 10, 25, 30) body.addRow(QLabel("<b>Address</b>"), QLabel(self.statusData['addr'])) body.addRow(QLabel("<b>Tx Hash: idx</b>"), QLabel(self.statusData['txhash']+": "+str(self.statusData['outidx']))) body.addRow(QLabel("<b>Network</b>"), QLabel(self.statusData['network'])) body.addRow(QLabel("<b>Version</b>"), QLabel(str(self.statusData['version']))) body.addRow(QLabel("<b>Rank</b>"), QLabel(str(self.statusData['rank']))) body.addRow(QLabel("<b>Queue Position</b>"), QLabel(str(self.statusData['queue_pos']))) body.addRow(QLabel("<b>Active Time</b>"), QLabel(sec_to_time(self.statusData['activetime']))) body.addRow(QLabel("<b>Last Seen</b>"), QLabel(time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime(self.statusData['lastseen'])))) body.addRow(QLabel("<b>Last Paid</b>"), QLabel(time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime(self.statusData['lastpaid'])))) layout.addLayout(body) self.okButton = QPushButton('OK') self.okButton.clicked.connect(self.accept) layout.addWidget(self.okButton) sh = layout.sizeHint() self.setFixedSize(sh)
def _build_ui(self): layout = QGridLayout() tabs = QTabWidget() layout.addWidget(tabs) ts_bond_tab = QWidget() ts_options = QFormLayout(ts_bond_tab) self.tsbond_color = ColorButton(has_alpha_channel=False, max_size=(16, 16)) self.tsbond_color.set_color(self.settings.tsbond_color) ts_options.addRow("color:", self.tsbond_color) self.tsbond_transparency = QSpinBox() self.tsbond_transparency.setRange(1, 99) self.tsbond_transparency.setValue(self.settings.tsbond_transparency) self.tsbond_transparency.setSuffix("%") ts_options.addRow("transparency:", self.tsbond_transparency) self.tsbond_radius = QDoubleSpinBox() self.tsbond_radius.setRange(0.01, 1) self.tsbond_radius.setDecimals(3) self.tsbond_radius.setSingleStep(0.005) self.tsbond_radius.setSuffix(" \u212B") self.tsbond_radius.setValue(self.settings.tsbond_radius) ts_options.addRow("radius:", self.tsbond_radius) draw_tsbonds = QPushButton("draw TS bonds on selected atoms/bonds") draw_tsbonds.clicked.connect(self.run_tsbond) ts_options.addRow(draw_tsbonds) self.draw_tsbonds = draw_tsbonds erase_tsbonds = QPushButton("erase selected TS bonds") erase_tsbonds.clicked.connect(self.run_erase_tsbond) ts_options.addRow(erase_tsbonds) self.erase_tsbonds = erase_tsbonds bond_tab = QWidget() bond_options = QFormLayout(bond_tab) self.bond_halfbond = QCheckBox() self.bond_halfbond.setChecked(self.settings.bond_halfbond) self.bond_halfbond.setToolTip( "each half of the bond will be colored according to the atom's color" ) bond_options.addRow("half-bond:", self.bond_halfbond) self.bond_color = ColorButton(has_alpha_channel=True, max_size=(16, 16)) self.bond_color.set_color(self.settings.bond_color) self.bond_color.setEnabled( self.bond_halfbond.checkState() != Qt.Checked) self.bond_halfbond.stateChanged.connect( lambda state, widget=self.bond_color: self.bond_color.setEnabled( state != Qt.Checked)) bond_options.addRow("color:", self.bond_color) self.bond_radius = QDoubleSpinBox() self.bond_radius.setRange(0.01, 1) self.bond_radius.setDecimals(3) self.bond_radius.setSingleStep(0.005) self.bond_radius.setSuffix(" \u212B") self.bond_radius.setValue(self.settings.bond_radius) bond_options.addRow("radius:", self.bond_radius) draw_tsbonds = QPushButton("draw bond between selected atoms") draw_tsbonds.clicked.connect(self.run_bond) bond_options.addRow(draw_tsbonds) self.draw_tsbonds = draw_tsbonds erase_bonds = QPushButton("erase selected bonds") erase_bonds.clicked.connect( lambda *, ses=self.session: run(ses, "delete bonds sel")) bond_options.addRow(erase_bonds) self.erase_bonds = erase_bonds hbond_tab = QWidget() hbond_options = QFormLayout(hbond_tab) self.hbond_color = ColorButton(has_alpha_channel=True, max_size=(16, 16)) self.hbond_color.set_color(self.settings.hbond_color) hbond_options.addRow("color:", self.hbond_color) self.hbond_radius = QDoubleSpinBox() self.hbond_radius.setDecimals(3) self.hbond_radius.setSuffix(" \u212B") self.hbond_radius.setValue(self.settings.hbond_radius) hbond_options.addRow("radius:", self.hbond_radius) self.hbond_dashes = QSpinBox() self.hbond_dashes.setRange(0, 28) self.hbond_dashes.setSingleStep(2) self.hbond_radius.setSingleStep(0.005) self.hbond_dashes.setValue(self.settings.hbond_dashes) hbond_options.addRow("dashes:", self.hbond_dashes) draw_hbonds = QPushButton("draw H-bonds") draw_hbonds.clicked.connect(self.run_hbond) hbond_options.addRow(draw_hbonds) self.draw_hbonds = draw_hbonds erase_hbonds = QPushButton("erase all H-bonds") erase_hbonds.clicked.connect( lambda *, ses=self.session: run(ses, "~hbonds")) hbond_options.addRow(erase_hbonds) self.erase_hbonds = erase_hbonds tm_bond_tab = QWidget() tm_bond_options = QFormLayout(tm_bond_tab) self.tm_bond_color = ColorButton(has_alpha_channel=True, max_size=(16, 16)) self.tm_bond_color.set_color(self.settings.tm_bond_color) tm_bond_options.addRow("color:", self.tm_bond_color) self.tm_bond_radius = QDoubleSpinBox() self.tm_bond_radius.setDecimals(3) self.tm_bond_radius.setSuffix(" \u212B") self.tm_bond_radius.setValue(self.settings.tm_bond_radius) tm_bond_options.addRow("radius:", self.tm_bond_radius) self.tm_bond_dashes = QSpinBox() self.tm_bond_dashes.setRange(0, 28) self.tm_bond_dashes.setSingleStep(2) self.tm_bond_radius.setSingleStep(0.005) self.tm_bond_dashes.setValue(self.settings.tm_bond_dashes) tm_bond_options.addRow("dashes:", self.tm_bond_dashes) draw_tm_bonds = QPushButton("draw metal coordination bonds") draw_tm_bonds.clicked.connect(self.run_tm_bond) tm_bond_options.addRow(draw_tm_bonds) self.draw_tm_bonds = draw_tm_bonds erase_tm_bonds = QPushButton("erase all metal coordination bonds") erase_tm_bonds.clicked.connect(self.del_tm_bond) tm_bond_options.addRow(erase_tm_bonds) self.erase_tm_bonds = erase_tm_bonds bond_length_tab = QWidget() bond_length_layout = QFormLayout(bond_length_tab) self.bond_distance = QDoubleSpinBox() self.bond_distance.setRange(0.5, 10.0) self.bond_distance.setSingleStep(0.05) self.bond_distance.setValue(1.51) self.bond_distance.setSuffix(" \u212B") bond_length_layout.addRow("bond length:", self.bond_distance) self.move_fragment = QComboBox() self.move_fragment.addItems(["both", "smaller", "larger"]) bond_length_layout.addRow("move side:", self.move_fragment) bond_lookup = QGroupBox("bond length lookup:") bond_lookup_layout = QGridLayout(bond_lookup) bond_lookup_layout.addWidget( QLabel("elements:"), 0, 0, ) self.ele1 = QPushButton("C") self.ele1.setMinimumWidth( int(1.3 * self.ele1.fontMetrics().boundingRect("QQ").width())) self.ele1.setMaximumWidth( int(1.3 * self.ele1.fontMetrics().boundingRect("QQ").width())) self.ele1.setMinimumHeight( int(1.5 * self.ele1.fontMetrics().boundingRect("QQ").height())) self.ele1.setMaximumHeight( int(1.5 * self.ele1.fontMetrics().boundingRect("QQ").height())) self.ele1.setSizePolicy(QSizePolicy.Maximum, QSizePolicy.Maximum) ele_color = tuple(list(element_color(ELEMENTS.index("C")))[:-1]) self.ele1.setStyleSheet( "QPushButton { background: rgb(%i, %i, %i); color: %s; font-weight: bold; }" % (*ele_color, 'white' if sum(int(x < 130) - int(x > 225) for x in ele_color) - int(ele_color[1] > 225) + int(ele_color[2] > 200) >= 2 else 'black')) self.ele1.clicked.connect( lambda *args, button=self.ele1: self.open_ptable(button)) bond_lookup_layout.addWidget(self.ele1, 0, 1, Qt.AlignRight | Qt.AlignTop) bond_lookup_layout.addWidget(QLabel("-"), 0, 2, Qt.AlignHCenter | Qt.AlignVCenter) self.ele2 = QPushButton("C") self.ele2.setMinimumWidth( int(1.3 * self.ele2.fontMetrics().boundingRect("QQ").width())) self.ele2.setMaximumWidth( int(1.3 * self.ele2.fontMetrics().boundingRect("QQ").width())) self.ele2.setMinimumHeight( int(1.5 * self.ele2.fontMetrics().boundingRect("QQ").height())) self.ele2.setMaximumHeight( int(1.5 * self.ele2.fontMetrics().boundingRect("QQ").height())) self.ele2.setSizePolicy(QSizePolicy.Maximum, QSizePolicy.Maximum) ele_color = tuple(list(element_color(ELEMENTS.index("C")))[:-1]) self.ele2.setStyleSheet( "QPushButton { background: rgb(%i, %i, %i); color: %s; font-weight: bold; }" % (*ele_color, 'white' if sum(int(x < 130) - int(x > 225) for x in ele_color) - int(ele_color[1] > 225) + int(ele_color[2] > 200) >= 2 else 'black')) self.ele2.clicked.connect( lambda *args, button=self.ele2: self.open_ptable(button)) bond_lookup_layout.addWidget(self.ele2, 0, 3, Qt.AlignLeft | Qt.AlignTop) bond_lookup_layout.addWidget(QLabel("bond order:"), 1, 0) self.bond_order = BondOrderSpinBox() self.bond_order.setRange(1., 3.) self.bond_order.setValue(1) self.bond_order.setSingleStep(0.5) self.bond_order.setDecimals(1) self.bond_order.valueChanged.connect(self.check_bond_lengths) bond_lookup_layout.addWidget(self.bond_order, 1, 1, 1, 3) bond_lookup_layout.setColumnStretch(0, 0) bond_lookup_layout.setColumnStretch(1, 0) bond_lookup_layout.setColumnStretch(2, 0) bond_lookup_layout.setColumnStretch(3, 1) bond_length_layout.addRow(bond_lookup) self.status = QStatusBar() self.status.setSizeGripEnabled(False) bond_lookup_layout.addWidget(self.status, 2, 0, 1, 4) self.do_bond_change = QPushButton("change selected bond lengths") self.do_bond_change.clicked.connect(self.change_bond_length) bond_length_layout.addRow(self.do_bond_change) tabs.addTab(bond_tab, "covalent bonds") tabs.addTab(ts_bond_tab, "TS bonds") tabs.addTab(hbond_tab, "H-bonds") tabs.addTab(tm_bond_tab, "coordination bonds") tabs.addTab(bond_length_tab, "bond length") self.tool_window.ui_area.setLayout(layout) self.tool_window.manage(None)
def __init__(self, templateDirectory): super().__init__() self.templateDirectory = templateDirectory self.setWindowTitle(i18n("Create new Template")) self.setLayout(QVBoxLayout()) buttons = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel) buttons.accepted.connect(self.accept) buttons.rejected.connect(self.reject) mainWidget = QWidget() explanation = QLabel( i18n( "This allows you to make a template document with guides.\nThe width and height are the size of the live-area, the safe area is the live area minus the margins, and the full image is the live area plus the bleeds." )) explanation.setWordWrap(True) self.layout().addWidget(explanation) self.layout().addWidget(mainWidget) self.layout().addWidget(buttons) mainWidget.setLayout(QHBoxLayout()) elements = QWidget() elements.setLayout(QVBoxLayout()) previewLayout = QWidget() previewLayout.setLayout(QVBoxLayout()) mainWidget.layout().addWidget(elements) mainWidget.layout().addWidget(previewLayout) self.imagePreview = QLabel() self.imagePreview.setMinimumSize(256, 256) previewLayout.layout().addWidget(self.imagePreview) self.templateName = QLineEdit() self.templateName.setPlaceholderText("...") elements.layout().addWidget(self.templateName) templateBGColor = QPushButton(i18n("Select background color")) templateBGColor.clicked.connect(self.slot_call_color_dialog) previewLayout.layout().addWidget(templateBGColor) self.DPI = QSpinBox() self.DPI.setMaximum(1200) self.DPI.setValue(300) self.spn_width = QDoubleSpinBox() self.spn_width.setMaximum(10000) self.spn_height = QDoubleSpinBox() self.spn_height.setMaximum(10000) self.widthUnit = simpleUnitBox() self.heightUnit = simpleUnitBox() widgetSize = QWidget() sizeForm = QFormLayout() sizeForm.addRow(i18n("DPI:"), self.DPI) widthLayout = QHBoxLayout() widthLayout.addWidget(self.spn_width) widthLayout.addWidget(self.widthUnit) sizeForm.addRow(i18n("Width:"), widthLayout) heightLayout = QHBoxLayout() heightLayout.addWidget(self.spn_height) heightLayout.addWidget(self.heightUnit) sizeForm.addRow(i18n("Height:"), heightLayout) widgetSize.setLayout(sizeForm) elements.layout().addWidget(widgetSize) marginAndBleed = QTabWidget() elements.layout().addWidget(marginAndBleed) margins = QWidget() marginForm = QGridLayout() margins.setLayout(marginForm) self.marginLeft = QDoubleSpinBox() self.marginLeft.setMaximum(1000) self.marginLeftUnit = simpleUnitBox() self.marginRight = QDoubleSpinBox() self.marginRight.setMaximum(1000) self.marginRightUnit = simpleUnitBox() self.marginTop = QDoubleSpinBox() self.marginTop.setMaximum(1000) self.marginTopUnit = simpleUnitBox() self.marginBottom = QDoubleSpinBox() self.marginBottom.setMaximum(1000) self.marginBottomUnit = simpleUnitBox() marginForm.addWidget(QLabel(i18n("Left:")), 0, 0, Qt.AlignRight) marginForm.addWidget(self.marginLeft, 0, 1) marginForm.addWidget(self.marginLeftUnit, 0, 2) marginForm.addWidget(QLabel(i18n("Top:")), 1, 0, Qt.AlignRight) marginForm.addWidget(self.marginTop, 1, 1) marginForm.addWidget(self.marginTopUnit, 1, 2) marginForm.addWidget(QLabel(i18n("Right:")), 2, 0, Qt.AlignRight) marginForm.addWidget(self.marginRight, 2, 1) marginForm.addWidget(self.marginRightUnit, 2, 2) marginForm.addWidget(QLabel(i18n("Bottom:")), 3, 0, Qt.AlignRight) marginForm.addWidget(self.marginBottom, 3, 1) marginForm.addWidget(self.marginBottomUnit, 3, 2) marginAndBleed.addTab(margins, i18n("Margins")) bleeds = QWidget() bleedsForm = QGridLayout() bleeds.setLayout(bleedsForm) self.bleedLeft = QDoubleSpinBox() self.bleedLeft.setMaximum(1000) self.bleedLeftUnit = simpleUnitBox() self.bleedRight = QDoubleSpinBox() self.bleedRight.setMaximum(1000) self.bleedRightUnit = simpleUnitBox() self.bleedTop = QDoubleSpinBox() self.bleedTop.setMaximum(1000) self.bleedTopUnit = simpleUnitBox() self.bleedBottom = QDoubleSpinBox() self.bleedBottom.setMaximum(1000) self.bleedBottomUnit = simpleUnitBox() bleedsForm.addWidget(QLabel(i18n("Left:")), 0, 0, Qt.AlignRight) bleedsForm.addWidget(self.bleedLeft, 0, 1) bleedsForm.addWidget(self.bleedLeftUnit, 0, 2) bleedsForm.addWidget(QLabel(i18n("Top:")), 1, 0, Qt.AlignRight) bleedsForm.addWidget(self.bleedTop, 1, 1) bleedsForm.addWidget(self.bleedTopUnit, 1, 2) bleedsForm.addWidget(QLabel(i18n("Right:")), 2, 0, Qt.AlignRight) bleedsForm.addWidget(self.bleedRight, 2, 1) bleedsForm.addWidget(self.bleedRightUnit, 2, 2) bleedsForm.addWidget(QLabel(i18n("Bottom:")), 3, 0, Qt.AlignRight) bleedsForm.addWidget(self.bleedBottom, 3, 1) bleedsForm.addWidget(self.bleedBottomUnit, 3, 2) marginAndBleed.addTab(bleeds, i18n("Bleeds")) if QLocale().system().measurementSystem() is QLocale.MetricSystem: self.setDefaults("European") else: self.setDefaults("American") self.spn_width.valueChanged.connect(self.updateImagePreview) self.widthUnit.currentIndexChanged.connect(self.updateImagePreview) self.spn_height.valueChanged.connect(self.updateImagePreview) self.heightUnit.currentIndexChanged.connect(self.updateImagePreview) self.marginLeft.valueChanged.connect(self.updateImagePreview) self.marginLeftUnit.currentIndexChanged.connect( self.updateImagePreview) self.marginRight.valueChanged.connect(self.updateImagePreview) self.marginRightUnit.currentIndexChanged.connect( self.updateImagePreview) self.marginTop.valueChanged.connect(self.updateImagePreview) self.marginTopUnit.currentIndexChanged.connect(self.updateImagePreview) self.marginBottom.valueChanged.connect(self.updateImagePreview) self.marginBottomUnit.currentIndexChanged.connect( self.updateImagePreview) self.bleedLeft.valueChanged.connect(self.updateImagePreview) self.bleedLeftUnit.currentIndexChanged.connect(self.updateImagePreview) self.bleedRight.valueChanged.connect(self.updateImagePreview) self.bleedRightUnit.currentIndexChanged.connect( self.updateImagePreview) self.bleedTop.valueChanged.connect(self.updateImagePreview) self.bleedTopUnit.currentIndexChanged.connect(self.updateImagePreview) self.bleedBottom.valueChanged.connect(self.updateImagePreview) self.bleedBottomUnit.currentIndexChanged.connect( self.updateImagePreview) self.updateImagePreview()
def initUI(self): mainLayout = QVBoxLayout() layH1 = QHBoxLayout() layH2 = QHBoxLayout() layH1.addWidget(self.leftList) layH1.addWidget(self.rightStack) self.cancelbtn = QPushButton(self.tr("Cancel")) self.okbtn = QPushButton(self.tr("OK")) # self.cancelbtn.setVisible(False) self.okbtn.setDefault(True) layH2.addStretch(1) layH2.addWidget(self.cancelbtn) layH2.addWidget(self.okbtn) mainLayout.addLayout(layH1) mainLayout.addLayout(layH2) self.setLayout(mainLayout) # left list self.leftList.addItem(self.tr("General")) self.leftList.addItem(self.tr("Editor")) self.leftList.addItem(self.tr("Update")) self.leftList.setMaximumWidth(150) # right stack w = QWidget() layw = QVBoxLayout() # general g = QGroupBox(self.tr("General")) glayout = QFormLayout() label1 = QLabel(self.tr("select UI language:")) self.langCombo = QComboBox() self.fillLangItems(self.langCombo) # .addItems(self.getLangList()) self.langCombo.setMinimumWidth(150) label2 = QLabel(self.tr("Number of recent files:")) self.recentcountspin = QSpinBox() self.recentcountspin.setMinimum(1) self.recentcountspin.setMaximum(30) glayout.addRow(label1, self.langCombo) glayout.addRow(label2, self.recentcountspin) g.setLayout(glayout) layw.addWidget(g) # advanced g2 = QGroupBox(self.tr("Advanced")) labeladv1 = QLabel(self.tr("Export qss When save qsst:")) self.checkboxAutoExportQss = QCheckBox() self.checkboxAutoExportQss.setToolTip( self. tr("Option for whether export qss when save qsst file each time.")) layh1 = QHBoxLayout() layh1.addWidget(labeladv1) layh1.addStretch(1) layh1.addWidget(self.checkboxAutoExportQss) g2layout = QVBoxLayout() g2layout.addLayout(layh1) g2.setLayout(g2layout) layw.addWidget(g2) # advanced g3 = QGroupBox(self.tr("UI Skin")) labeladv1 = QLabel(self.tr("Select the ui skin:")) self.skinCombo = QComboBox() self.skinCombo.setToolTip(self.tr("Select the ui skin.")) self.skindir = os.path.join(os.path.dirname(__file__), "skin") for f in os.listdir(self.skindir): if f.endswith(".qss") or f.endswith(".QSS"): self.skinCombo.addItem(os.path.basename(f)) layh1 = QHBoxLayout() layh1.addWidget(labeladv1) layh1.addStretch(1) layh1.addWidget(self.skinCombo) labelskin2 = QLabel(self.tr("Manage skins:")) skinaddr = QPushButton(self.tr("Skin Management")) skinaddr.setToolTip(self.tr("Open the skin directory.")) skinaddr.clicked.connect(lambda: os.startfile(self.skindir)) layh2 = QHBoxLayout() layh2.addWidget(labelskin2) layh2.addStretch(1) layh2.addWidget(skinaddr) g3layout = QVBoxLayout() g3layout.addLayout(layh1) g3layout.addLayout(layh2) g3.setLayout(g3layout) layw.addWidget(g3) layw.addStretch(1) w.setLayout(layw) self.rightStack.addWidget(w) # CodeEditor SettingPannel self.rightStack.addWidget(self.win.editor.settings.settingPanel()) # right stack for update w3 = QWidget() layw3 = QVBoxLayout() # update setting g31 = QGroupBox(self.tr("update check")) self.checkboxUpdate = QCheckBox(self.tr("auto check for update")) labtmp = QLabel(self.tr("update checking frequency:")) self.updateCombo = QComboBox() self.updateCombo.setToolTip( self.tr("setup frequency for checking update")) self.updateCombo.addItem(self.tr("Each startup"), "start") self.updateCombo.addItem(self.tr("Every day"), "day") self.updateCombo.addItem(self.tr("Every week"), "week") self.updateCombo.addItem(self.tr("Every month"), "month") self.updateCombo.setEnabled(False) self.checkboxUpdate.stateChanged.connect(self.updateCombo.setEnabled) ltmpv = QVBoxLayout() ltmph = QHBoxLayout() ltmpv.addWidget(self.checkboxUpdate) ltmpv.addLayout(ltmph) ltmph.addWidget(labtmp) ltmph.addStretch(1) ltmph.addWidget(self.updateCombo) g31.setLayout(ltmpv) tmp1 = self.win.config["update.autocheck"] tmp2 = self.win.config["update.checkfreq"] if not isinstance(tmp1, bool): tmp1 = True self.checkboxUpdate.setChecked(tmp1) if not tmp2: tmp2 = "start" tmpi = self.updateCombo.findData(tmp2) if tmpi: self.updateCombo.setCurrentIndex(tmpi) layw3.addWidget(g31) layw3.addStretch(1) w3.setLayout(layw3) self.rightStack.addWidget(w3) # action for dialog self.leftList.currentRowChanged.connect( self.rightStack.setCurrentIndex) self.cancelbtn.clicked.connect(lambda: (self.cancel(), self.close())) self.okbtn.clicked.connect(lambda: (self.apply(), self.close())) # actions self.recentcountspin.valueChanged.connect( lambda x: self.changedOptions.__setitem__("file.recentcount", x)) self.langCombo.currentIndexChanged.connect( lambda i: self.changedOptions.__setitem__( "general.language", self.langCombo.itemData(i))) self.checkboxUpdate.stateChanged.connect( lambda b: self.changedOptions.update({"update.autocheck": b})) self.updateCombo.currentIndexChanged.connect( lambda i: self.changedOptions.__setitem__( "update.checkfreq", self.updateCombo.itemData(i))) self.checkboxAutoExportQss.stateChanged.connect( lambda b: self.changedOptions.update({"advance.autoexportqss": b})) self.skinCombo.currentTextChanged.connect(lambda t: (self.applyskin( t), self.changedOptions.update({"general.skin": t})))
class WidgetCombinacionGanadora(QWidget): def __init__(self, licitacion, parent=None): super().__init__(parent=parent) self.licitacion = licitacion self.combinacion_ganadora = self.licitacion.combinacion_ganadora() self.caja_principal = QVBoxLayout() self.marco_lote = QGroupBox("Por Lote") self.caja_lote = QGridLayout() self.tabla_lote = QTableWidget(5, 1) self.marco_totales = QGroupBox("Totales") self.caja_totales = QHBoxLayout() self.formulario_totales = QFormLayout() self.llenar_tabla_lote() self.llenar_formulario_totales() self.tabla_lote.setStyleSheet( "QTableWidget {border:0px solid transparent}") self.tabla_lote.horizontalHeader().setVisible(False) self.tabla_lote.verticalHeader().setVisible(False) self.tabla_lote.setEnabled(True) self.tabla_lote.setSelectionBehavior(QAbstractItemView.SelectItems) self.tabla_lote.setSelectionMode(QAbstractItemView.ExtendedSelection) self.tabla_lote.setEditTriggers(QAbstractItemView.NoEditTriggers) self.tabla_lote.setSizeAdjustPolicy( QAbstractScrollArea.AdjustToContentsOnFirstShow) self.installEventFilter(self) self.formulario_totales.setHorizontalSpacing(25) self.resizeColumnsToMaximumContent() self.caja_lote.addWidget(self.tabla_lote, 0, 0) self.caja_lote.setColumnStretch(1, 1) self.marco_totales.setLayout(self.caja_totales) self.caja_totales.addLayout(self.formulario_totales) self.caja_totales.addStretch(1) self.marco_lote.setLayout(self.caja_lote) self.caja_principal.addWidget(self.marco_lote) self.caja_principal.addWidget(self.marco_totales) self.caja_principal.addStretch(1) self.setLayout(self.caja_principal) self.resize(self.sizeHint()) def llenar_tabla_lote(self): fuente_negrita = QFont() print(fuente_negrita.family()) #fuente_negrita.setBold(True) item_lotes = QTableWidgetItem("Lote") item_lotes.setFont(fuente_negrita) item_empresas = QTableWidgetItem("Empresa") item_empresas.setFont(fuente_negrita) item_ofertas = QTableWidgetItem("Oferta") item_ofertas.setFont(fuente_negrita) item_descuentos = QTableWidgetItem("Descuento") item_descuentos.setFont(fuente_negrita) item_ofertas_finales = QTableWidgetItem("Oferta Final") item_ofertas_finales.setFont(fuente_negrita) self.tabla_lote.setItem(0, 0, item_lotes) self.tabla_lote.setItem(1, 0, item_empresas) self.tabla_lote.setItem(2, 0, item_ofertas) self.tabla_lote.setItem(3, 0, item_descuentos) self.tabla_lote.setItem(4, 0, item_ofertas_finales) for lote in self.licitacion.lotes: self.tabla_lote.setColumnCount(self.tabla_lote.columnCount() + 1) columna = self.tabla_lote.columnCount() - 1 item_lote = QTableWidgetItem(lote.obtener_descripcion()) item_lote.setTextAlignment(Qt.AlignCenter) self.tabla_lote.setItem(0, columna, item_lote) for posibilidad in self.licitacion.combinacion_ganadora( ).posibilidades: if posibilidad.lote_contenido(lote): for oferta in posibilidad.conjunto_ofertas.ofertas: if oferta.lote == lote: item_empresa = QTableWidgetItem( oferta.empresa.nombre) item_empresa.setTextAlignment(Qt.AlignCenter) self.tabla_lote.setItem(1, columna, item_empresa) item_oferta = QTableWidgetItem("{0:,.3f}".format( oferta.valor)) item_oferta.setTextAlignment(Qt.AlignCenter) self.tabla_lote.setItem(2, columna, item_oferta) if posibilidad.adicional.es_nulo( ) or not posibilidad.adicional.conjunto_ofertas.oferta_contenida( oferta): item_descuento = QTableWidgetItem( "{0:.3f}%".format(0)) item_descuento.setTextAlignment(Qt.AlignCenter) self.tabla_lote.setItem( 3, columna, item_descuento) item_oferta_final = QTableWidgetItem( "{0:,.3f}".format(oferta.valor)) item_oferta_final.setTextAlignment( Qt.AlignCenter) self.tabla_lote.setItem( 4, columna, item_oferta_final) else: item_descuento = QTableWidgetItem( "{0:.2f}%".format( abs(posibilidad.adicional.porcentaje))) item_descuento.setTextAlignment(Qt.AlignCenter) self.tabla_lote.setItem( 3, columna, item_descuento) item_oferta_final = QTableWidgetItem( "{0:,.3f}".format(oferta.valor + posibilidad.adicional. valor_en_oferta(oferta))) item_oferta_final.setTextAlignment( Qt.AlignCenter) self.tabla_lote.setItem( 4, columna, item_oferta_final) break break def llenar_formulario_totales(self): cantidad_de_lotes_totales = len(self.licitacion.lotes) cantidad_de_lotes_adjudicados = self.combinacion_ganadora.cantidad_lotes_ofertados( ) cantidad_de_empresas_totales = len(self.licitacion.empresas) cantidad_de_empresas_ganadoras = self.combinacion_ganadora.cantidad_empresas_ganadoras( ) valor_total_sin_descuento = self.combinacion_ganadora.valor() descuentos_realizados = "" for adicional in self.combinacion_ganadora.adicionales_aplicados(): descuentos_realizados += "{0:.2f}%, ".format( abs(adicional.porcentaje)) descuentos_realizados = descuentos_realizados[:-2].strip() if descuentos_realizados == "": descuentos_realizados = "Ninguno" valor_total_con_descuento = self.combinacion_ganadora.valor_con_adicional( ) etiqueta_cantidad_de_lotes_totales = QLabel( "Cantidad de lotes totales:") etiqueta_cantidad_de_lotes_adjudicados = QLabel( "Cantidad de lote adjudicados:") etiqueta_cantidad_de_empresas_totales = QLabel( "Cantidad de empresas totales:") etiqueta_cantidad_de_empresas_ganadoras = QLabel( "Cantidad de empresas ganadoras:") etiqueta_valor_total_sin_descuento = QLabel( "Valor total sin descuento:") etiqueta_descuentos_realizados = QLabel("Descuentos realizados:") etiqueta_valor_total_con_descuento = QLabel( "Valor total con descuento:") campo_cantidad_de_lotes_totales = QLabel( str(cantidad_de_lotes_totales)) campo_cantidad_de_lotes_adjudicados = QLabel( str(cantidad_de_lotes_adjudicados)) campo_cantidad_de_empresas_totales = QLabel( str(cantidad_de_empresas_totales)) campo_cantidad_de_empresas_ganadoras = QLabel( str(cantidad_de_empresas_ganadoras)) campo_valor_sin_descuento = QLabel( "{0:,.3f}".format(valor_total_sin_descuento)) campo_valor_con_descuento = QLabel( "{0:,.3f}".format(valor_total_con_descuento)) campo_descuentos_realizados = QLabel(str(descuentos_realizados)) self.formulario_totales.addRow(etiqueta_cantidad_de_lotes_totales, campo_cantidad_de_lotes_totales) self.formulario_totales.addRow(etiqueta_cantidad_de_lotes_adjudicados, campo_cantidad_de_lotes_adjudicados) self.formulario_totales.addRow(etiqueta_cantidad_de_empresas_totales, campo_cantidad_de_empresas_totales) self.formulario_totales.addRow(etiqueta_cantidad_de_empresas_ganadoras, campo_cantidad_de_empresas_ganadoras) self.formulario_totales.addRow(etiqueta_valor_total_sin_descuento, campo_valor_sin_descuento) self.formulario_totales.addRow(etiqueta_descuentos_realizados, campo_descuentos_realizados) self.formulario_totales.addRow(etiqueta_valor_total_con_descuento, campo_valor_con_descuento) def resizeColumnsToMaximumContent(self): self.tabla_lote.resizeColumnsToContents() maximo = max([ self.tabla_lote.columnWidth(i) for i in range(self.tabla_lote.columnCount()) ]) for i in range(0, self.tabla_lote.columnCount()): self.tabla_lote.setColumnWidth(i, maximo) def tocado(self): self.tabla_lote.setRowCount(5) self.tabla_empresa.setRowCount(5) def eventFilter(self, source, event): if (event.type() == QEvent.KeyPress and event.matches(QKeySequence.Copy)): self.copySelection() return True return super().eventFilter(source, event) def copySelection(self): selection = self.tabla_lote.selectedIndexes() if selection: rows = sorted(index.row() for index in selection) columns = sorted(index.column() for index in selection) rowcount = rows[-1] - rows[0] + 1 colcount = columns[-1] - columns[0] + 1 table = [[''] * colcount for _ in range(rowcount)] for index in selection: row = index.row() - rows[0] column = index.column() - columns[0] table[row][column] = index.data() stream = StringIO() writer(stream, delimiter='\t').writerows(table) QGuiApplication.clipboard().setText(stream.getvalue())
def __init__(self, parent=None): QWidget.__init__(self, parent) self.interface_lng_val = parent.interface_lng_val self.con = parent.con self.full_dir = parent.full_dir self.par = parent if self.con.open(): table = QTableWidget(7, 2) table.setColumnWidth(0, 150) table.setColumnWidth(1, 230) table.setFixedSize(674, 480) table.setHorizontalHeaderLabels(["Параметр", "Значение"]) # rho.type rho_type_lbl = QLabel('rho.type') self.rho_type = QComboBox() rho_type_list = ["uniform", "demo"] self.rho_type.addItems(rho_type_list) table.setCellWidget(0, 1, self.rho_type) table.setCellWidget(0, 0, rho_type_lbl) # rho.value rho_value_lbl = QLabel('rho.value') self.rho_value = QLineEdit() table.setCellWidget(1, 1, self.rho_value) table.setCellWidget(1, 0, rho_value_lbl) # nu.type nu_type_lbl = QLabel('nu.type') self.nu_type = QComboBox() nu_type_list = ["uniform", "demo"] self.nu_type.addItems(nu_type_list) table.setCellWidget(2, 1, self.nu_type) table.setCellWidget(2, 0, nu_type_lbl) # nu.value nu_value_lbl = QLabel('nu.value') self.nu_value = QLineEdit() table.setCellWidget(3, 1, self.nu_value) table.setCellWidget(3, 0, nu_value_lbl) # E.type E_type_lbl = QLabel('E.type') self.E_type = QComboBox() E_type_list = ["uniform", "demo"] self.E_type.addItems(E_type_list) table.setCellWidget(4, 1, self.E_type) table.setCellWidget(4, 0, E_type_lbl) # E.value E_value_lbl = QLabel('E.value') self.E_value = QLineEdit() table.setCellWidget(5, 1, self.E_value) table.setCellWidget(5, 0, E_value_lbl) # planeStress planeStress_type_lbl = QLabel('planeStress') self.planeStress_type = QComboBox() planeStress_type_list = ["yes", "no"] self.planeStress_type.addItems(planeStress_type_list) table.setCellWidget(6, 1, self.planeStress_type) table.setCellWidget(6, 0, planeStress_type_lbl) # вывод значений параметров if 'mechanicalProperties' in self.con.tables(): #print('вах') query = QtSql.QSqlQuery() query.exec("SELECT * FROM mechanicalProperties") if query.isActive(): query.first() value_list = [] while query.isValid(): value_res = query.value('value') value_list.append(value_res) query.next() # rho_type rho_type_mas = self.rho_type.count() for i in range(rho_type_mas): if self.rho_type.itemText(i) == value_list[0]: self.rho_type.setCurrentIndex(i) # rho_value self.rho_value.setText(value_list[1]) # nu_type nu_type_mas = self.nu_type.count() for i in range(nu_type_mas): if self.nu_type.itemText(i) == value_list[2]: self.nu_type.setCurrentIndex(i) # nu_value self.nu_value.setText(value_list[3]) # E_type E_type_mas = self.E_type.count() for i in range(E_type_mas): if self.E_type.itemText(i) == value_list[4]: self.E_type.setCurrentIndex(i) # E_value self.E_value.setText(value_list[5]) # planeStress_type planeStress_type_mas = self.planeStress_type.count() for i in range(planeStress_type_mas): if self.planeStress_type.itemText(i) == value_list[6]: self.planeStress_type.setCurrentIndex(i) btnSave = QPushButton() btnSave.setFixedSize(80, 25) btnSave.clicked.connect(self.on_btnSave_clicked) if self.interface_lng_val == 'Russian': btnSave.setText("Сохранить") elif self.interface_lng_val == 'English': btnSave.setText("Save") vbox = QVBoxLayout() vbox.addWidget(table) vbox.addWidget(btnSave) # ---------------------Размещение на форме всех компонентов------------------------- form = QFormLayout() form.addRow(vbox) self.setLayout(form)
def makeManualCustomBox(self): # Box for manual overrides for certain algorithms # Using QFormLayout to make rows for each override along with their check marks self.manualBox = QGroupBox("Optional Manual Adjustments") self.manualBox.setFixedSize(350, 250) self.manualBox.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Expanding) manualLayout = QFormLayout() # All following override GUI except saveDir are disabled until # User checks the checkmark next to the option they want to override. Else # If unchecked the algorithm will not take the override. # Cluster override that allows users to select a number of clusters to run the algorithm by. # If no override, algorithm will use elbow method. customCluster = QLineEdit() clusterCheckBox = QCheckBox("Custom Clusters") clusterCheckBox.stateChanged.connect(self.stateChangeCluster) customCluster.setPlaceholderText("Enter Custom Clusters") customCluster.setEnabled(False) self.customCluster = customCluster self.clusterCheckBox = clusterCheckBox # Decimate override allows user to select decimation factor to reduce # the data by, not recommended for small data sets. decimateCheck = QCheckBox("Decimation Factor") DecimateText = QLineEdit() decimateCheck.stateChanged.connect(self.stateChangeDecimate) DecimateText.setEnabled(False) DecimateText.setPlaceholderText("Set Decimation Factor") self.decimateCheck = decimateCheck self.DecimateText = DecimateText # N-Neighbor override only applies to Hiearchal Clustering # Algorithm. Will not be enabled for other K-Means clustering neighborCheck = QCheckBox("Custom N Neighbors") neighborInput = QLineEdit() neighborCheck.setEnabled(False) neighborCheck.stateChanged.connect(self.stateChangeNeighbor) neighborInput.setEnabled(False) neighborInput.setPlaceholderText("Enter N Neighbors here") self.neighborCheck = neighborCheck self.neighborInput = neighborInput # Button allows user to select a directory where they want to save the results in # In case they want to review it for later use. Default directory will be in the Results # Folder in CompiledAlgorithms self.dirButton = QPushButton("Select Directory to Save Result Folder") self.dirButton.clicked.connect(self.getDir) self.currentDirLabel = QLabel(self.currentDir) self.currentDirConstantLabel = QLabel("Current Save Directory:") # Adds each override options along with their checkboxes to each row manualLayout.addRow(self.clusterCheckBox, self.customCluster) manualLayout.addRow(self.decimateCheck, self.DecimateText) manualLayout.addRow(self.neighborCheck, self.neighborInput) manualLayout.addRow(self.dirButton) manualLayout.addRow(self.currentDirConstantLabel) manualLayout.addRow(self.currentDirLabel) self.manualBox.setLayout(manualLayout)
class WIFI_(QMainWindow): def setupUi(self, Dialog): app.processEvents() Dialog.setWindowTitle("i3 Wi-Fi_M ") Dialog.setObjectName("i3 Wi-Fi_M") Dialog.setStyleSheet("background-color:#15171a") resolution = popen( "xdpyinfo | grep dimensions | awk '{printf $2}'| cut -f 1 -d 'x'" ).read() self.width = int(resolution.strip()) - 245 Dialog.setGeometry(self.width, 30, 190, 310) self.groupBox = QGroupBox() self.formLayout = QFormLayout() self.Dialog = Dialog self.current_path = getcwd() self.refresh = QPushButton(Dialog) self.refresh.setGeometry(QRect(15, 7, 17, 17)) self.refresh.setObjectName("Refresh") self.refresh.setIcon( QtGui.QIcon(f"{self.current_path}/icons/refresh_green-64.png")) self.refresh.setStyleSheet(style_sheet.back_push_color("#162e2e")) self.refresh.clicked.connect(self.handler) self.refresh.setToolTip('Refresh') self.exit = QPushButton(Dialog) self.exit.setGeometry(QRect(158, 7, 17, 17)) self.exit.setObjectName("Exit") self.exit.setIcon( QtGui.QIcon(f"{self.current_path}/icons/multiply-64.png")) self.exit.setStyleSheet(style_sheet.back_push_color("#4f0c3e")) self.exit.clicked.connect(lambda x: self.close_window(Dialog)) self.exit.setToolTip('Exit') self.scrollArea = QScrollArea(Dialog) self.scrollArea.setStyleSheet( "border-top: 1px solid #2b2f36;border-radius:8px") self.scrollArea.setGeometry(QRect(7, 33, 176, 257)) self.scrollArea.setWidgetResizable(True) self.scrollArea.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff) self.scrollArea.verticalScrollBar().setStyleSheet( style_sheet.scroll_style()) self.scrollArea.setWidget(self.groupBox) self.title_0 = QLabel(Dialog) self.title_0.setGeometry(QRect(45, 8, 100, 15)) self.title_0.setObjectName("title_0") self.title_0.setStyleSheet( ' color:#5aa1a1; subcontrol-position: top center;font:11pt') self.title_0.setText("Available WiFi") Dialog.show() self.timer = QTimer() self.timer.timeout.connect(self.handler) self.timer.start(10) QMetaObject.connectSlotsByName(Dialog) def handler(self): """ This function is for handling the crashing Wi-Fi scan """ app.processEvents() wifi = Popen("nmcli -t -f active,ssid,signal,bssid dev wifi | sort -r ",\ shell=True, stderr=PIPE, stdout=PIPE\ ) # Split ssid signal and bssid of out put somthing like that ['status', 'ssid', 'bssid' ] if wifi.communicate()[1]: msgBox = QMessageBox() msgBox.setIcon(QMessageBox.Critical) msgBox.setText(wifi.communicate()[1].decode()) msgBox.setStyleSheet("background-color:#15171a;color:#5aa1a1") msgBox.setWindowTitle("NetworkManager Error") msgBox.setFont(QtGui.QFont('vazir', 12)) msgBox.setStandardButtons(QMessageBox.Ok) geometry_menu = self.Dialog.geometry() # self.setGeometry(geometry_menu.x()+1000, geometry_menu.y(), 100, 100) msgBox.setGeometry(geometry_menu.x() - 325, geometry_menu.y() + 60, 0, 0) # 840,170,0,0) returnValue = msgBox.exec_() if returnValue == QMessageBox.Ok: sys.exit() else: self.wifi_ = [ x for x in wifi.communicate()[0].decode().split('\n') if x ] self.timer.stop() self.scan() def scan(self): """ Create a dynamic PushButton for avaliable Wi-Fi """ app.processEvents() wifi_list = [ x.replace("\\", "").strip().split(":", 3) for x in self.wifi_ ] layout = self.formLayout.layout() if layout.count( ) is not None: # Remove duplicate PushButton after each refresh for i in reversed(range(layout.count())): layout.itemAt(i).widget().deleteLater() for IW in range(len(wifi_list)): # Create a dynamic PushButton self.IW = QPushButton(Dialog) self.IW.setFont(QtGui.QFont('SansSerif', 10)) self.IW.setObjectName(wifi_list[IW][3]) self.IW.setFixedSize(166, 24) self.IW.mouseDoubleClickEvent if not wifi_list[IW][1]: wifi_list[IW][1] = "Hidden" if wifi_list[IW][0] == 'yes': self.IW.setStyleSheet(style_sheet.pushButton_style_connect()) else: self.IW.setStyleSheet(style_sheet.pushButton_style_other()) self.IW.setText(' '.join(wifi_list[IW][1:3])) self.IW.setContextMenuPolicy(Qt.CustomContextMenu) self.IW.customContextMenuRequested.connect(self.right_click) self.IW.clicked.connect(self.click_btn) self.formLayout.addRow(self.IW) self.groupBox.setLayout(self.formLayout) def click_btn(self, event): """ Handle events after single click PushButtons """ app.processEvents() self.Wifi_Info = self.sender() if (active_bssid := popen( "nmcli -t -f active,ssid,bssid dev wifi | sort -r|grep yes "). read().replace("\\", "").strip().split(":", 2)): active_bssid = active_bssid[2] if len(active_bssid) > 1 else "" if self.Wifi_Info.objectName() != active_bssid: self.close_window(self.Dialog) if popen(f" nmcli c | grep '{self.Wifi_Info.text().split()[0]}'" ).read(): command_0 = "nmcli c up `nmcli c | grep '^%s.*' | awk '{print $2}'`" % ( self.Wifi_Info.text().split()[0]) status = run(command_0, stderr=PIPE, stdout=PIPE, shell=True) stdout = status.stdout.decode() stderr = status.stderr.decode() if 'successfully' not in stdout and 'successfully' not in stderr: command_1 = "nmcli c delete `nmcli c | grep '^%s.*' | awk '{print $2}'`" % ( self.Wifi_Info.text().split()[0]) run(command_1, shell=True, stdout=PIPE, stderr=PIPE) self.connect_window() command_2 = f"notify-send -u low '{status.stderr.decode()}'" run(command_2, shell=True) else: command_3 = f"notify-send -u low '{status.stdout.decode()}'" run(command_3, shell=True) self.close_window(self.Dialog) else: self.connect_window()
class StudentUpdateWindow(QDialog): """ With this class QDialog for updating the selected model.Student into database is shown. """ def __init__(self, selectedItems): """ constructor :param selectedItems:list of QTableWidget-s """ super().__init__() self.selectedItems = selectedItems self.title = "Update The Selected Student" self.left, self.top, self.width, self.height = 50, 50, 500, 500 self.validator = StudentValidator() self.dao = StudentDAOPymysqlImpl() self.initGUI() self.setWindowModality(Qt.ApplicationModal) def initGUI(self): """ initializes GUI :return: """ self.setWindowTitle(self.title) self.setGeometry(self.left, self.top, self.width, self.height) self.addComponents() self.registerEvents() def addComponents(self): """ sets the mainLayout for this class and adds components into it. :return: """ self.mainLayout = QFormLayout() self.setLayout(self.mainLayout) # title self.lblTitle = QLabel("Update The Selected Student") self.lblEmpty = QLabel() # enrolmentNumber self.lblEnrolmentNumber = QLabel("EnrolmentNumber: ") self.editEnrolmentNumber = QLineEdit() # firstName self.lblFirstName = QLabel("FirstName: ") self.editFirstName = QLineEdit() # lastName self.lblLastName = QLabel("LastName: ") self.editLastName = QLineEdit() # dob self.lblDob = QLabel("DateOfBirth: ") self.editDob = QLineEdit() # faculty self.lblFaculty = QLabel("Faculty: ") self.editFaculty = QLineEdit() # email self.lblEmail = QLabel("Email: ") self.editEmail = QLineEdit() # buttons self.btnUpdate = QPushButton("Update") self.btnCancel = QPushButton("Cancel") # add all rows to mainLayout self.mainLayout.addRow(self.lblEmpty, self.lblTitle) self.mainLayout.addRow(self.lblEnrolmentNumber, self.editEnrolmentNumber) self.mainLayout.addRow(self.lblFirstName, self.editFirstName) self.mainLayout.addRow(self.lblLastName, self.editLastName) self.mainLayout.addRow(self.lblDob, self.editDob) self.mainLayout.addRow(self.lblFaculty, self.editFaculty) self.mainLayout.addRow(self.lblEmail, self.editEmail) self.mainLayout.addRow(self.btnUpdate, self.btnCancel) data = [selectedItem.text() for selectedItem in self.selectedItems] self.editEnrolmentNumber.setText(data[0]) self.editFirstName.setText(data[1]) self.editLastName.setText(data[2]) self.editDob.setText(data[3]) self.editFaculty.setText(data[4]) self.editEmail.setText(data[5]) self.editEnrolmentNumber.setReadOnly(True) def registerEvents(self): """ registers events :return: """ self.btnUpdate.clicked.connect(self.onBtnUpdateClicked) self.btnCancel.clicked.connect(self.onBtnCancelClicked) @pyqtSlot() def onBtnUpdateClicked(self): """ Slot for signal-slot handling . Gets invoked when btnUpdate is clicked. :return: """ try: errors = [] enrolmentNumber = self.editEnrolmentNumber.text() firstName = self.editFirstName.text() lastName = self.editLastName.text() dob = self.editDob.text() faculty = self.editFaculty.text() email = self.editEmail.text() if not self.validator.validateEnrolmentNumber(enrolmentNumber): errors.append("enrolmentNumber is incorrect.") if not self.validator.validateFirstName(firstName): errors.append("firstName is incorrect.") if not self.validator.validateLastName(lastName): errors.append("lastName is incorrect.") if not self.validator.validateDob(dob): errors.append("DateOfBirth is incorrect.") if not self.validator.validateFaculty(faculty): errors.append("Faculty is incorrect.") if not self.validator.validateEmail(email): errors.append("Email is incorrect.") if len(errors) > 0: raise Exception("\n".join(errors)) self.dao.update( enrolmentNumber, Student(enrolmentNumber, firstName, lastName, dob, faculty, email)) # self.selectedItems[0].setText(enrolmentNumber) # self.selectedItems[1].setText(firstName) # self.selectedItems[2].setText(lastName) # self.selectedItems[3].setText(dob) # self.selectedItems[4].setText(faculty) # self.selectedItems[5].setText(email) self.close() except Exception as err: QMessageBox.critical(self, "<<Error>>", str(err)) @pyqtSlot() def onBtnCancelClicked(self): """ Slot for signal-slot handling . Gets invoked when btnCancel is clicked. :return: """ self.close()
class UIColorSpace(object): def __init__(self): self.mainDialog = colorspacedialog.ColorSpaceDialog() self.mainLayout = QVBoxLayout(self.mainDialog) self.formLayout = QFormLayout() self.documentLayout = QVBoxLayout() self.refreshButton = QPushButton(QIcon(':/icons/refresh.svg'), "Refresh") self.widgetDocuments = QListWidget() self.colorModelComboBox = colormodelcombobox.ColorModelComboBox(self) self.colorDepthComboBox = colordepthcombobox.ColorDepthComboBox(self) self.colorProfileComboBox = colorprofilecombobox.ColorProfileComboBox( self) self.buttonBox = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel) self.kritaInstance = krita.Krita.instance() self.documentsList = [] self.colorModelsList = [] self.colorDepthsList = [] self.colorProfilesList = [] self.refreshButton.clicked.connect(self.refreshButtonClicked) self.buttonBox.accepted.connect(self.confirmButton) self.buttonBox.rejected.connect(self.mainDialog.close) self.mainDialog.setWindowModality(Qt.NonModal) self.widgetDocuments.setSelectionMode(QAbstractItemView.MultiSelection) self.widgetDocuments.setSizeAdjustPolicy( QAbstractScrollArea.AdjustToContents) def initialize(self): self.loadDocuments() self.loadColorModels() self.loadColorDepths() self.loadColorProfiles() self.documentLayout.addWidget(self.widgetDocuments) self.documentLayout.addWidget(self.refreshButton) self.formLayout.addRow('Documents', self.documentLayout) self.formLayout.addRow('Color Model', self.colorModelComboBox) self.formLayout.addRow('Color Depth', self.colorDepthComboBox) self.formLayout.addRow('Color Profile', self.colorProfileComboBox) self.line = QFrame() self.line.setFrameShape(QFrame.HLine) self.line.setFrameShadow(QFrame.Sunken) self.mainLayout.addLayout(self.formLayout) self.mainLayout.addWidget(self.line) self.mainLayout.addWidget(self.buttonBox) self.mainDialog.resize(500, 300) self.mainDialog.setWindowTitle("Color Space") self.mainDialog.setSizeGripEnabled(True) self.mainDialog.show() self.mainDialog.activateWindow() def loadColorModels(self): self.colorModelsList = sorted(self.kritaInstance.colorModels()) self.colorModelComboBox.addItems(self.colorModelsList) def loadColorDepths(self): self.colorDepthComboBox.clear() colorModel = self.colorModelComboBox.currentText() self.colorDepthsList = sorted( self.kritaInstance.colorDepths(colorModel)) self.colorDepthComboBox.addItems(self.colorDepthsList) def loadColorProfiles(self): self.colorProfileComboBox.clear() colorModel = self.colorModelComboBox.currentText() colorDepth = self.colorDepthComboBox.currentText() self.colorProfilesList = sorted( self.kritaInstance.profiles(colorModel, colorDepth)) self.colorProfileComboBox.addItems(self.colorProfilesList) def loadDocuments(self): self.widgetDocuments.clear() self.documentsList = [ document for document in self.kritaInstance.documents() if document.fileName() ] for document in self.documentsList: self.widgetDocuments.addItem(document.fileName()) def refreshButtonClicked(self): self.loadDocuments() def confirmButton(self): selectedPaths = [ item.text() for item in self.widgetDocuments.selectedItems() ] selectedDocuments = [ document for document in self.documentsList for path in selectedPaths if path == document.fileName() ] self.msgBox = QMessageBox(self.mainDialog) if selectedDocuments: self.convertColorSpace(selectedDocuments) self.msgBox.setText("The selected documents has been converted.") else: self.msgBox.setText("Select at least one document.") self.msgBox.exec_() def convertColorSpace(self, documents): for document in documents: document.setColorSpace(self.colorModelComboBox.currentText(), self.colorDepthComboBox.currentText(), self.colorProfileComboBox.currentText())
class Adf4113RefcountLatchWidget(QGroupBox): bitmapChanged = pyqtSignal() title = 'Ref count latch' def __init__(self, parent=None): super().__init__(parent) self.setCheckable(True) self.setChecked(True) self._slideRefcount = SpinSlide(1, 16383, 1, '') self._comboAntibacklash = QComboBox() self._comboLockDetectPrec = QComboBox() self._comboSync = QComboBox() self._containerLayout = QVBoxLayout() self._formLayout = QFormLayout() self._bitLayout = QVBoxLayout() self._latch = Adf4113RefcountLatch() self._tableBits = QTableView() self._bitModel = BitModel(rowSize=8, bits=self._latch.bin, labels=[ 'X', 'DLY', 'SYNC', 'LDP', 'T2', 'T1', 'ABP2', 'ABP1', 'R14', 'R13', 'R12', 'R11', 'R10', 'R9', 'R8', 'R7', 'R6', 'R5', 'R4', 'R3', 'R2', 'R1', 'C2', 'C1' ], disabled=[ True, False, False, False, True, True, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, True, True ], parent=self) self._init() def _init(self): self._containerLayout.addLayout(self._formLayout) self._containerLayout.addLayout(self._bitLayout) self.setLayout(self._containerLayout) self._formLayout.addRow('Reference counter', self._slideRefcount) self._formLayout.addRow('Anti-backlash pulse width', self._comboAntibacklash) self._formLayout.addRow('Lock detection precision', self._comboLockDetectPrec) self._formLayout.addRow('Prescaler sync', self._comboSync) self._bitLayout.addWidget(self._tableBits) self._comboAntibacklash.setModel( MapModel(self, self._latch.antibacklash_pulse_width_labels, sort=False)) self._comboLockDetectPrec.setModel( MapModel(self, self._latch.lock_detect_precision_labels, sort=False)) self._comboLockDetectPrec.setModel( MapModel(self, self._latch.lock_detect_precision_labels, sort=False)) self._comboSync.setModel( MapModel(self, self._latch.precaler_sync_mode, sort=False)) self.setTitle( f'{self.title} (h:{self._latch.hex} b:{self._latch.bin})') self._tableBits.setModel(self._bitModel) self._tableBits.horizontalHeader().setVisible(False) self._tableBits.verticalHeader().setVisible(False) self._tableBits.verticalHeader().setDefaultSectionSize(20) self._tableBits.resizeColumnsToContents() self._tableBits.setSelectionMode(0) self._setupSignals() def _setupSignals(self): self._slideRefcount.valueChanged.connect(self.updateBitmap) self._comboAntibacklash.currentIndexChanged.connect(self.updateBitmap) self._comboLockDetectPrec.currentIndexChanged.connect( self.updateBitmap) self._comboSync.currentIndexChanged.connect(self.updateBitmap) self._bitModel.bitChanged.connect(self.onBitChanged) def updateDisplay(self): self.setTitle( f'{self.title} (h:{self._latch.hex} b:{self._latch.bin})') self._bitModel.update(self._latch.bin) self.bitmapChanged.emit() @pyqtSlot(int) def updateBitmap(self, _): self._latch.reference_counter = self._slideRefcount.value() self._latch.antibacklash_pulse_width = self._comboAntibacklash.currentData( MapModel.RoleNodeId) self._latch.lock_detect_precision = self._comboLockDetectPrec.currentData( MapModel.RoleNodeId) self._latch.sync_mode = self._comboSync.currentData( MapModel.RoleNodeId) self.updateDisplay() @pyqtSlot(int, int) def onBitChanged(self, row, col): self.latch.toggle_nth_bit(row * 8 + 7 - col) self.updateDisplay() @property def latch(self): return self._latch
def __init__(self, parent): super(QWidget, self).__init__(parent) self.parent = parent self.tree = ProposalsTreeWidget(parent) # Proposals that have been paid for but not submitted. self.unsubmitted_proposals = [] description = ''.join([ 'You can create a budget proposal below. ', 'Proposals require 5 DASH to create. ', 'Your proposal can be submitted once the collateral transaction has enough confirmations.' ]) description = QLabel(_(description)) description.setWordWrap(True) self.name_edit = QLineEdit() self.name_edit.setPlaceholderText(_('Name of your proposal')) self.url_edit = QLineEdit() self.url_edit.setPlaceholderText( _('URL that your proposal can be found at')) self.payments_count_edit = QSpinBox() self.payments_count_edit.setRange(1, 1000000) self.start_block_edit = QSpinBox() self.start_block_edit.setRange(0, 1000000) self.address_edit = QLineEdit() self.address_edit.setPlaceholderText( _('Address that will receive payments')) self.amount_edit = BTCAmountEdit(self.parent.get_decimal_point) self.create_proposal_button = QPushButton(_('Create Proposal')) self.create_proposal_button.clicked.connect(self.create_proposal) self.submit_ready_proposals_button = QPushButton( _('Submit Confirmed Proposals')) self.submit_ready_proposals_button.clicked.connect( self.submit_waiting_proposals) self.submit_ready_proposals_button.setEnabled(False) self.ready_proposals = QLabel() self.ready_proposals.setVisible(False) form = QFormLayout() form.addRow(_('Proposal Name:'), self.name_edit) form.addRow(_('Proposal URL:'), self.url_edit) form.addRow(_('Number of Payments:'), self.payments_count_edit) form.addRow(_('Starting Block:'), self.start_block_edit) form.addRow(_('Payment Address:'), self.address_edit) form.addRow(_('Monthly DASH Payment:'), self.amount_edit) vbox = QVBoxLayout() vbox.addWidget(self.tree) vbox.addWidget(description) vbox.addLayout(form) vbox.addLayout(util.Buttons(self.create_proposal_button)) vbox.addLayout( util.Buttons(self.ready_proposals, self.submit_ready_proposals_button)) self.setLayout(vbox)
def __init__(self, main_widget, parent=None): super(ProposalEditor, self).__init__(parent) self.main_widget = main_widget self.name_edit = QLineEdit() self.url_edit = QLineEdit() self.start_block_edit = QLineEdit() self.end_block_edit = QLineEdit() self.amount_edit = QLineEdit() self.address_edit = QLineEdit() self.txid_edit = QLineEdit() for i in [ self.name_edit, self.url_edit, self.start_block_edit, self.end_block_edit, self.amount_edit, self.address_edit, self.txid_edit ]: i.setReadOnly(True) self.mapper = QDataWidgetMapper() self.mapper.setModel(self.main_widget.proxy_model) self.mapper.setSubmitPolicy(QDataWidgetMapper.ManualSubmit) self.mapper.addMapping(self.name_edit, ProposalsModel.NAME) self.mapper.addMapping(self.url_edit, ProposalsModel.URL) self.mapper.addMapping(self.start_block_edit, ProposalsModel.START_BLOCK) self.mapper.addMapping(self.end_block_edit, ProposalsModel.END_BLOCK) self.mapper.addMapping(self.amount_edit, ProposalsModel.AMOUNT) self.mapper.addMapping(self.address_edit, ProposalsModel.ADDRESS) self.mapper.addMapping(self.txid_edit, ProposalsModel.TXID) block_hbox = QHBoxLayout() block_hbox.addWidget(self.start_block_edit) block_hbox.addWidget(QLabel(' - ')) block_hbox.addWidget(self.end_block_edit) self.vote_combo = QComboBox() self.vote_combo.addItem(_('Yes')) self.vote_combo.addItem(_('No')) self.vote_button = QPushButton(_('Vote')) self.vote_button.clicked.connect(self.cast_vote) vote_hbox = util.Buttons(self.vote_combo, self.vote_button) form = QFormLayout() form.addRow(_('Name:'), self.name_edit) form.addRow(_('URL:'), self.url_edit) form.addRow(_('Blocks:'), block_hbox) form.addRow(_('Monthly Payment:'), self.amount_edit) form.addRow(_('Payment Address:'), self.address_edit) form.addRow(_('Fee TxID:'), self.txid_edit) form.addRow(_('Vote:'), vote_hbox) self.setLayout(form)
class Player(QMainWindow): def __init__(self): super(Player, self).__init__() uic.loadUi("src/ui/player_interface.ui", self) self.add_music_button.clicked.connect(self.add_music) self.setWindowTitle("BEZKRINZA MP3-PLAYER") self.list_of_all_buttons = [] # настройки кнопки play self.play_button.setIcon(self.style().standardIcon(QStyle.SP_MediaPlay)) self.play_button.clicked.connect(self.play_pause_track) self.play_button.setEnabled(False) self.setWindowIcon(QIcon("src/img/logo player.png")) self.setFixedSize(1050, 600) # настройки внешнего вида и функционала кнопок левый/правый трек self.right_track_button.setIcon(self.style().standardIcon(QStyle.SP_MediaSkipForward)) self.left_track_button.setIcon(self.style().standardIcon(QStyle.SP_MediaSkipBackward)) self.right_track_button.setEnabled(False) self.left_track_button.setEnabled(False) self.right_track_button.clicked.connect(self.next_track) self.left_track_button.clicked.connect(self.previous_track) self.random_track_button.clicked.connect(self.choose_random_music) self.random_track_button.setEnabled(False) self.playing = False # словари, в которых будут в качестве ключей храниться кнопки delete и play, которые находятся # в scrollarea, а значениями будут id треков, соответствующих этим кнопкам self.button_slovar = {} self.button_del_slovar = {} # настройка функционала и внешнего вида ползунков self.volume_slider.valueChanged[int].connect(self.change_volume) self.volume_slider.setRange(0, 10) self.volume_slider.setValue(5) self.content_slider.sliderMoved[int].connect(self.change_content) self.new_playlist_id = 1 self.info_button.clicked.connect(self.show_info) self.add_playlist_button.clicked.connect(self.add_playlist) self.playlists_list = ["Основной"] self.update_scrollarea() self.playlists.addItem("Основной") self.update_combobox() self.playlists.currentTextChanged.connect(self.change_playlist) self.change_color_button.clicked.connect(self.change_color_theme) self.theme = "Dark" # создание и настройка таймеров: ежесекундного и замеряющего время до конца трека self.timer = QTimer(self) self.timer.timeout.connect(self.next_track) self.slider_timer = QTimer(self) self.slider_timer.setInterval(1000) self.slider_timer.timeout.connect(self.move_content_slider) self.artist = '' self.title = '' # метод, вызываемый для остановки/продолжения воспроизведения трека def play_pause_track(self): # проверка флага if not self.playing: mixer.music.unpause() # изменение значения флага self.playing = True self.play_button.setIcon(self.style().standardIcon(QStyle.SP_MediaPause)) # остановка и повторный запуск таймеров self.timer.stop() delta = self.length * 1000 - mixer.music.get_pos() self.timer.start(delta) self.slider_timer.start() else: mixer.music.pause() # изменение значения флага self.playing = False self.play_button.setIcon(self.style().standardIcon(QStyle.SP_MediaPlay)) # остановка таймеров self.timer.stop() self.timer.stop() self.slider_timer.stop() # изменение позиции проигрывания трека def change_content(self, value): mixer.music.set_pos(float(value)) # запуск таймера с новым значением времени, оставшегося до конца self.timer.stop() delta = self.length * 1000 - value * 1000 self.timer.start(delta) # изменение громкости, играющего трека в зависимости от установленной громкости (по умолчанию 50%) def change_volume(self, value): mixer.music.set_volume(float(value / 10)) # добавление данных о новом треке в БД/выбор трека def add_music(self): fname = QFileDialog.getOpenFileName(self, 'choose mp3 file', '', 'Звук в формате MP3 (*.mp3)')[0] # проверка наличия выбранного файла if fname: audio_file = eyed3.load(fname) song = MP3(fname) # получаем данные о длине трека (минуты) length = int(song.info.length) # проверка наличия в файле данных об исполнителе и названии if audio_file.tag.title != None: title = audio_file.tag.title else: title = "Неизвестно" if audio_file.tag.artist != None: artist_name = audio_file.tag.artist else: artist_name = "Неизвестен" # создаю jpg с обложкой with open("src/music/img/{} - {}.jpg".format(artist_name, title), mode="wb") as image_file: if list(audio_file.tag.images) != []: image_name = "src/music/img/{} - {}.jpg".format(artist_name, title) image_file.write(audio_file.tag.images[0].image_data) else: image_name = "src/img/none_photo.png" # заношу все в БД con = sqlite3.connect("src/database/database_player.db") cur = con.cursor() result = cur.execute("""INSERT INTO tracks(artist,title,length,path_to_track, path_to_image, playlist) VALUES (?,?,?,?,?,?)""", (artist_name, title, length, fname, image_name, self.new_playlist_id)).fetchall() con.commit() con.close() self.update_scrollarea() # изменение данных в scrollarea def update_scrollarea(self): # внешний главный layout self.layout = QFormLayout(self) # groupbox для занесения layout в scrollarea self.groupBox = QGroupBox(self) # списки всех кнопок delete, play и строчек с названиями и исполнителями self.list_label = [] self.list_button = [] self.list_del_button = [] con = sqlite3.connect("src/database/database_player.db") cur = con.cursor() result = cur.execute("""SELECT id, artist, title FROM tracks WHERE playlist = ?""", (self.new_playlist_id,)).fetchall() i = 0 # внутренний layout hlayout = QGridLayout(self) for elem in result: # обрабатываю данные, полученные по запросу в БД id = elem[0] artist = elem[1] title = elem[2] # заношу данные в списки self.list_label.append(QLabel("{} - {}".format(artist, title), self)) self.list_button.append(QPushButton(self)) self.list_del_button.append(QPushButton(self)) # заношу виджеты кнопок, названия во вонутренний layout hlayout.addWidget(self.list_label[i], i, 0) hlayout.addWidget(self.list_button[i], i, 1) hlayout.addWidget(self.list_del_button[i], i, 2) # привязываю к кнопкам методы self.list_button[i].clicked.connect(self.start_music) self.list_del_button[i].clicked.connect(self.delete_music) # настраиваю внешний вид self.list_del_button[i].setIcon(QIcon("src/img/bin.png")) self.list_button[i].setIcon(self.style().standardIcon(QStyle.SP_MediaPlay)) # заношу виджеты как ключ в словарь и присваиваю им всем id self.button_slovar[str(self.list_button[i])] = id self.button_del_slovar[str(self.list_del_button[i])] = id # настраиваю внешний вид виджетов self.list_label[i].setFont(QFont("Century Gothic", 10, QFont.Bold)) self.list_del_button[i].setStyleSheet('QPushButton {background-color: rgb(130, 130, 130);' 'border-radius: 8px}') self.list_button[i].setStyleSheet('QPushButton {background-color: rgb(130, 130, 130);' 'border-radius: 8px}') i += 1 # заношу внутренний layout во внешний, чтобы убрать образовывающиеся пробелы во внутреннем layout self.layout.addRow(hlayout) self.groupBox.setLayout(self.layout) # добавляю в scrollarea groupbox со внешним layout self.music_scroller.setWidget(self.groupBox) con.commit() con.close() # удаление музыки def delete_music(self): con = sqlite3.connect("src/database/database_player.db") cur = con.cursor() # определяю, кто отправил сигнал и достаю из словаря соответствующий id btn = str(self.sender()) id = self.button_del_slovar[btn] # удаляю данные из БД result = cur.execute("""DELETE from tracks WHERE id = ?""", (id,)).fetchall() con.commit() con.close() self.update_scrollarea() # начало проигрывания музыки def start_music(self, new_id=-1): con = sqlite3.connect("src/database/database_player.db") cur = con.cursor() # проверка, был ли послан сигнал по нажатию кнопки next_track, кнопки play в scrollarea или автоматически # при заверешении предыдущего трека if not new_id: btn = str(self.sender()) self.playing_id = self.button_slovar[btn] result = cur.execute("""SELECT artist,title,length,path_to_track,path_to_image FROM tracks WHERE id = ?""", (self.playing_id,)).fetchall() else: result = cur.execute("""SELECT artist,title,length,path_to_track,path_to_image FROM tracks WHERE id = ?""", (new_id,)).fetchall() self.playing_id = new_id # Обрабатываю данные из БД self.artist = result[0][0] self.title = result[0][1] self.length = result[0][2] self.current_path = result[0][3] # задаю интервал таймеру равный длине трека (мсек) и запускаю его self.timer.setInterval(self.length * 1000) self.timer.start() image = result[0][4] con.close() mixer.music.load(self.current_path) mixer.music.play() # изменяю значение флага self.playing = True mixer.music.set_volume(0.5) self.content_slider.setRange(0, int(self.length - 1)) self.volume_slider.setValue(5) # устанавливаю обложку альбома self.pixmap = QPixmap(image) self.image.setPixmap(self.pixmap) # проверяю, какого цвета надо установить шрифт, в зависимости от темы if self.theme == "Dark": self.playing_song_artist.setText("<span style='color: rgb(255, 255, 255);'>{}</span>".format(self.artist)) self.playing_song_title.setText("<span style='color: rgb(255, 255, 255);'>{}</span>".format(self.title)) else: self.playing_song_artist.setText("<span style='color: rgb(0, 0, 0);'>{}</span>".format(self.artist)) self.playing_song_title.setText("<span style='color: rgb(0, 0, 0);'>{}</span>".format(self.title)) # возваращаю ползунок песни в начало self.content_slider.setValue(0) # делаб все кнопки нажимаемы (нужно при запуске первого трека) self.play_button.setEnabled(True) self.right_track_button.setEnabled(True) self.left_track_button.setEnabled(True) self.random_track_button.setEnabled(True) self.play_button.setIcon(self.style().standardIcon(QStyle.SP_MediaPause)) # запускаю секнудный таймер self.slider_timer.start() # отображение информации о приложении def show_info(self): app_info = QMessageBox() app_info.setWindowTitle("Info") app_info.setWindowIcon(QIcon("src/img/info.png")) app_info.setText("В данный момент вы используете MP3-плейер bezkrinza. " "В этом плейере вы можете в один клик добавить новый плейлист(кнопка ADD PLAYLIST)," "добавить в него свои любимые треки(кнопка ADD MUSIC). Если же они вам наскучат, " "вы сможете их удалить(кнопка delete справа от названия трека в виджете со всеми песянми, " "добавленными в плейлист). Также присутствует возможность включить рандомный трек из играющего" "в данный момент плейлиста(кнопка random_track справа от панели управления).\n" "Приложение разработал Куценко Дмитрий\n" "Все права защищены") app_info.setStyleSheet( """ QMessageBox { font: Century Gothic 20px; color: rgb(255, 255, 255); background-color: rgb(255, 255, 255); } """ ) info_window = app_info.exec_() # добавление новых плейлистов def add_playlist(self): # диалог с вводомназвания нового плейлиста playlist_name, ok_pressed = QInputDialog.getText(self, "New Playlist Name", "Введите название нового плейлиста") # проверка нажатия кнопки ОК if ok_pressed: # обновляю данные в БД con = sqlite3.connect("src/database/database_player.db") cur = con.cursor() result = cur.execute("""INSERT INTO playlists(playlist_name) VALUES(?)""", (playlist_name,)) con.commit() con.close() self.update_combobox() # изменение списка отображаемых плейлистов в combobox def update_combobox(self): con = sqlite3.connect("src/database/database_player.db") cur = con.cursor() result = cur.execute("""SELECT playlist_name FROM playlists""").fetchall() for elem in result: # проверка наличия элемента в combobox if elem[0] not in self.playlists_list: self.playlists.addItem(elem[0]) self.playlists_list.append(elem[0]) # изменение данных о выбранном плейлисте def change_playlist(self): new_playlist_name = self.playlists.currentText() con = sqlite3.connect("src/database/database_player.db") cur = con.cursor() self.new_playlist_id = cur.execute("""SELECT id FROM playlists WHERE playlist_name = ?""", (new_playlist_name,)).fetchall()[0][0] con.commit() con.close() self.update_scrollarea() # начало проигрывания следующего трека в плейлисте # если трек всего один, он начнет проигрываться заново def next_track(self): try: con = sqlite3.connect("src/database/database_player.db") cur = con.cursor() # получаю данные об айди играющего сейчас плейлиста current_playlist_id = cur.execute("""SELECT playlist FROM tracks WHERE id = ?""", (self.playing_id,)).fetchall()[0][0] result = cur.execute("""SELECT id FROM tracks WHERE playlist = ?""", (current_playlist_id,)).fetchall() # список айди всех треков плейлиста list_of_ids = [elem[0] for elem in result] # проверка длины плейлиста if len(list_of_ids) == 1: self.start_music(new_id=self.playing_id) else: if list_of_ids.index(int(self.playing_id)) == len(list_of_ids) - 1: self.playing_id = list_of_ids[0] self.start_music(new_id=list_of_ids[0]) else: ind = list_of_ids.index(self.playing_id) self.playing_id = list_of_ids[ind + 1] self.start_music(new_id=list_of_ids[ind + 1]) except Exception: pass # аналогично с next_track поигрывет предыдущий трек def previous_track(self): try: con = sqlite3.connect("src/database/database_player.db") cur = con.cursor() current_playlist_id = cur.execute("""SELECT playlist FROM tracks WHERE id = ?""", (self.playing_id,)).fetchall()[0][0] result = cur.execute("""SELECT id FROM tracks WHERE playlist = ?""", (current_playlist_id,)).fetchall() list_of_ids = [elem[0] for elem in result] if len(list_of_ids) == 1: self.start_music(new_id=self.playing_id) else: if list_of_ids.index(int(self.playing_id)) == 0: self.playing_id = list_of_ids[-1] self.start_music(new_id=list_of_ids[-1]) else: ind = list_of_ids.index(self.playing_id) self.playing_id = list_of_ids[ind - 1] self.start_music(new_id=list_of_ids[ind - 1]) except Exception: pass # метод для автоматического движения ползунка во время проигрывания трека def move_content_slider(self): self.content_slider.setValue(self.content_slider.value() + 1) # изменение цветовой темы def change_color_theme(self): # вручную меняю оформление почти всех виджетов приложения if self.theme == "Dark": self.frame.setStyleSheet('QFrame {background-color: rgb(255, 255, 255)}') self.add_music_button.setStyleSheet('QPushButton {background-color: #7dff8c; border-radius: 20px}') self.add_playlist_button.setStyleSheet('QPushButton {background-color: #7dff8c; border-radius: 20px}') self.play_button.setStyleSheet('QPushButton {background-color: #7dff8c; border-radius: 15px}') self.right_track_button.setStyleSheet('QPushButton {background-color: #7dff8c; border-radius: 15px}') self.left_track_button.setStyleSheet('QPushButton {background-color: #7dff8c; border-radius: 15px}') self.info_button.setStyleSheet('QPushButton ''{background-color: #7dff8c; border-radius: 10px}') self.random_track_button.setStyleSheet('QPushButton ''{background-color: #7dff8c; border-radius: 10px}') self.change_color_button.setStyleSheet('QPushButton ''{background-color: #7dff8c; border-radius: 10px}') if self.artist and self.title: self.playing_song_artist.setText("<span style='color: rgb(0, 0, 0);'>{}</span>".format(self.artist)) self.playing_song_title.setText("<span style='color: rgb(0, 0, 0);'>{}</span>".format(self.title)) self.theme = "Light" else: self.frame.setStyleSheet('QFrame {background-color: rgb(52, 52, 52)}') self.add_music_button.setStyleSheet('QPushButton ' '{background-color: rgb(23, 255, 58); border-radius: 20px}') self.add_playlist_button.setStyleSheet('QPushButton ' '{background-color: rgb(23, 255, 58); border-radius: 20px}') self.play_button.setStyleSheet('QPushButton ' '{background-color: rgb(23, 255, 58); border-radius: 15px}') self.right_track_button.setStyleSheet('QPushButton ' '{background-color: rgb(23, 255, 58); border-radius: 15px}') self.left_track_button.setStyleSheet('QPushButton ' '{background-color: rgb(23, 255, 58); border-radius: 15px}') self.info_button.setStyleSheet('QPushButton ' '{background-color: rgb(23, 255, 58); border-radius: 10px}') self.change_color_button.setStyleSheet('QPushButton ''' '{background-color: rgb(23, 255, 58); border-radius: 10px}') self.random_track_button.setStyleSheet('QPushButton ''' '{background-color: rgb(23, 255, 58); border-radius: 10px}') if self.artist and self.title: self.playing_song_artist.setText( "<span style='color: rgb(255, 255, 255);'>{}</span>".format(self.artist)) self.playing_song_title.setText("<span style='color: rgb(255, 255, 255);'>{}</span>".format(self.title)) self.theme = "Dark" # генерация окна с подтверждением желания пользователя закрыть приложение def closeEvent(self, event): # месседж бокс с вопросом и двумя вариантами ответа reply = QMessageBox.question(self, 'Выход из программы', "Вы точно хотите закрыть плейер?", QMessageBox.Yes | QMessageBox.No, QMessageBox.Yes) if reply == QMessageBox.Yes: event.accept() else: event.ignore() # выбор рандомного айди трека из играющего плейлиста и его запуск def choose_random_music(self): try: con = sqlite3.connect("src/database/database_player.db") cur = con.cursor() # получаю данные об айди играющего сейчас плейлиста current_playlist_id = cur.execute("""SELECT playlist FROM tracks WHERE id = ?""", (self.playing_id,)).fetchall()[0][0] result = cur.execute("""SELECT id FROM tracks WHERE playlist = ?""", (current_playlist_id,)).fetchall() list_of_ids = [elem[0] for elem in result] # функцией choice выбираю рандомный айди self.start_music(new_id=choice(list_of_ids)) except Exception: pass
def __init__(self, CTMain=None): super().__init__() self._CTMain = CTMain self._full_file_path = os.path.join(sys.path[0], 'encrypted_settings') # Initialize grid layout self._layout = QGridLayout() self._layout.setRowStretch(0, 2) self._layout.setRowStretch(1, 1) self._layout.setRowStretch(2, 1) self._layout.setRowStretch(3, 1) self._layout.setRowStretch(4, 1) self._layout.setRowStretch(5, 2) self._layout.setColumnStretch(0, 1) self._layout.setColumnStretch(1, 1) self._layout.setColumnStretch(2, 1) self._layout.setColumnStretch(3, 1) # Create top and bottom notifications self._label_bottom = QTextEdit('') self._label_bottom.setReadOnly(True) self._label_bottom.setStyleSheet(""" background-color: #f1f1f1; border: none; """) if os.path.isfile(self._full_file_path): self._label_top_text = 'Please enter the password to load your API keys or press a button below ' + \ 'to continue without encrypted data' else: self._label_top_text = 'Please create a password to encrypt your API Keys' self._label_bottom.setText( 'It is recommended to use longer passwords that include lower and ' + 'upper case letters, numbers, and special characters.') self._label_top = QTextEdit(self._label_top_text) self._label_top.setReadOnly(True) self._label_top.setAlignment(Qt.AlignCenter) self._label_top.setStyleSheet(""" background-color: #f1f1f1; border: none; """) self._password_form_box = QGroupBox("") group_box_layout = QFormLayout() self._textbox_password = QLineEdit('', self) self._textbox_password.setEchoMode(QLineEdit.Password) self._textbox_password.returnPressed.connect(self.enter_password) self._label_password = QLabel("Password:"******"Unlock encrypted settings") self._enter_button.clicked.connect(self.enter_password) self._skip_button = QPushButton() self._skip_button.setText( "Proceed without unlocking encrypted settings") self._skip_button.clicked.connect(self.skip_password) self._layout.addWidget(self._label_top, 1, 1, 1, 2) self._layout.addWidget(self._password_form_box, 2, 1, 1, 2) self._layout.addWidget(self._enter_button, 3, 1, 1, 2) if os.path.isfile(self._full_file_path): self._layout.addWidget(self._skip_button, 4, 1, 1, 2) self._layout.addWidget(self._label_bottom, 5, 1, 1, 2) self.setLayout(self._layout) self.show()
def __init__(self, parent=None): super(lineEditDemo, self).__init__(parent) e1 = QLineEdit() e1.setValidator( QIntValidator() ) e1.setMaxLength(4) e1.setAlignment( Qt.AlignRight ) e1.setFont( QFont("Arial",20)) e2 = QLineEdit() e2.setValidator( QDoubleValidator(0.99,99.99,2)) flo = QFormLayout() flo.addRow("integer validator", e1) flo.addRow("Double validator",e2) e3 = QLineEdit() e3.setInputMask('+99_9999_999999') flo.addRow("Input Mask",e3) e4 = QLineEdit() e4.textChanged.connect( self.textchanged ) flo.addRow("Text changed",e4) e5 = QLineEdit() e5.setEchoMode( QLineEdit.Password ) flo.addRow("Password",e5) e6 = QLineEdit("Hello PyQt5") e6.setReadOnly(True) flo.addRow("Read Only",e6 ) e5.editingFinished.connect( self.enterPress ) self.setLayout(flo) self.setWindowTitle("QLineEdit範例")
def _setup_saving_ui(self): """ Create everything related to the image/video saving tab """ encoder_dict = Encoder.get_encoder_dict() form_layout = QFormLayout() layout = QVBoxLayout() layout.addLayout(form_layout) location_layout = QHBoxLayout() location_label = QLabel("Where to save images/videos:", self) self.location_edit = QLineEdit(self) location_dialog_button = QPushButton("...", self) location_dialog_button.clicked.connect(self.open_file_dialog) location_layout.addWidget(self.location_edit) location_layout.addWidget(location_dialog_button) # maintain descriptions as own labels # pyqt seems to loose the descriptions somewhere # when simple strings are used or the qlabel does not have self as owner form_layout.addRow(location_label, location_layout) self.image_type_combobox = QComboBox(self) for key, value in encoder_dict.items(): if value.encoder_type == Encoder.MediaType.image: self.image_type_combobox.addItem(key) image_type_label = QLabel("Save images as:") self.image_type_combobox.currentIndexChanged['QString'].connect( self.image_name_suffix_changed) form_layout.addRow(image_type_label, self.image_type_combobox) if self.enabled_video: self.video_type_combobox = QComboBox(self) for key, value in encoder_dict.items(): if value.encoder_type == Encoder.MediaType.video: self.video_type_combobox.addItem(key) self.video_type_combobox.currentIndexChanged['QString'].connect( self.video_name_suffix_changed) video_type_label = QLabel("Save videos as:", self) form_layout.addRow(video_type_label, self.video_type_combobox) image_name_groupbox = QGroupBox("Image File Names") groupbox_layout = QFormLayout() image_name_groupbox.setLayout(groupbox_layout) self.image_name_preview = QLabel( "<USER-PREFIX>-<SERIAL>-<FORMAT>-<TIMESTAMP>-<COUNTER>.png") self.image_name_preview_description = QLabel( "Images will be named like:") groupbox_layout.addRow(self.image_name_preview_description, self.image_name_preview) self.image_name_prefix = QLineEdit() self.image_name_prefix.textChanged.connect( self.image_name_prefix_changed) self.image_name_prefix.setMaxLength(100) self.image_name_prefix_description = QLabel("User Prefix:", self) groupbox_layout.addRow(self.image_name_prefix_description, self.image_name_prefix) self.image_name_serial = QCheckBox(self) self.image_name_serial.toggled.connect( self.image_name_properties_toggled) self.image_name_serial_description = QLabel("Include Serial:") groupbox_layout.addRow(self.image_name_serial_description, self.image_name_serial) self.image_name_format = QCheckBox(self) self.image_name_format.toggled.connect( self.image_name_properties_toggled) self.image_name_format_description = QLabel("Include Format:") groupbox_layout.addRow(self.image_name_format_description, self.image_name_format) self.image_name_counter = QCheckBox(self) self.image_name_counter.toggled.connect( self.image_name_properties_toggled) self.image_name_counter_description = QLabel("Include Counter:") groupbox_layout.addRow(self.image_name_counter_description, self.image_name_counter) self.image_name_counter_box = QSpinBox(self) self.image_name_counter_box.setRange(1, 10) self.image_name_counter_box.valueChanged.connect( self.image_name_counter_changed) self.image_name_counter_box_description = QLabel("Counter Size:") groupbox_layout.addRow(self.image_name_counter_box_description, self.image_name_counter_box) self.image_name_counter.toggled.connect( self.toggle_image_counter_box_availability) self.image_name_counter.toggled.connect( self.image_name_properties_toggled) self.image_name_timestamp = QCheckBox(self) self.image_name_timestamp.toggled.connect( self.image_name_properties_toggled) self.image_name_timestamp_description = QLabel("Include Timestamp:") groupbox_layout.addRow(self.image_name_timestamp_description, self.image_name_timestamp) layout.addWidget(image_name_groupbox) video_groupbox = QGroupBox("Video File Names") video_layout = QFormLayout() video_groupbox.setLayout(video_layout) self.video_name_preview = QLabel( "<USER-PREFIX>-<SERIAL>-<FORMAT>-<TIMESTAMP>-<COUNTER>.png") self.video_name_preview_description = QLabel( "Videos will be named like:") video_layout.addRow(self.video_name_preview_description, self.video_name_preview) self.video_name_prefix = QLineEdit() self.video_name_prefix.textChanged.connect( self.video_name_prefix_changed) self.video_name_prefix.setMaxLength(100) self.video_name_prefix_description = QLabel("User Prefix:", self) video_layout.addRow(self.video_name_prefix_description, self.video_name_prefix) self.video_name_serial = QCheckBox(self) self.video_name_serial.toggled.connect( self.video_name_properties_toggled) self.video_name_serial_description = QLabel("Include Serial:") video_layout.addRow(self.video_name_serial_description, self.video_name_serial) self.video_name_format = QCheckBox(self) self.video_name_format.toggled.connect( self.video_name_properties_toggled) self.video_name_format_description = QLabel("Include Format:") video_layout.addRow(self.video_name_format_description, self.video_name_format) self.video_name_counter = QCheckBox(self) self.video_name_counter.toggled.connect( self.video_name_properties_toggled) self.video_name_counter_description = QLabel("Include Counter:") video_layout.addRow(self.video_name_counter_description, self.video_name_counter) self.video_name_counter_box = QSpinBox(self) self.video_name_counter_box.setRange(1, 10) self.video_name_counter_box.valueChanged.connect( self.video_name_counter_changed) self.video_name_counter_box_description = QLabel("Counter Size:") video_layout.addRow(self.video_name_counter_box_description, self.video_name_counter_box) self.video_name_counter.toggled.connect( self.toggle_video_counter_box_availability) self.video_name_counter.toggled.connect( self.video_name_properties_toggled) self.video_name_timestamp = QCheckBox(self) self.video_name_timestamp.toggled.connect( self.video_name_properties_toggled) self.video_name_timestamp_description = QLabel("Include Timestamp:") video_layout.addRow(self.video_name_timestamp_description, self.video_name_timestamp) layout.addWidget(video_groupbox) self.saving_widget.setLayout(layout)
#!/usr/bin/env python3 import sys from PyQt5.QtWidgets import QApplication, QWidget, QFormLayout, QLineEdit app = QApplication(sys.argv) window = QWidget() window.setWindowTitle('Q Form Layout') layout = QFormLayout() layout.addRow('Name: ', QLineEdit()) layout.addRow('Age: ', QLineEdit()) layout.addRow('Job: ', QLineEdit()) layout.addRow('Hobbies: ', QLineEdit()) window.setLayout(layout) window.show() sys.exit(app.exec_())
def __init__(self, topic=None, config=None, isPublisher=True): super(QDialog, self).__init__() self.isPublisher = isPublisher # set dialog title titleText = '' if topic is None: titleText += 'Add ' else: titleText += 'Edit ' if self.isPublisher: titleText += 'Publisher' else: titleText += 'Subscriber' self.setWindowTitle(titleText) self.topic = topic self.config = config layout = QFormLayout() self.setLayout(layout) # create gui elements methodNameLbl = None if self.isPublisher: methodNameLbl = QLabel('Method Name') else: methodNameLbl = QLabel('Variable Name') topicLbl = QLabel('Topic') typeLbl = QLabel('Type') self.methodNameEdit = QLineEdit() self.methodNameEdit.setMinimumWidth(200) self.topicEdit = QLineEdit() self.topicEdit.setMinimumWidth(200) self.typeCb = QComboBox() self.typeCb.setEditable(True) self.typeCb.setMinimumWidth(200) layout.addRow(methodNameLbl, self.methodNameEdit) layout.addRow(topicLbl, self.topicEdit) layout.addRow(typeLbl, self.typeCb) buttonLayout = QHBoxLayout() cancelBtn = QPushButton('Cancel') cancelBtn.clicked.connect(self.cancelClicked) buttonLayout.addWidget(cancelBtn) saveBtn = QPushButton('Add') saveBtn.clicked.connect(self.saveClicked) buttonLayout.addWidget(saveBtn) layout.addRow(None, buttonLayout) for type in getAllTypes(): self.typeCb.addItem(type, type) # if topic is not None activate the edit mode if self.topic is not None: saveBtn.setText('Update') if self.isPublisher: self.methodNameEdit.setText(self.topic['methodname']) else: self.methodNameEdit.setText(self.topic['variablename']) self.topicEdit.setText(self.topic['name']) # find and set the combobox to the index selectedTypeIndex = -1 for i in range(self.typeCb.count()): if self.typeCb.itemText(i) == topic['type']: selectedTypeIndex = i break if selectedTypeIndex == -1: self.typeCb.addItem(topic['type'], topic['type']) self.typeCb.setCurrentIndex(self.typeCb.count() - 1) else: self.typeCb.setCurrentIndex(selectedTypeIndex)
def __init__(self, parent=None): super().__init__(parent) self.project_name = '' self.setModal(True) self.setMinimumWidth(400) self.accepted.connect(self.save) # Project name self.project_name_input = QLineEdit() project_name_layout = QFormLayout() project_name_layout.addRow('Project name:', self.project_name_input) # Path group self.project_root_input = QLineEdit() browse_button = QPushButton('&Browse...') browse_button.clicked.connect(self.select_project_root) project_root_layout = QHBoxLayout() project_root_layout.addWidget(self.project_root_input) project_root_layout.addWidget(browse_button) self.path_mapping_input = QLineEdit() path_layout = QFormLayout() path_layout.addRow('Root:', project_root_layout) path_layout.addRow('Maps from:', self.path_mapping_input) path_group = QGroupBox('Path') path_group.setLayout(path_layout) # Debugger group self.host_input = QLineEdit() self.port_number_input = QSpinBox() self.port_number_input.setRange(1, 65535) self.idekey_input = QLineEdit() self.break_at_first_line_input = QCheckBox('Break at first line') self.max_depth_input = QSpinBox() self.max_depth_input.setRange(1, 999999999) self.max_children_input = QSpinBox() self.max_children_input.setRange(1, 999999999) self.max_data_input = QSpinBox() self.max_data_input.setRange(1, 999999999) debugger_layout = QFormLayout() debugger_layout.addRow('Host:', self.host_input) debugger_layout.addRow('Port:', self.port_number_input) debugger_layout.addRow('IDE Key:', self.idekey_input) debugger_layout.addRow('', self.break_at_first_line_input) debugger_layout.addRow('Max depth:', self.max_depth_input) debugger_layout.addRow('Max children:', self.max_children_input) debugger_layout.addRow('Max data:', self.max_data_input) debugger_group = QGroupBox('Debugger') debugger_group.setLayout(debugger_layout) # Buttons save_button = QPushButton('OK') save_button.setDefault(True) save_button.clicked.connect(self.validate) cancel_button = QPushButton('Cancel') cancel_button.clicked.connect(self.reject) button_layout = QHBoxLayout() button_layout.addWidget(save_button, 1, Qt.AlignRight) button_layout.addWidget(cancel_button) # Main layout main_layout = QVBoxLayout() main_layout.addLayout(project_name_layout) main_layout.addWidget(path_group) main_layout.addWidget(debugger_group) main_layout.addLayout(button_layout) self.setLayout(main_layout)
class CourseEditDialog(QDialog): def __init__(self, course, is_new=False): super().__init__(GlobalAccess().get_main_window()) assert (isinstance(course, Course)) self.current_object = course self.is_new = is_new def exec(self): self.init_ui() self.set_values_from_model() return super().exec() def init_ui(self): self.setWindowTitle(_('Course properties')) self.setWindowIcon(QIcon(config.ICON)) self.setSizeGripEnabled(False) self.setModal(True) self.layout = QFormLayout(self) self.label_name = QLabel(_('Name')) self.item_name = QLineEdit() self.item_name.textChanged.connect(self.check_name) self.layout.addRow(self.label_name, self.item_name) self.label_length = QLabel(_('Length')) self.item_length = QSpinBox() self.item_length.setMaximum(100000) self.item_length.setSingleStep(100) self.item_length.setValue(0) self.layout.addRow(self.label_length, self.item_length) self.label_climb = QLabel(_('Climb')) self.item_climb = QSpinBox() self.item_climb.setValue(0) self.item_climb.setMaximum(10000) self.item_climb.setSingleStep(10) self.layout.addRow(self.label_climb, self.item_climb) self.label_control_qty = QLabel(_('Point count')) self.item_control_qty = QSpinBox() self.item_control_qty.setDisabled(True) self.layout.addRow(self.label_control_qty, self.item_control_qty) self.label_controls = QLabel('{}\n\n31 150\n32 200\n33\n34 500\n...\n90 150'.format(_('Controls'))) self.item_controls = QTextEdit() self.item_controls.setTabChangesFocus(True) self.layout.addRow(self.label_controls, self.item_controls) def cancel_changes(): self.close() def apply_changes(): try: self.apply_changes_impl() except Exception as e: logging.error(str(e)) self.close() button_box = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel) self.button_ok = button_box.button(QDialogButtonBox.Ok) self.button_ok.setText(_('OK')) self.button_ok.clicked.connect(apply_changes) self.button_cancel = button_box.button(QDialogButtonBox.Cancel) self.button_cancel.setText(_('Cancel')) self.button_cancel.clicked.connect(cancel_changes) self.layout.addRow(button_box) self.show() def check_name(self): name = self.item_name.text() self.button_ok.setDisabled(False) if name and name != self.current_object.name: org = find(race().courses, name=name) if org: self.button_ok.setDisabled(True) def set_values_from_model(self): self.item_name.setText(self.current_object.name) if self.current_object.length: self.item_length.setValue(self.current_object.length) if self.current_object.climb: self.item_climb.setValue(self.current_object.climb) if self.current_object.controls: self.item_control_qty.setValue(len(self.current_object.controls)) for i in self.current_object.controls: assert isinstance(i, CourseControl) self.item_controls.append('{} {}'.format(i.code, i.length if i.length else '')) def apply_changes_impl(self): course = self.current_object if self.is_new: race().courses.insert(0, course) if course.name != self.item_name.text(): course.name = self.item_name.text() if course.length != self.item_length.value(): course.length = self.item_length.value() if course.climb != self.item_climb.value(): course.climb = self.item_climb.value() text = self.item_controls.toPlainText() course.controls.clear() for i in text.split('\n'): control = CourseControl() if i is None or len(i) == 0: continue control.code = i.split()[0] if len(i.split()) > 1: try: control.length = int(i.split()[1]) except Exception as e: logging.error(str(e)) control.length = 0 course.controls.append(control) obj = race() ResultChecker.check_all() ResultCalculation(obj).process_results() RaceSplits(obj).generate() ScoreCalculation(obj).calculate_scores() GlobalAccess().get_main_window().refresh() Teamwork().send(course.to_dict())
def __setupUi(self): """Set up the UI. """ if self.__macUnified: self.tab = QToolBar() self.addToolBar(Qt.TopToolBarArea, self.tab) self.setUnifiedTitleAndToolBarOnMac(True) # This does not seem to work self.setWindowFlags(self.windowFlags() & \ ~Qt.MacWindowToolBarButtonHint) self.tab.actionTriggered[QAction].connect( self.__macOnToolBarAction) central = QStackedWidget() central.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed) else: self.tab = central = QTabWidget(self) # Add a close button to the bottom of the dialog # (to satisfy GNOME 3 which shows the dialog without a title bar). container = container_widget_helper() container.layout().addWidget(central) buttonbox = QDialogButtonBox(QDialogButtonBox.Close) buttonbox.rejected.connect(self.close) container.layout().addWidget(buttonbox) self.setCentralWidget(container) self.stack = central # General Tab tab = QWidget() self.addTab(tab, self.tr("General"), toolTip=self.tr("General Options")) form = QFormLayout() tab.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed) nodes = QWidget(self, objectName="nodes") nodes.setLayout(QVBoxLayout()) nodes.layout().setContentsMargins(0, 0, 0, 0) cb_anim = QCheckBox(self.tr("Enable node animations"), objectName="enable-node-animations", toolTip=self.tr( "Enable shadow and ping animations for nodes " "in the workflow.")) self.bind(cb_anim, "checked", "schemeedit/enable-node-animations") nodes.layout().addWidget(cb_anim) form.addRow(self.tr("Nodes"), nodes) links = QWidget(self, objectName="links") links.setLayout(QVBoxLayout()) links.layout().setContentsMargins(0, 0, 0, 0) cb_show = QCheckBox(self.tr("Show channel names between widgets"), objectName="show-channel-names", toolTip=self.tr( "Show source and sink channel names " "over the links.")) self.bind(cb_show, "checked", "schemeedit/show-channel-names") links.layout().addWidget(cb_show) form.addRow(self.tr("Links"), links) quickmenu = QWidget(self, objectName="quickmenu-options") quickmenu.setLayout(QVBoxLayout()) quickmenu.layout().setContentsMargins(0, 0, 0, 0) cb1 = QCheckBox(self.tr("On double click"), toolTip=self.tr("Open quick menu on a double click " "on an empty spot in the canvas")) cb2 = QCheckBox(self.tr("On right click"), toolTip=self.tr("Open quick menu on a right click " "on an empty spot in the canvas")) cb3 = QCheckBox(self.tr("On space key press"), toolTip=self.tr("On Space key press while the mouse" "is hovering over the canvas.")) cb4 = QCheckBox(self.tr("On any key press"), toolTip=self.tr("On any key press while the mouse" "is hovering over the canvas.")) self.bind(cb1, "checked", "quickmenu/trigger-on-double-click") self.bind(cb2, "checked", "quickmenu/trigger-on-right-click") self.bind(cb3, "checked", "quickmenu/trigger-on-space-key") self.bind(cb4, "checked", "quickmenu/trigger-on-any-key") quickmenu.layout().addWidget(cb1) quickmenu.layout().addWidget(cb2) quickmenu.layout().addWidget(cb3) quickmenu.layout().addWidget(cb4) form.addRow(self.tr("Open quick menu on"), quickmenu) startup = QWidget(self, objectName="startup-group") startup.setLayout(QVBoxLayout()) startup.layout().setContentsMargins(0, 0, 0, 0) cb_splash = QCheckBox(self.tr("Show splash screen"), self, objectName="show-splash-screen") cb_welcome = QCheckBox(self.tr("Show welcome screen"), self, objectName="show-welcome-screen") self.bind(cb_splash, "checked", "startup/show-splash-screen") self.bind(cb_welcome, "checked", "startup/show-welcome-screen") startup.layout().addWidget(cb_splash) startup.layout().addWidget(cb_welcome) form.addRow(self.tr("On startup"), startup) toolbox = QWidget(self, objectName="toolbox-group") toolbox.setLayout(QVBoxLayout()) toolbox.layout().setContentsMargins(0, 0, 0, 0) exclusive = QCheckBox(self.tr("Only one tab can be open at a time")) self.bind(exclusive, "checked", "mainwindow/toolbox-dock-exclusive") toolbox.layout().addWidget(exclusive) form.addRow(self.tr("Tool box"), toolbox) tab.setLayout(form) # Output Tab tab = QWidget() self.addTab(tab, self.tr("Output"), toolTip="Output Redirection") form = QFormLayout() box = QWidget(self, objectName="streams") layout = QVBoxLayout() layout.setContentsMargins(0, 0, 0, 0) cb1 = QCheckBox(self.tr("Standard output")) cb2 = QCheckBox(self.tr("Standard error")) self.bind(cb1, "checked", "output/redirect-stdout") self.bind(cb2, "checked", "output/redirect-stderr") layout.addWidget(cb1) layout.addWidget(cb2) box.setLayout(layout) form.addRow(self.tr("Redirect output"), box) box = QWidget() layout = QVBoxLayout() layout.setContentsMargins(0, 0, 0, 0) combo = QComboBox() combo.addItems([ self.tr("Critical"), self.tr("Error"), self.tr("Warn"), self.tr("Info"), self.tr("Debug") ]) cb = QCheckBox(self.tr("Show output on 'Error'"), objectName="focus-on-error") self.bind(combo, "currentIndex", "logging/level") self.bind(cb, "checked", "output/show-on-error") layout.addWidget(combo) layout.addWidget(cb) box.setLayout(layout) form.addRow(self.tr("Logging"), box) box = QWidget() layout = QVBoxLayout() layout.setContentsMargins(0, 0, 0, 0) cb1 = QCheckBox(self.tr("Stay on top"), objectName="stay-on-top") cb2 = QCheckBox(self.tr("Dockable"), objectName="output-dockable") self.bind(cb1, "checked", "output/stay-on-top") self.bind(cb2, "checked", "output/dockable") layout.addWidget(cb1) layout.addWidget(cb2) box.setLayout(layout) form.addRow(self.tr("Output window"), box) box = QWidget() layout = QVBoxLayout() layout.setContentsMargins(0, 0, 0, 0) cb1 = QCheckBox(self.tr("Open in external browser"), objectName="open-in-external-browser") cb2 = QCheckBox(self.tr("Stay on top"), objectName="help-stay-on-top") cb3 = QCheckBox(self.tr("Dockable"), objectName="help-dockable") self.bind(cb1, "checked", "help/open-in-external-browser") self.bind(cb2, "checked", "help/stay-on-top") self.bind(cb3, "checked", "help/dockable") layout.addWidget(cb1) layout.addWidget(cb2) layout.addWidget(cb3) box.setLayout(layout) form.addRow(self.tr("Help window"), box) tab.setLayout(form) # Applications Specific tab = QWidget() self.addTab(tab, self.tr("Applications"), toolTip=self.tr("Applications Specific Options")) form = QFormLayout() tab.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed) tab.setLayout(form) # Categories Tab tab = QWidget() layout = QVBoxLayout() view = QListView() from .. import registry reg = registry.global_registry() model = QStandardItemModel() settings = QSettings() for cat in reg.categories(): item = QStandardItem() item.setText(cat.name) item.setCheckable(True) visible, _ = category_state(cat, settings) item.setCheckState(Qt.Checked if visible else Qt.Unchecked) model.appendRow([item]) view.setModel(model) layout.addWidget(view) tab.setLayout(layout) model.itemChanged.connect(lambda item: save_category_state( reg.category(str(item.text())), _State(item.checkState() == Qt.Checked, -1), settings)) self.addTab(tab, "Categories") if self.__macUnified: # Need some sensible size otherwise mac unified toolbar 'takes' # the space that should be used for layout of the contents self.adjustSize()
def init_ui(self): self.setWindowTitle('PidInterface') # Parameters self.sample_time_spin = QSpinBox() self.sample_time_spin.setMinimum(0) self.sample_time_spin.setMaximum(1000) self.sample_time_spin.setSuffix(' ms') self.sample_time_spin.setValue(self.sample_time) self.sample_time_spin.valueChanged.connect(self.set_sample_time) self.kp_spin = QDoubleSpinBox() self.kp_spin.setMinimum(0) self.kp_spin.setMaximum(float('inf')) self.kp_spin.setValue(self.kp) self.kp_spin.valueChanged.connect(self.set_kp) self.ki_spin = QDoubleSpinBox() self.ki_spin.setMinimum(0) self.ki_spin.setMaximum(float('inf')) self.ki_spin.setValue(self.ki) self.ki_spin.valueChanged.connect(self.set_ki) self.kd_spin = QDoubleSpinBox() self.kd_spin.setMinimum(0) self.kd_spin.setMaximum(float('inf')) self.kd_spin.setValue(self.kd) self.kd_spin.valueChanged.connect(self.set_kd) self.setpoint_slider = QSlider(QtCore.Qt.Horizontal) self.setpoint_slider.setMinimum(0) self.setpoint_slider.setMaximum(self.max_setpoint) self.setpoint_slider.setValue(0) self.setpoint_slider.sliderMoved.connect(self.set_setpoint) self.mode_check = QCheckBox() self.mode_check.setChecked(self.mode) self.mode_check.toggled.connect(self.set_mode) self.anti_windup_check = QCheckBox() self.anti_windup_check.setChecked(self.anti_windup) self.anti_windup_check.toggled.connect(self.set_anti_windup) parameters_layout = QFormLayout() parameters_layout.addRow('sample_time', self.sample_time_spin) parameters_layout.addRow('kp', self.kp_spin) parameters_layout.addRow('ki', self.ki_spin) parameters_layout.addRow('kd', self.kd_spin) parameters_layout.addRow('setpoint', self.setpoint_slider) parameters_layout.addRow('mode', self.mode_check) parameters_layout.addRow('anti_windup', self.anti_windup_check) parameters_group = QGroupBox('Parameters') parameters_group.setLayout(parameters_layout) apply_button = QPushButton('Apply') apply_button.clicked.connect(self.sent_parameters) pid_layout = QVBoxLayout() pid_layout.addWidget(parameters_group) pid_layout.addWidget(apply_button) pid_layout.addStretch() # Display self.plot = BeautifulPlot(self) # Main main_layout = QHBoxLayout() main_layout.addLayout(pid_layout) main_layout.addWidget(self.plot) self.setLayout(main_layout)
def _updateLayout(self, node): layout = self._layout # Meta Args meta_args = node.params.get('meta_args') if meta_args and self._show_meta: meta_arg_data = node.params_info["meta_args"] # Create container if self._show_compact: this_layout = layout else: box = QFrame() box.setFrameShape(QFrame.StyledPanel) this_layout = QFormLayout() box.setLayout(this_layout) layout.addRow(self.tr("Meta Args"), box) for name, value in meta_args.items(): try: inspector_option = meta_arg_data[name] # This happens with hidden args passed to factory (currently only exists for meta args # [hive.pull/push in/out]) # Hidden args means that the inspector didn't find these args, but they were passed in the args dict except KeyError: continue widget, controller = create_widget(inspector_option.data_type, inspector_option.options) widget.setEnabled(False) controller.value = value this_layout.addRow(self.tr(name), widget) edit_button = QPushButton('Re-configure') edit_button.setToolTip( "Re-create this node with new meta-args, and attempt to preserve state" ) edit_button.clicked.connect(lambda: self.doMorphNode.emit(node)) this_layout.addRow(edit_button) # Args for wrapper_name, title_name in (("args", "Builder Args"), ("cls_args", "Class Args")): try: args = node.params[wrapper_name] except KeyError: continue arg_data = node.params_info[wrapper_name] # Create container if self._show_compact: this_layout = layout else: box = QFrame() box.setFrameShape(QFrame.StyledPanel) this_layout = QFormLayout() box.setLayout(this_layout) layout.addRow(self.tr(title_name), box) for name, value in args.items(): # Get data type inspector_option = arg_data[name] widget, controller = create_widget(inspector_option.data_type, inspector_option.options) widget.controller = controller def on_changed(value, name=name, wrapper_name=wrapper_name): self.updateParam.emit(node, wrapper_name, name, value) controller.value = value controller.on_changed.subscribe(on_changed) this_layout.addRow(self.tr(name), widget)
def stack1UI(self): layout = QFormLayout() layout.addRow("Name", QLineEdit()) layout.addRow("Address", QLineEdit()) # self.setTabText(0,"Contact Details") self.stack1.setLayout(layout)
def __init__(self): super().__init__() self.rm = visa.ResourceManager() self.rm.list_resources() self.setWindowTitle("Spectrum Analyzer") containerWidget = QWidget(self) formLayout = QFormLayout(containerWidget) self.address = QLineEdit(containerWidget) self.address.insert("TCPIP0::172.17.66.10::inst0::INSTR") formLayout.addRow("Address", self.address) self.m_connect = QPushButton("Connect", containerWidget) formLayout.addRow(self.m_connect) self.m_saStartFreq = QLineEdit(containerWidget) self.m_saStartFreq.insert("900") formLayout.addRow("Start Frequency (MHz)", self.m_saStartFreq) self.m_saStopFreq = QLineEdit(containerWidget) self.m_saStopFreq.insert("930") formLayout.addRow("Stop Frequency (MHz)", self.m_saStopFreq) self.m_saCenterFreq = QLineEdit(containerWidget) self.m_saCenterFreq.insert("915") formLayout.addRow("Center Frequency (MHz)", self.m_saCenterFreq) self.m_saSpan = QLineEdit(containerWidget) self.m_saSpan.insert("1") formLayout.addRow("Span (MHz)", self.m_saSpan) self.m_saExternalGain = QLineEdit(containerWidget) self.m_saExternalGain.insert("-10.8") formLayout.addRow("External Gain (dB)", self.m_saExternalGain) self.m_saRefLevel = QLineEdit(containerWidget) self.m_saRefLevel.insert("30") formLayout.addRow("Ref Level (dBm)", self.m_saRefLevel) self.m_saScale = QLineEdit(containerWidget) self.m_saScale.insert("10") formLayout.addRow("Scale (dB)", self.m_saScale) self.m_saAttenuation = QComboBox(containerWidget) for i in range(5): self.m_saAttenuation.insertItem(i, str(i * 10)) self.m_saAttenuation.setCurrentIndex(3) formLayout.addRow("Attenuation (dB)", self.m_saAttenuation) self.m_saRBW = QLineEdit(containerWidget) self.m_saRBW.insert("100") formLayout.addRow("RBW (KHz)", self.m_saRBW) self.m_saVBW = QLineEdit(containerWidget) self.m_saVBW.insert("300") formLayout.addRow("VBW (KHz)", self.m_saVBW) self.m_saTrace = QComboBox(containerWidget) self.m_saTrace.insertItem(0, "ClearWrite") self.m_saTrace.insertItem(1, "Average") self.m_saTrace.insertItem(2, "MaxHold") formLayout.addRow("Trace", self.m_saTrace) self.m_saDetector = QComboBox(containerWidget) self.m_saDetector.insertItem(0, "Average") self.m_saDetector.insertItem(1, "Peak") self.m_saDetector.insertItem(2, "Normal") self.m_saDetector.insertItem(3, "Sample") self.m_saDetector.insertItem(4, "QPeak") self.m_saDetector.insertItem(5, "EMI Average") formLayout.addRow("Detector", self.m_saDetector) self.m_saStartFreq.setEnabled(False) self.m_saStopFreq.setEnabled(False) self.m_saCenterFreq.setEnabled(False) self.m_saSpan.setEnabled(False) self.m_saRefLevel.setEnabled(False) self.m_saScale.setEnabled(False) self.m_saExternalGain.setEnabled(False) self.m_saAttenuation.setEnabled(False) self.m_saRBW.setEnabled(False) self.m_saVBW.setEnabled(False) self.m_saTrace.setEnabled(False) self.m_saDetector.setEnabled(False) self.groupBox = QGroupBox("Spectrum Analyzer", self) self.groupBox.setLayout(formLayout) layout = QVBoxLayout() layout.addWidget(self.groupBox) self.setLayout(layout) self.m_connect.clicked.connect(lambda: self.connect()) self.m_saStartFreq.editingFinished.connect(lambda: self.setStartFreq(float(self.m_saStartFreq.text()) * 1e6)) self.m_saStopFreq.editingFinished.connect(lambda: self.setStopFreq(float(self.m_saStopFreq.text()) * 1e6)) self.m_saCenterFreq.editingFinished.connect(lambda: self.setCenterFreq(float(self.m_saCenterFreq.text()) * 1e6)) self.m_saSpan.editingFinished.connect(lambda: self.setSpan(float(self.m_saSpan.text()) * 1e6)) self.m_saExternalGain.editingFinished.connect(lambda: self.setExternalGain(float(self.m_saExternalGain.text()))) self.m_saAttenuation.currentIndexChanged.connect(lambda: self.setAttenuation(int(self.m_saAttenuation.currentIndex()) * 10)) self.m_saRefLevel.editingFinished.connect(lambda: self.setRefLevel(float(self.m_saRefLevel.text()))) self.m_saRBW.editingFinished.connect(lambda: self.setRBW(float(self.m_saRBW.text()) * 1e3)) self.m_saTrace.currentIndexChanged.connect(lambda: self.setTrace(self.m_saTrace.currentIndex())) self.m_saDetector.currentIndexChanged.connect(lambda: self.setDetector(self.m_saDetector.currentIndex()))
class OperatorSaveWindow(QDialog): """ With this class QDialog for adding new model.Operator into database is shown. """ def __init__(self, tableWidget): """ constructor :param tableWidget: QTableWidget """ super().__init__() self.tableWidget = tableWidget self.title = "Save New Operator" self.left, self.top, self.width, self.height = 50, 50, 500, 500 self.validator = OperatorValidator() self.dao = OperatorDAOPymysqlImpl() self.initGUI() def initGUI(self): """ initializes GUI :return: """ self.setWindowTitle(self.title) self.setGeometry(self.left * 2, self.top * 2, self.width, self.height / 2.2) self.setWindowModality(Qt.ApplicationModal) self.addComponents() self.registerEvents() def addComponents(self): """ sets the mainLayout for this class and adds components into it. :return: """ self.mainLayout = QFormLayout() self.setLayout(self.mainLayout) # title self.lblTitle = QLabel("Save New Operator") self.lblEmpty = QLabel() # code self.lblCode = QLabel("Code: ") self.editCode = QLineEdit() self.editCode.setPlaceholderText("Code") self.editCode.setInputMask('99999') # name self.lblName = QLabel("Name: ") self.editName = QLineEdit() self.editName.setPlaceholderText("Name") # validation self.lblValidation = QLabel("Validation: ") self.editValidation = QComboBox() self.editValidation.addItem("N") self.editValidation.addItem("Y") # remark self.lblRemark = QLabel("Remark: ") self.editRemark = QLineEdit() self.editRemark.setPlaceholderText("Remark") # buttons self.btnSave = QPushButton("Save") self.btnCancel = QPushButton("Cancel") # add all rows to mainLayout self.mainLayout.addRow(self.lblEmpty, self.lblTitle) self.mainLayout.addRow(self.lblCode, self.editCode) self.mainLayout.addRow(self.lblName, self.editName) self.mainLayout.addRow(self.lblValidation, self.editValidation) self.mainLayout.addRow(self.lblRemark, self.editRemark) self.mainLayout.addRow(self.btnSave, self.btnCancel) def registerEvents(self): """ registers events :return: """ self.btnSave.clicked.connect(self.onBtnSaveClicked) self.btnCancel.clicked.connect(self.onBtnCancelClicked) @pyqtSlot() def onBtnSaveClicked(self): """ Slot for signal-slot handling . Gets invoked when btnSave is clicked. :return: """ try: errors = [] code = self.editCode.text() name = self.editName.text() validation = self.editValidation.itemText( self.editValidation.currentIndex()) remark = self.editRemark.text() if not self.validator.validateCode(code): errors.append("code is incorrect.") if not self.validator.validateName(name): errors.append("name is incorrect.") if not self.validator.validateValidation(validation): errors.append("Validation is incorrect.") if not self.validator.validateRemark(remark): errors.append("Remark is incorrect.") if len(errors) > 0: raise Exception("\n".join(errors)) ret = self.dao.save( Operator(0, "", "", "", "", "", "", "", "", code, name, validation, remark)) if ret: raise Exception(ret) rowPosition = self.tableWidget.rowCount() self.tableWidget.insertRow(rowPosition) self.tableWidget.setItem(rowPosition, 10, QTableWidgetItem(code)) self.tableWidget.setItem(rowPosition, 11, QTableWidgetItem(name)) self.tableWidget.setItem(rowPosition, 12, QTableWidgetItem(validation)) self.tableWidget.setItem(rowPosition, 13, QTableWidgetItem(remark)) self.close() except Exception as err: QMessageBox.critical(self, "<<Error>>", str(err)) @pyqtSlot() def onBtnCancelClicked(self): """ Slot for signal-slot handling . Gets invoked when btnCancel is clicked. :return: """ self.close()
def __init__(self, parent=None): QWidget.__init__(self, parent) self.setWindowFlags(QtCore.Qt.Dialog | QtCore.Qt.WindowSystemMenuHint) self.setWindowModality(QtCore.Qt.WindowModal) global par par = parent global int_lng int_lng = par.interface_lng_val # ------------------------------------Первый блок формы-------------------------------------- if int_lng == 'Russian': file_create_lbl = QLabel("Укажите имя файла:") elif int_lng == 'English': file_create_lbl = QLabel("Enter file name:") file_hbox = QHBoxLayout() file_hbox.addWidget(file_create_lbl) self.file_edit = QLineEdit() self.file_edit.setFixedSize(200, 27) file_hbox.addWidget(self.file_edit) if int_lng == 'Russian': object_create_lbl = QLabel("Укажите имя объекта:") elif int_lng == 'English': object_create_lbl = QLabel("Enter object name:") object_hbox = QHBoxLayout() object_hbox.addWidget(object_create_lbl) self.object_edit = QLineEdit() self.object_edit.setFixedSize(200, 27) object_hbox.addWidget(self.object_edit) block_grid = QGridLayout() block_grid.addLayout(file_hbox, 0, 0) block_grid.addLayout(object_hbox, 1, 0) # ---------------------Кнопки сохранения и отмены и их блок------------------------- if int_lng == 'Russian': save_button = QPushButton("Сохранить") cancel_button = QPushButton("Отмена") elif int_lng == 'English': save_button = QPushButton("Save") cancel_button = QPushButton("Cancel") save_button.setFixedSize(80, 25) save_button.clicked.connect(self.on_save_clicked) cancel_button.setFixedSize(80, 25) cancel_button.clicked.connect(self.on_cancel_clicked) buttons_hbox = QHBoxLayout() buttons_hbox.addWidget(save_button) buttons_hbox.addWidget(cancel_button) # -------------------------Фрейм формы--------------------------- bound_grid = QGridLayout() bound_grid.addLayout(block_grid, 0, 0, alignment=QtCore.Qt.AlignCenter) bound_grid.addLayout(buttons_hbox, 1, 0, alignment=QtCore.Qt.AlignCenter) bound_frame = QFrame() bound_frame.setStyleSheet(open("./styles/properties_form_style.qss", "r").read()) bound_frame.setLayout(bound_grid) bound_vbox = QVBoxLayout() bound_vbox.addWidget(bound_frame) # --------------------Размещение на форме всех компонентов--------- form_1 = QFormLayout() form_1.addRow(bound_vbox) self.setLayout(form_1)
def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) # get the PID parameter ranges from the settings file. kp_min, kp_init, kp_max = stng.PID_P ki_min, ki_init, ki_max = stng.PID_I kd_min, kd_init, kd_max = stng.PID_D # remember the initial values so they can be retrieved for a PID reset self.kp_init = kp_init self.ki_init = ki_init self.kd_init = kd_init # get the outer temperature averaging duration from the settings file, but # if not present (recent addition to settings file), assume no averaging. outer_avg_duration = stng.OUTER_AVG_SECONDS if hasattr( stng, 'OUTER_AVG_SECONDS') else None # make a controller object self.controller = Controller( stng.OUTER_TEMPS, stng.INNER_TEMPS, stng.INFO_TEMPS, stng.THERMISTOR_DIVIDER_R, stng.THERMISTOR_APPLIED_V_CH, stng.CONTROL_PERIOD, outer_avg_duration, stng.PWM_CHANNEL, stng.PWM_PERIOD, stng.INIT_PWM_MAX, (kp_init, ki_init, kd_init), None) # I discovered that I cannot create a pyqtgraph inside of the controller # callback function. It works for awhile and then freezes. I needed to # use a QTimer to add real-time graph points. self.plotDelta = SimplePlot('Minute (0 = Now)', 'Inner - Outer (°F)') self.plotPWM = SimplePlot('Minute (0 = Now)', 'Heater Output, % of Max') self.plotPWM.setYRange(0.0, 1.03, padding=0) self.plotTemperature = SimplePlot('Minute (0 = Now)', 'Temperature (°F)') self.plotTemperature.addLegend() # combos to select the two sensors to plot on the bottom graph. self.combo_sensor1 = QComboBox() lbl_sensor1 = QLabel('Sensor 1:') lbl_sensor1.setBuddy(self.combo_sensor1) self.combo_sensor2 = QComboBox() lbl_sensor2 = QLabel('Sensor 2:') lbl_sensor2.setBuddy(self.combo_sensor2) # Make a list of all the temperature sensors and their associated dictionary # keys to populate the combo boxes with. temp_list = make_temp_list(stng.INNER_TEMPS, 'Inner') temp_list += make_temp_list(stng.OUTER_TEMPS, 'Outer') temp_list += make_temp_list(stng.INFO_TEMPS, 'Info') # fill the combos and select the starting temperature values. ix = 0 for lbl, data in temp_list: if data == ('inner', 'average'): combo1_ix = ix # default item for sensor 1 if data == ('outer', 'rolling_avg'): combo2_ix = ix # default item for sensor 2 self.combo_sensor1.addItem(lbl, data) self.combo_sensor2.addItem(lbl, data) ix += 1 self.combo_sensor1.setCurrentIndex(combo1_ix) self.combo_sensor2.setCurrentIndex(combo2_ix) sensor_box = QHBoxLayout() sensor_box.addWidget(lbl_sensor1) sensor_box.addWidget(self.combo_sensor1) sensor_box.addSpacing(30) sensor_box.addWidget(lbl_sensor2) sensor_box.addWidget(self.combo_sensor2) sensor_box.addStretch(1) graph_layout = QVBoxLayout() graph_layout.addWidget(self.plotDelta) graph_layout.addWidget(self.plotPWM) graph_layout.addLayout(sensor_box) graph_layout.addWidget(self.plotTemperature) controls = QWidget() controls.setFixedWidth(250) controls.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Expanding) control_layout = QVBoxLayout() self.check_enable_heater = QCheckBox('Enable Heater') self.check_enable_heater.stateChanged.connect( self.enable_heater_change) self.enable_heater_change() control_layout.addWidget(self.check_enable_heater) control_layout.addSpacing(20) pid_group = QGroupBox('PID Tuning Parameters') pid_form = QFormLayout() self.slider_kp = SliderWithVal((kp_min, kp_max), kp_init, 2) self.slider_ki = SliderWithVal((ki_min, ki_max), ki_init, 3) self.slider_kd = SliderWithVal((kd_min, kd_max), kd_init, 2) pid_form.addRow("P", self.slider_kp) pid_form.addRow("I", self.slider_ki) pid_form.addRow("D", self.slider_kd) pid_group.setLayout(pid_form) control_layout.addWidget(pid_group) # handle change in PID tuning sliders self.slider_kp.valueChanged.connect(self.pid_tuning_change) self.slider_ki.valueChanged.connect(self.pid_tuning_change) self.slider_kd.valueChanged.connect(self.pid_tuning_change) self.button_reset_pid = QPushButton('Restore Initial PID Tunings') self.button_reset_pid.clicked.connect(self.ask_reset_pid) control_layout.addWidget(self.button_reset_pid) control_layout.addSpacing(20) self.slider_heater_max = SliderWithVal((0.0, 1.0), stng.INIT_PWM_MAX, 2) self.slider_heater_max.valueChanged.connect(self.heater_max_change) control_layout.addWidget( QLabel('Maximum Heater Output\n(% of Full Capacity)')) control_layout.addWidget(self.slider_heater_max) control_layout.addSpacing(20) self.check_enable_on_off = QCheckBox('Enable Simple On/Off Control') self.check_enable_on_off.stateChanged.connect( self.enable_on_off_change) self.enable_on_off_change() control_layout.addWidget(self.check_enable_on_off) control_layout.addSpacing(20) self.label_log_name = QLabel('') control_layout.addWidget(self.label_log_name) self.button_start_new_log = QPushButton('Start New Log File') self.button_start_new_log.clicked.connect(self.ask_new_log_file) control_layout.addWidget(self.button_start_new_log) self.start_new_log_file() control_layout.addStretch(1) controls.setLayout(control_layout) main_layout = QHBoxLayout() main_layout.addWidget(controls) main_layout.addLayout(graph_layout) self.setLayout(main_layout) self.setGeometry(1000, 800, 1000, 800) self.setWindowTitle('Heater Controller') # the current index into the plotting arrays self.plot_ix = 0 # index to keep track of when to log to file self.log_ix = 0 # Start the controller self.controller.start() # Start a timer to update plots in this GUI self.plot_timer = QTimer() self.plot_timer.setInterval(int(stng.PLOT_TIME_INTERVAL * 1000)) self.plot_timer.timeout.connect(self.handle_control_results) self.plot_timer.start()
def initUI(self): pg.setConfigOption('background', 'w') params = { 'figure.figsize': [4, 4], 'figure.dpi': 300, 'savefig.dpi': 300 } plt.rcParams.update(params) ############################################################################### ########Variables Globales #################################################### ############################################################################### self.setWindowTitle('Detrended Analysis Fluctuation') self.setWindowIcon(QIcon("Icons\DFA.ico")) self.resize(1000, 600) self.ruta = None self.nombreSenial1='' self.x=[] self.y1=[] self.h1=[] contain = QSplitter(Qt.Horizontal) botones = QtWidgets.QVBoxLayout() graficos = QVBoxLayout() results1 = QFormLayout() results2 = QFormLayout() results3 = QFormLayout() results4 = QFormLayout() group_box_files = QGroupBox("Load file(s)") group_box_settings = QGroupBox("Settings") group_box_plots = QGroupBox("Plots") group_box_values = QGroupBox("Values") ################################################################# ## Elementos del layout botones ################################################################# self.btnLoadSig1 = QPushButton('Load signal') self.btnLoadSig1.clicked.connect(self.cargarSenial1) self.btnLoadSig1.setStyleSheet("font-size: 18px") lblm1 = QLabel("P adjust degree: ") lblm1.setStyleSheet("font-size: 18px") self.txtm1 = QLineEdit('1') self.txtm1.setEnabled(False) self.txtm1.setStyleSheet("font-size: 18px") lblh1 = QLabel("Hurst exponent h: ") lblh1.setStyleSheet("font-size: 18px") self.txth1 = QLineEdit('') self.txth1.setEnabled(False) lblr1 = QLabel("R^2: ") lblr1.setStyleSheet("font-size: 18px") self.txtr1 = QLabel('') self.lbl_num_files = QLabel("Files loaded: ") self.lbl_num_files.setStyleSheet("font-size: 18px") self.btnDFA1 = QPushButton('DFA') self.btnDFA1.clicked.connect(self.DFA1) self.btnDFA1.setStyleSheet("font-size: 18px") self.btnDFA1.setEnabled(False) lbl_file = QLabel("File: ") lbl_file.setStyleSheet("font-size: 18px") self.list3 = QComboBox() self.list3.currentIndexChanged.connect(self.plots) lbl_DFA = QLabel("DFA: ") lbl_DFA.setStyleSheet("font-size: 18px") self.list_DFA = QComboBox() self.list_DFA.currentIndexChanged.connect(self.plots_DFA) ################################################################# ## Colocar elementos en layout botones ################################################################# results1.addRow(self.btnLoadSig1) results1.addRow(self.lbl_num_files) group_box_files.setLayout(results1) results2.addRow(lblm1, self.txtm1) group_box_settings.setLayout(results2) results3.addRow(lbl_file, self.list3) results3.addRow(lbl_DFA, self.list_DFA) group_box_plots.setLayout(results3) results4.addRow(lblh1, self.txth1) results4.addRow(lblr1, self.txtr1) group_box_values.setLayout(results4) botones.addWidget(group_box_files) botones.addWidget(group_box_settings) botones.addWidget(group_box_plots) botones.addWidget(group_box_values) botones.addWidget(self.btnDFA1) ################################################################# ## Colocar elementos en layout graficos ################################################################# self.plot1=pg.PlotWidget() self.plot1.setLabel('bottom',color='k', **{'font-size':'14pt'}) self.plot1.getAxis('bottom').setPen(pg.mkPen(color='k', width=1)) self.plot1.setLabel('left',color='k', **{'font-size':'14pt'}) self.plot1.getAxis('left').setPen(pg.mkPen(color='k', width=1)) self.plot1.showGrid(1,1,0.2) graficos.addWidget(self.plot1) bot = QWidget() bot.setLayout(botones) gra = QWidget() gra.setLayout(graficos) contain.addWidget(bot) contain.addWidget(gra) self.setCentralWidget(contain)
class CardinalityRestrictionForm(QDialog): """ This class implements the form used to input domain/range restriction cardinalities. """ def __init__(self, parent=None): """ Initialize the form dialog. :type parent: QWidget """ super().__init__(parent) self.minCardinalityValue = None self.maxCardinalityValue = None self.minCardinalityField = IntField(self) self.maxCardinalityField = IntField(self) self.minCardinalityField.setFixedWidth(80) self.maxCardinalityField.setFixedWidth(80) self.buttonBox = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel, Qt.Horizontal, self) self.mainLayout = QFormLayout(self) self.mainLayout.addRow('Min. cardinality', self.minCardinalityField) self.mainLayout.addRow('Max. cardinality', self.maxCardinalityField) self.mainLayout.addRow(self.buttonBox) self.setWindowTitle('Insert cardinality') self.setWindowIcon(QIcon(':/images/eddy')) self.setFixedSize(self.sizeHint()) connect(self.buttonBox.accepted, self.validate) connect(self.buttonBox.rejected, self.reject) #################################################################################################################### # # # SLOTS # # # #################################################################################################################### @pyqtSlot() def validate(self): """ Validate the form and trigger accept() if the form is valid. """ if not isEmpty(self.minCardinalityField.text()) and not isEmpty(self.maxCardinalityField.text()): v1 = int(self.minCardinalityField.text()) v2 = int(self.maxCardinalityField.text()) if v1 > v2: msgbox = QMessageBox(self) msgbox.setIconPixmap(QPixmap(':/icons/warning')) msgbox.setWindowIcon(QIcon(':/images/eddy')) msgbox.setWindowTitle('Invalid range specified') msgbox.setText('Minimum cardinality {} must be lower or equal than Maximum cardinality {}'.format(v1, v2)) msgbox.setStandardButtons(QMessageBox.Ok) msgbox.exec_() return if not isEmpty(self.minCardinalityField.text()): self.minCardinalityValue = int(self.minCardinalityField.text()) if not isEmpty(self.maxCardinalityField.text()): self.maxCardinalityValue = int(self.maxCardinalityField.text()) self.accept()