def __init__(self, parent=None, group_name=''): super().__init__(parent) if not group_name: window_title = _('Create a new group of students') message = _('Please, enter the name of the new group of students ' 'you want to create:') else: window_title = _('Rename the group of students') message = _('Please, enter the new name of the group of students') self.setWindowTitle(window_title) self.group_name = group_name layout = QVBoxLayout(self) self.setLayout(layout) self._name_widget = QLineEdit(self) if group_name: self._name_widget.setText(group_name) self._name_widget.selectAll() self._name_widget.textChanged.connect(self._group_name_changed) main_line = widgets.LineContainer( self, QLabel(_('Group name')), self._name_widget) buttons = QDialogButtonBox(QDialogButtonBox.Ok|QDialogButtonBox.Cancel) self._button_ok = buttons.button(QDialogButtonBox.Ok) layout.addWidget(QLabel(message)) layout.addWidget(main_line) layout.addWidget(buttons) buttons.accepted.connect(self.accept) buttons.rejected.connect(self.reject) self._group_name_changed(group_name)
class GstPipeEditDialog(QDialog): def __init__(self, pipe, app_mode=False, **kwargs): super().__init__(**kwargs) self.setLayout(QVBoxLayout()) self.setWindowTitle('Edit Pipeline') self.setWindowModality(Qt.ApplicationModal) self.setMaximumSize(500, 400) self.setMinimumSize(500, 400) self.resize(500, 400) # GstPipeEdit self.pipeEdit = GstPipeEdit(pipe, app_mode=app_mode, parent=self) self.layout().addWidget(self.pipeEdit) # Confirm/Cancel buttons self.dialogButtons = QDialogButtonBox(self) self.dialogButtons.setStandardButtons(QDialogButtonBox.Cancel | QDialogButtonBox.Ok) self.layout().addWidget(self.dialogButtons) self.dialogButtons.accepted.connect(self.accept) self.dialogButtons.rejected.connect(self.reject) def get_pipe(self): return self.pipeEdit.get_pipe()
def manage_properties(self): self.update() self.setWindowTitle('Properties:') layout = QGridLayout() button_box = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel) button_box.button(QDialogButtonBox.Ok).setDefault(True) for idx, prop in enumerate(sorted(self.flume_object.properties.keys())): label = QLabel(prop + ':') editor = QLineEdit(self.flume_object.properties[prop]["value"]) if prop == "type": editor.setReadOnly(True) if self.flume_object.properties[prop]["required"]: label.setText(prop + ":*") pass # label.setFont(QFont) TODO editor.setToolTip(self.flume_object.properties[prop]["description"]) editor.setToolTipDuration(-1) self.new_properties[prop] = editor label.setBuddy(self.new_properties[prop]) layout.addWidget(label, idx, 0) layout.addWidget(self.new_properties[prop], idx, 1) layout.addWidget(button_box) self.setLayout(layout) button_box.accepted.connect(self.accept_prop) button_box.rejected.connect(self.reject)
def __init__(self, parent=None): super(MyController, self).__init__(parent) self.theClassNames = QList() self.theClassCombo = QComboBox(self) self.theControlledObject = None button = QToolButton(self) self.theController = ObjectController(self) buttonBox = QDialogButtonBox(self) button.clicked.connect(self.createAndControl) buttonBox.rejected.connect(self.reject) button.setText(self.tr("Create And Control")) buttonBox.setStandardButtons(QDialogButtonBox.Close) layout = QVBoxLayout(self) internalLayout = QHBoxLayout() internalLayout.addWidget(self.theClassCombo) internalLayout.addWidget(button) layout.addLayout(internalLayout) layout.addWidget(self.theController) layout.addWidget(buttonBox) self.theClassNames.append("QWidget") self.theClassNames.append("QPushButton") self.theClassNames.append("QDialogButtonBox") self.theClassNames.append("QTreeWidget") self.theClassNames.append("QCalendarWidget") self.theClassNames.append("QAction") self.theClassNames.append("QTimeLine") self.theClassNames.append("QTextDocument") self.theClassCombo.addItems(self.theClassNames)
class GUI(QDialog): def __init__(self, settings): super(QDialog, self).__init__() self.setWindowTitle("Settings") self.setWindowIcon(QIcon('ui/icon.png')) self.setModal(True) self.setWindowFlags(Qt.WindowStaysOnTopHint) self._button_box = QDialogButtonBox( QDialogButtonBox.Ok ) self._button_box.button(QDialogButtonBox.Ok).clicked.connect(self.accept) self._tabs = QTabWidget() self._layout = QBoxLayout(QBoxLayout.TopToBottom) self._layout.addWidget(self._tabs) self._layout.addWidget(self._button_box) self.setLayout(self._layout) # setup tabs self.tab_list = {} self.widgets = {} # general tab general_tab = GeneralTab(settings) self._tabs.addTab(general_tab, general_tab.get_title()) characters_tab = CharactersTab(settings) self._tabs.addTab(characters_tab, characters_tab.get_title()) def set_show_tab(self, tab): if tab == "characters": self._tabs.setCurrentIndex(1)
def get_properties(self): self.setWindowTitle('Component type') layout = QVBoxLayout() label = QLabel() label.setText('Component type:') # combo_box.setEditable(True) # print(self.flume_object.component) for f in os.listdir('properties/' + self.flume_object.component): self.cb_component_type.addItem(f[:f.find(".")]) # self.cb_component_type.addItems('avro thrift'.split()) button_box1 = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel) button_box1.button(QDialogButtonBox.Ok).setDefault(True) layout.addWidget(label) layout.addWidget(self.cb_component_type) layout.addWidget(button_box1) self.setLayout(layout) self.resize(200, 100) button_box1.accepted.connect(self.properties_chosen) button_box1.rejected.connect(self.reject)
def initUI(self): """ Object method Params: None Return: None This method sets the dialog box's layout. The Dialog box conatains two radio buttons and OK/Cancel buttons. sizeHint() sets the box to an ideal size. """ #creating layout settings_layout = QVBoxLayout(); #creating Radio buttons self.nat_order = QRadioButton("Natural order", self); self.alph_order = QRadioButton("Alphabetical", self); #creating the buttons buttons = QDialogButtonBox(); #creating OK button and connecting it to the dialog buttons.addButton(QDialogButtonBox.Ok); buttons.accepted.connect(self.accept) #creating Cancel button and connecting it to the dialog buttons.addButton(QDialogButtonBox.Cancel); buttons.rejected.connect(self.reject) #adding created buttons to the layout settings_layout.addWidget(self.nat_order); settings_layout.addWidget(self.alph_order); settings_layout.addWidget(buttons); #adding layout to dialog self.setLayout(settings_layout); self.sizeHint()
def dialogExtract2csv(self): d = QDialog(self) d.setFixedWidth(450) d.setWindowTitle("Extract data to Csv") d.setVisible(True) vbox = QVBoxLayout() tabWidget = QTabWidget() for name, mod in list(self.moduleDict.items()): wid = QWidget() grid = QGridLayout() grid.setSpacing(20) wid.dateStart = QLineEdit('%s00:00' % dt.datetime.now().strftime("%Y-%m-%dT")) wid.dateEnd = QLineEdit("Now") grid.addWidget(QLabel("From"), 0, 0) grid.addWidget(wid.dateStart, 0, 1) grid.addWidget(QLabel("To"), 0, 2) grid.addWidget(wid.dateEnd, 0, 3) for i, device in enumerate(mod.devices): checkbox = QCheckBox(device.deviceLabel) checkbox.stateChanged.connect(partial(self.csvUpdateTab, name, checkbox, device)) checkbox.setCheckState(2) grid.addWidget(checkbox, 1 + i, 0, 1, 3) wid.setLayout(grid) tabWidget.addTab(wid, name) buttonBox = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel) buttonBox.button(QDialogButtonBox.Ok).clicked.connect(partial(self.extract2csv, tabWidget, d)) buttonBox.button(QDialogButtonBox.Cancel).clicked.connect(d.close) vbox.addWidget(tabWidget) vbox.addWidget(buttonBox) d.setLayout(vbox)
class LayerListDialog(QDialog): def __init__(self, parent): QDialog.__init__(self, parent) # add a button box self.layout = QVBoxLayout() self.layer_list = LayerListWidget(self) self.button_box = QDialogButtonBox(self) self.button_box.setOrientation(Qt.Horizontal) self.button_box.setStandardButtons(QDialogButtonBox.Cancel | QDialogButtonBox.Ok) self.button_box.accepted.connect(self.accept) self.button_box.rejected.connect(self.reject) self.layout.addWidget(self.layer_list) self.layout.addWidget(self.button_box) self.setLayout(self.layout) def set_labeling_model(self, model): self.layer_list.set_model(model) def exec_(self): self.layer_list.update_from_layers() return QDialog.exec_(self) def accept(self): # update layers self.layer_list.update_labeling_from_list() QDialog.accept(self)
def __init__(self, parent): QDialog.__init__(self, parent) self.parent = parent self.setWindowTitle(self.tr('Insert table')) buttonBox = QDialogButtonBox(self) buttonBox.setStandardButtons(QDialogButtonBox.Ok | QDialogButtonBox.Cancel) buttonBox.accepted.connect(self.makeTable) buttonBox.rejected.connect(self.close) layout = QGridLayout(self) rowsLabel = QLabel(self.tr('Number of rows') + ':', self) columnsLabel = QLabel(self.tr('Number of columns') + ':', self) self.rowsSpinBox = QSpinBox(self) self.columnsSpinBox = QSpinBox(self) self.rowsSpinBox.setRange(1, 10) self.columnsSpinBox.setRange(1, 10) self.rowsSpinBox.setValue(3) self.columnsSpinBox.setValue(3) layout.addWidget(rowsLabel, 0, 0) layout.addWidget(self.rowsSpinBox, 0, 1, Qt.AlignRight) layout.addWidget(columnsLabel, 1, 0) layout.addWidget(self.columnsSpinBox, 1, 1, Qt.AlignRight) layout.addWidget(buttonBox, 2, 0, 1, 2)
def __init__(self, opPixelClassification, parent): super( QDialog, self ).__init__(parent=parent) self._op = opPixelClassification classifier_listwidget = QListWidget(parent=self) classifier_listwidget.setSelectionMode( QListWidget.SingleSelection ) classifier_factories = self._get_available_classifier_factories() for name, classifier_factory in list(classifier_factories.items()): item = QListWidgetItem( name ) item.setData( Qt.UserRole, classifier_factory ) classifier_listwidget.addItem(item) buttonbox = QDialogButtonBox( Qt.Horizontal, parent=self ) buttonbox.setStandardButtons( QDialogButtonBox.Ok | QDialogButtonBox.Cancel ) buttonbox.accepted.connect( self.accept ) buttonbox.rejected.connect( self.reject ) layout = QVBoxLayout() layout.addWidget( classifier_listwidget ) layout.addWidget( buttonbox ) self.setLayout(layout) self.setWindowTitle( "Select Classifier Type" ) # Save members self._classifier_listwidget = classifier_listwidget
def show(): dialog = QDialog() dialog.setWindowTitle("Oops!") layout = QVBoxLayout(dialog) label = QLabel(dialog) layout.addWidget(label) label.setText("<p>An uncaught exception has occurred!</p><p>Please use the information below to post a bug report at <a href=\"http://github.com/Ultimaker/Cura/issues\">http://github.com/Ultimaker/Cura/issues</a></p>") textarea = QTextEdit(dialog) layout.addWidget(textarea) try: from UM.Application import Application version = Application.getInstance().getVersion() except: version = "Unknown" trace = "".join(traceback.format_exception(sys.exc_info()[0], sys.exc_info()[1], sys.exc_info()[2])) crash_info = "Version: {0}\nPlatform: {1}\nQt: {2}\nPyQt: {3}\n\nException:\n{4}" crash_info = crash_info.format(version, platform.platform(), QT_VERSION_STR, PYQT_VERSION_STR, trace) textarea.setText(crash_info) buttons = QDialogButtonBox(QDialogButtonBox.Close, dialog) layout.addWidget(buttons) buttons.addButton("Open Web Page", QDialogButtonBox.HelpRole) buttons.rejected.connect(lambda: dialog.close()) buttons.helpRequested.connect(lambda: webbrowser.open("http://github.com/Ultimaker/Cura/issues")) dialog.exec_()
def __init__(self, tableName, parent=None): super(TableEditor, self).__init__(parent) self.model = QSqlTableModel(self) self.model.setTable(tableName) self.model.setEditStrategy(QSqlTableModel.OnManualSubmit) self.model.select() self.model.setHeaderData(0, Qt.Horizontal, "ID") self.model.setHeaderData(1, Qt.Horizontal, "First name") self.model.setHeaderData(2, Qt.Horizontal, "Last name") view = QTableView() view.setModel(self.model) submitButton = QPushButton("Submit") submitButton.setDefault(True) revertButton = QPushButton("&Revert") quitButton = QPushButton("Quit") buttonBox = QDialogButtonBox(Qt.Vertical) buttonBox.addButton(submitButton, QDialogButtonBox.ActionRole) buttonBox.addButton(revertButton, QDialogButtonBox.ActionRole) buttonBox.addButton(quitButton, QDialogButtonBox.RejectRole) submitButton.clicked.connect(self.submit) revertButton.clicked.connect(self.model.revertAll) quitButton.clicked.connect(self.close) mainLayout = QHBoxLayout() mainLayout.addWidget(view) mainLayout.addWidget(buttonBox) self.setLayout(mainLayout) self.setWindowTitle("Cached Table")
class DialogChangelog(QtWidgets.QDialog): def __init__(self, Dialog, Wizard, parent=None): super(DialogChangelog, self).__init__(parent) # Reference to wizard self.wizard = Wizard # Setting dialog's size self.setMinimumSize(QtCore.QSize(350, 500)) self.setMaximumSize(QtCore.QSize(850, 650)) # Labels and QLineEdits for input nameLabel = QLabel("Name") emailLabel = QLabel("Email") dateLabel = QLabel("Pick a date") messageLabel = QLabel("Message") self.nameEdit = QLineEdit() self.emailEdit = QLineEdit() self.messageEdit = QPlainTextEdit() self.datePicker = QCalendarWidget() # Button box with "OK" and "Cancel buttons" self.okButton = QPushButton("OK") self.cancelButton = QPushButton("Cancel") self.boxButtons = QDialogButtonBox(parent=Wizard) self.boxButtons.addButton(self.okButton, 0) self.boxButtons.addButton(self.cancelButton, 1) self.boxButtons.accepted.connect(self.acceptIt) self.boxButtons.rejected.connect(self.reject) # Import button self.importCvsButton = QPushButton("Import from CVS") self.importCvsButton.clicked.connect(self.importFromCVS) # Setting layout mainLayout = QVBoxLayout() upperLayout = QHBoxLayout() upperLayout.addWidget(nameLabel) upperLayout.addWidget(self.importCvsButton) mainLayout.addLayout(upperLayout) mainLayout.addWidget(self.nameEdit) mainLayout.addWidget(emailLabel) mainLayout.addWidget(self.emailEdit) mainLayout.addWidget(dateLabel) mainLayout.addWidget(self.datePicker) mainLayout.addWidget(messageLabel) mainLayout.addWidget(self.messageEdit) mainLayout.addWidget(self.boxButtons) self.setLayout(mainLayout) def acceptIt(self): ''' If user clicked "OK" button ''' self.accept() def importFromCVS(self): ''' If user clicked "Import from CVS" button ''' pass
def __init__(self, channel_names, feature_names, default_selections=None, parent=None): """ Parameters ---------- channel_names *list of str* The user will be shown a separate checklist of feature options for each channel. feature_names *list of str* Feature names, exactly as expected by :py:meth:`~ilastikrag.rag.Rag.compute_features()`. The features will be grouped by category and shown in duplicate checklist widgets for each channel. default_selections *dict, str: list-of-str* Mapping from channel_name -> feature_names, indicating which features should be selected by default for each channel. parent *QWidget* """ super(FeatureSelectionDialog, self).__init__(parent) self.setWindowTitle("Select Edge Features") self.tree_widgets = {} self.checklist_widgets = OrderedDict() boxes_layout = QHBoxLayout() for channel_name in channel_names: default_checked = [] if default_selections and channel_name in default_selections: default_checked = default_selections[channel_name] checklist = _make_checklist(feature_names, default_checked) checklist.name = channel_name checklist_widget = HierarchicalChecklistView( checklist, parent=self ) self.checklist_widgets[channel_name] = checklist_widget boxes_layout.addWidget(checklist_widget) buttonbox = QDialogButtonBox( Qt.Horizontal, parent=self ) buttonbox.setStandardButtons( QDialogButtonBox.Ok | QDialogButtonBox.Cancel ) buttonbox.accepted.connect( self.accept ) buttonbox.rejected.connect( self.reject ) widget_layout = QVBoxLayout() # FIXME: Would like to hold the TreeWidgets in a QScrollArea, # but they don't seem to respect fixed size policies, # so the scroll area never shows a scrollbar... #scrollarea = QScrollArea() #scrollarea.setLayout(boxes_layout) #widget_layout.addWidget(scrollarea) widget_layout.addLayout(boxes_layout) widget_layout.addWidget(buttonbox) self.setLayout(widget_layout) total_spacing = self.width() - (len(channel_names)*checklist_widget.width()) total_width = total_spacing + len(channel_names) * ( 20 + checklist_widget.columnWidth(0) ) self.resize(total_width, 500)
def _buttonsWidget(self): buttons = QDialogButtonBox() buttons.addButton(QDialogButtonBox.Close) buttons.addButton(catalog.i18nc("@action:button", "Send report"), QDialogButtonBox.AcceptRole) buttons.rejected.connect(self.dialog.close) buttons.accepted.connect(self._sendCrashReport) return buttons
class DialogStudentId(QDialog): """Dialog to change the student id. Example (replace `parent` by the parent widget): dialog = DialogStudentId(parent) id = dialog.exec_() """ def __init__(self, parent, ranked_students, student_listings): super().__init__(parent) self.student_listings = student_listings self.setWindowTitle(_('Change the student id')) layout = QFormLayout() self.setLayout(layout) self.combo = widgets.StudentComboBox(parent=self) self.combo.add_students(ranked_students) self.combo.editTextChanged.connect(self._check_value) self.combo.currentIndexChanged.connect(self._check_value) new_student_button = QPushButton( \ QIcon(utils.resource_path('new_id.svg')), _('New student'), parent=self) new_student_button.clicked.connect(self._new_student) self.buttons = QDialogButtonBox((QDialogButtonBox.Ok | QDialogButtonBox.Cancel)) self.buttons.addButton(new_student_button, QDialogButtonBox.ActionRole) self.buttons.accepted.connect(self.accept) self.buttons.rejected.connect(self.reject) layout.addRow(_('Student id:'), self.combo) layout.addRow(self.buttons) def exec_(self): """Shows the dialog and waits until it is closed. Returns a student object with the option selected by the user. The return value is None if the user cancels the dialog. """ result = super().exec_() if result == QDialog.Accepted: return self.combo.current_student() else: return None def _new_student(self): dialog = NewStudentDialog(self.student_listings, parent=self) student = dialog.exec_() if student is not None: self.combo.add_student(student, set_current=True) self.buttons.button(QDialogButtonBox.Ok).setFocus() self.buttons.button(QDialogButtonBox.Ok).setEnabled(True) def _check_value(self, param): if self.combo.current_student() is not None: self.buttons.button(QDialogButtonBox.Ok).setEnabled(True) else: self.buttons.button(QDialogButtonBox.Ok).setEnabled(False)
class LoginDialog(QDialog): """虾米音乐登录对话框""" login_success = pyqtSignal([object]) def __init__(self, parent=None): super().__init__(parent) self._label = QLabel(self) self.username_input = QLineEdit(self) self.pw_input = QLineEdit(self) self.pw_input.setEchoMode(QLineEdit.Password) self._btn_box = QDialogButtonBox(self) self._ok_btn = QDialogButtonBox.Ok self._setup_ui() self.setWindowTitle('虾米账号密码登录') self._btn_box.clicked.connect(self.do_verify) def _setup_ui(self): self._btn_box.addButton(self._ok_btn) self._label.hide() self._layout = QFormLayout(self) self._layout.addRow('邮箱/手机号:', self.username_input) self._layout.addRow('密码:', self.pw_input) self._layout.addRow(self._label) self._layout.addRow(self._btn_box) def show_msg(self, msg, error=False): """显示提示信息""" self._label.show() self._label.setTextFormat(Qt.RichText) if error: color = 'red' else: color = 'green' self._label.setText('<span style="color: {};">{}</span>' .format(color, msg)) def do_verify(self): """校验用户名和密码,成功则发送信号""" username = self.username_input.text() password = self.pw_input.text() pw_md5digest = hashlib.md5(password.encode('utf-8')).hexdigest() rv = api.login(username, pw_md5digest) code, msg = rv['ret'][0].split('::') is_success = code == 'SUCCESS' self.show_msg(msg, error=(not is_success)) if is_success: data = rv['data']['data'] schema = UserSchema(strict=True) user, _ = schema.load(data) self.login_success.emit(user) self.close()
def __init__(self, parent=None): super(BlockingClient, self).__init__(parent) self.thread = FortuneThread() self.currentFortune = '' hostLabel = QLabel("&Server name:") portLabel = QLabel("S&erver port:") for ipAddress in QNetworkInterface.allAddresses(): if ipAddress != QHostAddress.LocalHost and ipAddress.toIPv4Address() != 0: break else: ipAddress = QHostAddress(QHostAddress.LocalHost) ipAddress = ipAddress.toString() self.hostLineEdit = QLineEdit(ipAddress) self.portLineEdit = QLineEdit() self.portLineEdit.setValidator(QIntValidator(1, 65535, self)) hostLabel.setBuddy(self.hostLineEdit) portLabel.setBuddy(self.portLineEdit) self.statusLabel = QLabel( "This example requires that you run the Fortune Server example as well.") self.statusLabel.setWordWrap(True) self.getFortuneButton = QPushButton("Get Fortune") self.getFortuneButton.setDefault(True) self.getFortuneButton.setEnabled(False) quitButton = QPushButton("Quit") buttonBox = QDialogButtonBox() buttonBox.addButton(self.getFortuneButton, QDialogButtonBox.ActionRole) buttonBox.addButton(quitButton, QDialogButtonBox.RejectRole) self.getFortuneButton.clicked.connect(self.requestNewFortune) quitButton.clicked.connect(self.close) self.hostLineEdit.textChanged.connect(self.enableGetFortuneButton) self.portLineEdit.textChanged.connect(self.enableGetFortuneButton) self.thread.newFortune.connect(self.showFortune) self.thread.error.connect(self.displayError) mainLayout = QGridLayout() mainLayout.addWidget(hostLabel, 0, 0) mainLayout.addWidget(self.hostLineEdit, 0, 1) mainLayout.addWidget(portLabel, 1, 0) mainLayout.addWidget(self.portLineEdit, 1, 1) mainLayout.addWidget(self.statusLabel, 2, 0, 1, 2) mainLayout.addWidget(buttonBox, 3, 0, 1, 2) self.setLayout(mainLayout) self.setWindowTitle("Blocking Fortune Client") self.portLineEdit.setFocus()
def __init__(self, parent=None): super(FindDialog, self).__init__(parent) label = QLabel("Find &what:") lineEdit = QLineEdit() label.setBuddy(lineEdit) caseCheckBox = QCheckBox("Match &case") fromStartCheckBox = QCheckBox("Search from &start") fromStartCheckBox.setChecked(True) findButton = QPushButton("&Find") findButton.setDefault(True) moreButton = QPushButton("&More") moreButton.setCheckable(True) moreButton.setAutoDefault(False) extension = QWidget() wholeWordsCheckBox = QCheckBox("&Whole words") backwardCheckBox = QCheckBox("Search &backward") searchSelectionCheckBox = QCheckBox("Search se&lection") buttonBox = QDialogButtonBox(Qt.Vertical) buttonBox.addButton(findButton, QDialogButtonBox.ActionRole) buttonBox.addButton(moreButton, QDialogButtonBox.ActionRole) moreButton.toggled.connect(extension.setVisible) extensionLayout = QVBoxLayout() extensionLayout.setContentsMargins(0, 0, 0, 0) extensionLayout.addWidget(wholeWordsCheckBox) extensionLayout.addWidget(backwardCheckBox) extensionLayout.addWidget(searchSelectionCheckBox) extension.setLayout(extensionLayout) topLeftLayout = QHBoxLayout() topLeftLayout.addWidget(label) topLeftLayout.addWidget(lineEdit) leftLayout = QVBoxLayout() leftLayout.addLayout(topLeftLayout) leftLayout.addWidget(caseCheckBox) leftLayout.addWidget(fromStartCheckBox) mainLayout = QGridLayout() mainLayout.setSizeConstraint(QLayout.SetFixedSize) mainLayout.addLayout(leftLayout, 0, 0) mainLayout.addWidget(buttonBox, 0, 1) mainLayout.addWidget(extension, 1, 0, 1, 2) mainLayout.setRowStretch(2, 1) self.setLayout(mainLayout) self.setWindowTitle("Extension") extension.hide()
def __init__(self, parent=None): super(ToolOffsetDialog, self).__init__(parent) self._color = QColor(0, 0, 0, 150) self._state = False self.setWindowModality(Qt.ApplicationModal) self.setWindowFlags(self.windowFlags() | Qt.Tool | Qt.Dialog | Qt.WindowStaysOnTopHint | Qt.WindowSystemMenuHint) self.setMinimumSize(200, 200) buttonBox = QDialogButtonBox() buttonBox.setEnabled(False) STATUS.connect('not-all-homed', lambda w, axis: buttonBox.setEnabled(False)) STATUS.connect('all-homed', lambda w: buttonBox.setEnabled(True)) STATUS.connect('state-estop', lambda w: buttonBox.setEnabled(False)) STATUS.connect('state-estop-reset', lambda w: buttonBox.setEnabled(STATUS.machine_is_on() and STATUS.is_all_homed())) for i in('X', 'Y', 'Z'): b = 'button_%s' % i self[b] = QPushButton('Zero %s' % i) self[b].clicked.connect(self.zeroPress('%s' % i)) buttonBox.addButton(self[b], 3) v = QVBoxLayout() h = QHBoxLayout() self._o = TOOLVIEW_WIDGET() self._o._hal_init() self.setLayout(v) v.addWidget(self._o) b = QPushButton('OK') b.clicked.connect(lambda: self.close()) h.addWidget(b) h.addWidget(buttonBox) v.addLayout(h) self.setModal(True)
def __init__(self, parent): QDialog.__init__(self, parent) self.parent = parent self.initConfigOptions() self.layout = QGridLayout(self) buttonBox = QDialogButtonBox(self) buttonBox.setStandardButtons(QDialogButtonBox.Ok | QDialogButtonBox.Cancel) buttonBox.accepted.connect(self.saveSettings) buttonBox.rejected.connect(self.close) self.initWidgets() self.layout.addWidget(buttonBox, len(self.options), 0, 1, 2)
def _buttonsWidget(self): buttons = QDialogButtonBox() buttons.addButton(QDialogButtonBox.Close) # Like above, this will be served as a separate detailed report dialog if the application has not yet been # fully loaded. In this case, "send report" will be a check box in the early crash dialog, so there is no # need for this extra button. if self.has_started: buttons.addButton(catalog.i18nc("@action:button", "Send report"), QDialogButtonBox.AcceptRole) buttons.accepted.connect(self._sendCrashReport) buttons.rejected.connect(self.dialog.close) return buttons
def __init__(self, format, parent=None): super(NumberFormatDlg, self).__init__(parent) self.setAttribute(Qt.WA_DeleteOnClose) punctuationRe = QRegExp(r"[ ,;:.]") thousandsLabel = QLabel("&Thousands separator") self.thousandsEdit = QLineEdit(format["thousandsseparator"]) thousandsLabel.setBuddy(self.thousandsEdit) self.thousandsEdit.setMaxLength(1) self.thousandsEdit.setValidator( QRegExpValidator(punctuationRe, self)) decimalMarkerLabel = QLabel("Decimal &marker") self.decimalMarkerEdit = QLineEdit(format["decimalmarker"]) decimalMarkerLabel.setBuddy(self.decimalMarkerEdit) self.decimalMarkerEdit.setMaxLength(1) self.decimalMarkerEdit.setValidator( QRegExpValidator(punctuationRe, self)) self.decimalMarkerEdit.setInputMask("X") decimalPlacesLabel = QLabel("&Decimal places") self.decimalPlacesSpinBox = QSpinBox() decimalPlacesLabel.setBuddy(self.decimalPlacesSpinBox) self.decimalPlacesSpinBox.setRange(0, 6) self.decimalPlacesSpinBox.setValue(format["decimalplaces"]) self.redNegativesCheckBox = QCheckBox("&Red negative numbers") self.redNegativesCheckBox.setChecked(format["rednegatives"]) buttonBox = QDialogButtonBox(QDialogButtonBox.Apply| QDialogButtonBox.Close) self.format = format grid = QGridLayout() grid.addWidget(thousandsLabel, 0, 0) grid.addWidget(self.thousandsEdit, 0, 1) grid.addWidget(decimalMarkerLabel, 1, 0) grid.addWidget(self.decimalMarkerEdit, 1, 1) grid.addWidget(decimalPlacesLabel, 2, 0) grid.addWidget(self.decimalPlacesSpinBox, 2, 1) grid.addWidget(self.redNegativesCheckBox, 3, 0, 1, 2) grid.addWidget(buttonBox, 4, 0, 1, 2) self.setLayout(grid) buttonBox.button(QDialogButtonBox.Apply).clicked.connect(self.apply) buttonBox.rejected.connect(self.reject) # self.connect(buttonBox.button(QDialogButtonBox.Apply), # SIGNAL("clicked()"), self.apply) # self.connect(buttonBox, SIGNAL("rejected()"), # self, SLOT("reject()")) self.setWindowTitle("Set Number Format (Modeless)")
def __init__(self, parent=None): super(NewProjectManager, self).__init__(parent, Qt.Dialog) self.setWindowTitle(translations.TR_NEW_PROJECT) self.setMinimumHeight(500) vbox = QVBoxLayout(self) vbox.addWidget(QLabel(translations.TR_CHOOSE_TEMPLATE)) vbox.addWidget(QLabel(translations.TR_TAB_PROJECTS)) hbox = QHBoxLayout() self.list_projects = QListWidget() self.list_projects.setProperty("wizard", True) hbox.addWidget(self.list_projects) self.list_templates = QListWidget() self.list_templates.setProperty("wizard", True) hbox.addWidget(self.list_templates) self.text_info = QTextBrowser() self.text_info.setProperty("wizard", True) hbox.addWidget(self.text_info) vbox.addLayout(hbox) button_box = QDialogButtonBox( QDialogButtonBox.Cancel | QDialogButtonBox.Ok) choose_button = button_box.button(QDialogButtonBox.Ok) choose_button.setText(translations.TR_CHOOSE) # hbox2 = QHBoxLayout() # cancel = QPushButton(translations.TR_CANCEL) # choose = QPushButton(translations.TR_CHOOSE) # hbox2.addSpacerItem(QSpacerItem(1, 0, QSizePolicy.Expanding, # QSizePolicy.Fixed)) # hbox2.addWidget(cancel) # hbox2.addWidget(choose) # vbox.addLayout(button_box) vbox.addWidget(button_box) self.template_registry = IDE.get_service("template_registry") categories = self.template_registry.list_project_categories() for category in categories: self.list_projects.addItem(category) button_box.accepted.connect(self.accept) button_box.rejected.connect(self.reject) # cancel.clicked.connect(self.close) # choose.clicked.connect(self._start_wizard) self.list_projects.itemSelectionChanged.connect( self._project_selected) self.list_templates.itemSelectionChanged.connect( self._template_selected) self.list_projects.setCurrentRow(0)
class CueSettings(QDialog): on_apply = QtCore.pyqtSignal(dict) def __init__(self, widgets=[], cue=None, check=False, **kwargs): super().__init__(**kwargs) conf = {} if(cue is not None): conf = deepcopy(cue.properties()) self.setWindowTitle(conf['name']) self.setWindowModality(QtCore.Qt.ApplicationModal) self.setMaximumSize(635, 530) self.setMinimumSize(635, 530) self.resize(635, 530) self.sections = QTabWidget(self) self.sections.setGeometry(QtCore.QRect(5, 10, 625, 470)) wsize = QtCore.QSize(625, 470 - self.sections.tabBar().height()) for widget in widgets: widget = widget(wsize, cue) widget.set_configuration(conf) widget.enable_check(check) self.sections.addTab(widget, widget.Name) self.dialogButtons = QDialogButtonBox(self) self.dialogButtons.setGeometry(10, 490, 615, 30) self.dialogButtons.setStandardButtons(QDialogButtonBox.Cancel | QDialogButtonBox.Ok | QDialogButtonBox.Apply) self.dialogButtons.rejected.connect(self.reject) self.dialogButtons.accepted.connect(self.accept) apply = self.dialogButtons.button(QDialogButtonBox.Apply) apply.clicked.connect(self.apply) def accept(self): self.apply() super().accept() def apply(self): new_conf = {} for n in range(self.sections.count()): deep_update(new_conf, self.sections.widget(n).get_configuration()) self.on_apply.emit(new_conf)
def show(exception_type, value, tb): debug_mode = False if QCoreApplication.instance(): debug_mode = QCoreApplication.instance().getCommandLineOption("debug-mode", False) Logger.log("c", "An uncaught exception has occurred!") for line in traceback.format_exception(exception_type, value, tb): for part in line.rstrip("\n").split("\n"): Logger.log("c", part) if not debug_mode and exception_type not in fatal_exception_types: return application = QCoreApplication.instance() if not application: sys.exit(1) dialog = QDialog() dialog.setWindowTitle(catalog.i18nc("@title:window", "Oops!")) layout = QVBoxLayout(dialog) label = QLabel(dialog) layout.addWidget(label) label.setText(catalog.i18nc("@label", "<p>A fatal exception has occurred that we could not recover from!</p><p>Please use the information below to post a bug report at <a href=\"http://github.com/Ultimaker/Cura/issues\">http://github.com/Ultimaker/Cura/issues</a></p>")) textarea = QTextEdit(dialog) layout.addWidget(textarea) try: from UM.Application import Application version = Application.getInstance().getVersion() except: version = "Unknown" trace = "".join(traceback.format_exception(exception_type, value, tb)) crash_info = "Version: {0}\nPlatform: {1}\nQt: {2}\nPyQt: {3}\n\nException:\n{4}" crash_info = crash_info.format(version, platform.platform(), QT_VERSION_STR, PYQT_VERSION_STR, trace) textarea.setText(crash_info) buttons = QDialogButtonBox(QDialogButtonBox.Close, dialog) layout.addWidget(buttons) buttons.addButton(catalog.i18nc("@action:button", "Open Web Page"), QDialogButtonBox.HelpRole) buttons.rejected.connect(dialog.close) buttons.helpRequested.connect(lambda: webbrowser.open("http://github.com/Ultimaker/Cura/issues")) dialog.exec_() sys.exit(1)
def __init__(self, parent=None): QDialog.__init__(self, parent) self.resize(700, 600) verticalLayout = QVBoxLayout(self) self.textEdit = QTextEdit(self) self.textEdit.setReadOnly(True) self.textEdit.setFont(globalSettings.editorFont) self.hl = ReTextHighlighter(self.textEdit.document()) self.hl.docType = 'html' verticalLayout.addWidget(self.textEdit) buttonBox = QDialogButtonBox(self) buttonBox.setStandardButtons(QDialogButtonBox.Close) buttonBox.rejected.connect(self.close) verticalLayout.addWidget(buttonBox)
def __init__(self, text): super(ShowTransactionDetails, self).__init__() text_edit = QTextEdit() text_edit.setText("<b>Response</b>: %s" % text) self.setWindowTitle("Details") button_box = QDialogButtonBox() button_box.addButton("Close", QDialogButtonBox.AcceptRole) layout = QVBoxLayout() layout.addWidget(text_edit) layout.addWidget(button_box) self.setMinimumHeight(180) self.setLayout(layout) button_box.clicked.connect(self.close) text_edit.setReadOnly(True)
class Preferences(QDialog): """Represents the dialog containg the application settings :param parent: Parent widget, defaults to None :type parent: QWidget, optional """ def __init__(self, parent=None): super().__init__(parent) self.setWindowTitle("Preferences") self.prefs = QSettings() self.cpu_port = None self.gpu_port = None self.actions = QDialogButtonBox( QDialogButtonBox.Ok | QDialogButtonBox.Apply | QDialogButtonBox.Cancel ) self.actions.clicked.connect(self.handlePrefsBtns) settings_form = QFormLayout() com_ports = [ port.__dict__["device"] for port in list(list_ports.comports()) ] self.cpu_port_combo_box = QComboBox() self.cpu_port_combo_box.addItems(com_ports) self.gpu_port_combo_box = QComboBox() self.gpu_port_combo_box.addItems(com_ports) self.prefs.beginGroup("ports") if self.prefs.contains("cpu_port"): self.cpu_port = self.prefs.value("cpu_port") self.cpu_port_combo_box.setCurrentText(self.cpu_port) if self.prefs.contains("gpu_port"): self.gpu_port = self.prefs.value("gpu_port") self.gpu_port_combo_box.setCurrentText(self.gpu_port) self.prefs.endGroup() self.cpu_port_combo_box.currentTextChanged.connect(self.setCpuPort) self.gpu_port_combo_box.currentTextChanged.connect(self.setGpuPort) auto_ident = QPushButton("Auto-Identify CPU/GPU") auto_ident.clicked.connect(self.idUcs) settings_form.addRow(QLabel("Propeller Ports")) settings_form.addRow("CPU Port:", self.cpu_port_combo_box) settings_form.addRow("GPU Port:", self.gpu_port_combo_box) settings_form.addRow(auto_ident) settings_form.addWidget(self.actions) self.setLayout(settings_form) def idUcs(self): """Executes the serial routines necessary to identify which COM ports the GPU and CPU are on """ new_cpu_port = None new_gpu_port = None for port in list(list_ports.comports()): result = subprocess.getoutput( [ "propellent.exe", "/id", "/port", port.__dict__["device"], "/gui", "off", ] ) prop_ports = re.search( r"Propeller chip version 1 found on (COM[0-9]+)", result ) if prop_ports: port = prop_ports.group(1) ser = serial_for_url(port, 19200, timeout=0, do_not_open=True) ser.open() response = None start = time.time() timeout = 5 while not response and time.time() < start + timeout: ser.write(b"\x59") response = ser.read(3) ser.close() if response == b"CPU": new_cpu_port = port elif response == b"GPU": new_gpu_port = port if not new_cpu_port or not new_gpu_port: # Error dialog return self.setCpuPort(new_cpu_port) self.setGpuPort(new_gpu_port) self.cpu_port_combo_box.setCurrentText(self.cpu_port) self.gpu_port_combo_box.setCurrentText(self.gpu_port) def setCpuPort(self, port): """Sets the GPU COM port in preferences :param port: COM port hosting the CPU :type port: str """ self.cpu_port = port def setGpuPort(self, port): """Sets the GPU COM port in preferences :param port: COM port hosting the GPU :type port: str """ self.gpu_port = port def handlePrefsBtns(self, button): """Handles Ok/Apply/Cancel preferences buttons :param button: Button which triggered the actions :type button: QPushButton """ if button is self.actions.button(QDialogButtonBox.Cancel): self.reject() self.prefs.beginGroup("ports") self.prefs.setValue("cpu_port", self.cpu_port) self.prefs.setValue("gpu_port", self.gpu_port) self.prefs.endGroup() if button is self.actions.button(QDialogButtonBox.Ok): self.accept()
class SurveyWindow(QFrame): def __init__(self): if version_info[0] == 3: super().__init__() else: super(SurveyWindow, self).__init__() # Establish basic window shape self.setWindowTitle('Survey') self.setStyleSheet('background-color: rgb(255,180,188);') self.output = "" self.layout = QVBoxLayout() self.setLayout(self.layout) # Alteration on BRCA1 in1label = QLabel() in1label.setText('Do you have an inherited alteration on the BRCA1 ' 'gene?') self.inherit1ComboBox = QComboBox() self.inherit1ComboBox.setStyleSheet('background-color: white;') self.inherit1ComboBox.addItems(['', 'Yes', 'No', 'I don\'t know']) brca1layout = QHBoxLayout() brca1layout.addWidget(in1label) brca1layout.addWidget(self.inherit1ComboBox) self.layout.addLayout(brca1layout) # self.layout.addSpace(15) # Alteration on BRCA2 in2label = QLabel() in2label.setText('Do you have an inherited alteration on the BRCA2 ' 'gene?') self.inherit2ComboBox = QComboBox() self.inherit2ComboBox.setStyleSheet('background-color: white;') self.inherit2ComboBox.addItems(['', 'Yes', 'No', 'I don\'t know']) brca2layout = QHBoxLayout() brca2layout.addWidget(in2label) brca2layout.addWidget(self.inherit2ComboBox) self.layout.addLayout(brca2layout) # Ethnicity ethlabel = QLabel() ethlabel.setText('What is your ethnicity?') self.ethComboBox = QComboBox() self.ethComboBox.setStyleSheet('background-color: white;') self.ethComboBox.addItems([ '', 'White', 'Hispanic', 'Asian/Pacific Islander', 'Black', 'Other' ]) ethlayout = QHBoxLayout() ethlayout.addWidget(ethlabel) ethlayout.addWidget(self.ethComboBox) self.layout.addLayout(ethlayout) # Age agelabel = QLabel() agelabel.setText('What range best represents your age?') self.ageComboBox = QComboBox() self.ageComboBox.setStyleSheet('background-color: white;') self.ageComboBox.addItems([ '', '18 or younger', '19-29', '30-39', '40-50', '51-60', '61-70', '70+' ]) agelayout = QHBoxLayout() agelayout.addWidget(agelabel) agelayout.addWidget(self.ageComboBox) self.layout.addLayout(agelayout) # Menstruation menslabel = QLabel() menslabel.setText('Did you start menstruation before 12 years old?') self.mensComboBox = QComboBox() self.mensComboBox.setStyleSheet('background-color: white;') self.mensComboBox.addItems(['', 'Yes', 'No', 'Does not apply to me']) menslayout = QHBoxLayout() menslayout.addWidget(menslabel) menslayout.addWidget(self.mensComboBox) self.layout.addLayout(menslayout) # Menopause menolabel = QLabel() menolabel.setText('Did you begin menopause after age 55?') self.menoComboBox = QComboBox() self.menoComboBox.setStyleSheet('background-color: white;') self.menoComboBox.addItems(['', 'Yes', 'No', 'Does not apply to me']) menolayout = QHBoxLayout() menolayout.addWidget(menolabel) menolayout.addWidget(self.menoComboBox) self.layout.addLayout(menolayout) # HRT chrtlabel = QLabel() chrtlabel.setText('Have you taken combination hormone replacement ' 'therapy, even for a short time?') self.chrtComboBox = QComboBox() self.chrtComboBox.setStyleSheet('background-color: white;') self.chrtComboBox.addItems(['', 'Yes', 'No']) chrtlayout = QHBoxLayout() chrtlayout.addWidget(chrtlabel) chrtlayout.addWidget(self.chrtComboBox) self.layout.addLayout(chrtlayout) # EHRT ehrtlabel = QLabel() ehrtlabel.setText('Have you taken estrogen hormone replacement therapy' ' for 10 or more years?') self.ehrtComboBox = QComboBox() self.ehrtComboBox.setStyleSheet('background-color: white;') self.ehrtComboBox.addItems(['', 'Yes', 'No']) ehrtlayout = QHBoxLayout() ehrtlayout.addWidget(ehrtlabel) ehrtlayout.addWidget(self.ehrtComboBox) self.layout.addLayout(ehrtlayout) # des deslabel = QLabel() deslabel.setText('Have you taken diethylstillbestrol (DES)?') self.desComboBox = QComboBox() self.desComboBox.setStyleSheet('background-color: white;') self.desComboBox.addItems(['', 'Yes', 'No', 'I don\'t know']) deslayout = QHBoxLayout() deslayout.addWidget(deslabel) deslayout.addWidget(self.desComboBox) self.layout.addLayout(deslayout) # mothers des mdeslabel = QLabel() mdeslabel.setText('Has your mother taken diethylstillbestrol (DES) ' 'between 1940-1971?') self.mdesComboBox = QComboBox() self.mdesComboBox.setStyleSheet('background-color: white;') self.mdesComboBox.addItems(['', 'Yes', 'No', 'I don\'t know']) mdeslayout = QHBoxLayout() mdeslayout.addWidget(mdeslabel) mdeslayout.addWidget(self.mdesComboBox) self.layout.addLayout(mdeslayout) # dense tissue pretlabel = QLabel() pretlabel.setText('Do you have dense breast tissue, and at what age?') self.pretComboBox = QComboBox() self.pretComboBox.setStyleSheet('background-color: white;') self.pretComboBox.addItems( ['', 'Premenopausal', 'Postmenopausal', 'No', 'I don\'t know']) pretlayout = QHBoxLayout() pretlayout.addWidget(pretlabel) pretlayout.addWidget(self.pretComboBox) self.layout.addLayout(pretlayout) # Children chilabel = QLabel() chilabel.setText('When did you give birth to your first child?') self.chiComboBox = QComboBox() self.chiComboBox.setStyleSheet('background-color: white;') self.chiComboBox.addItems( ['', 'before 20', '21-34', 'After 35', 'Never had children']) chilayout = QHBoxLayout() chilayout.addWidget(chilabel) chilayout.addWidget(self.chiComboBox) self.layout.addLayout(chilayout) canlabel = QLabel() canlabel.setText( 'How many of your close relatives have had breast, ovarian, ' 'or prostate cancer?') self.canComboBox = QComboBox() self.canComboBox.setStyleSheet('background-color: white;') self.canComboBox.addItems(['', '0', '1', '2', '3', '4 or more']) canlayout = QHBoxLayout() canlayout.addWidget(canlabel) canlayout.addWidget(self.canComboBox) self.layout.addLayout(canlayout) # End self.buttonBox = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel) self.buttonBox.setStyleSheet('background-color: white;') self.buttonBox.accepted.connect(self.submit_it) self.buttonBox.rejected.connect(self.reject) self.layout.addWidget(self.buttonBox) def setFlag(self, s): self.output += '- ' + s + '\n' def submit_it(self): r = 0 if (self.inherit1ComboBox.currentText() == 'Yes'): self.setFlag('An inherited alteration on BRCA1 makes risk of ' 'development' ' 72% by age 80.') r += 120 if (self.inherit2ComboBox.currentText() == 'Yes'): self.setFlag('An inherited alteration on BRCA2 makes risk of ' 'development 69% by age 80.') r += 110 if (self.ethComboBox.currentText() == 'White'): self.setFlag('12.2 per 100,000 white women have ovarian cancer.') r += 15 if (self.ethComboBox.currentText() == 'Hispanic'): self.setFlag('10.6 per 100,000 hispanic women have ovarian ' 'cancer.') r += 12 if (self.ethComboBox.currentText() == 'Asian/Pacific Islander'): self.setFlag('9.5 per 100,000 Asian/Pacific Islander women have ' 'ovarian cancer.') r += 10 if (self.ethComboBox.currentText() == 'Black'): self.setFlag('9.4 per 100,000 black women have ovarian cancer.') r += 9.5 if (self.ageComboBox.currentText() == '40-50'): self.setFlag('1 in 68 women have a risk of developing breast ' 'cancer between the ages of 40 to 50.') r += 40 elif (self.ageComboBox.currentText() == '51-60'): self.setFlag( '1 in 42 women have a risk of developing breast cancer ' 'between the ages of 50 to 60.') r += 50 elif (self.ageComboBox.currentText() == '61-70'): self.setFlag( '1 in 28 women have a risk of developing breast cancer ' 'between the ages of 60 to 70.') r += 60 elif (self.ageComboBox.currentText() == '70+'): self.setFlag( '1 in 26 women have a risk of developing breast cancer ' 'at 70+ years old.') r += 63 if (self.mensComboBox.currentText() == 'Yes'): self.setFlag('Longer or higher exposure to reproductive hormones, ' 'like estrogen and progesterone, increase risk of ' 'cancer. 80% of all breast cancers grow according' ' to estrogen supply.') r += 30 if (self.menoComboBox.currentText() == 'Yes'): self.setFlag('Longer or higher exposure to reproductive hormones, ' 'like estrogen and progesterone, increase risk of ' 'cancer. 80% of all breast cancers grow according' ' to estrogen supply.') r += 30 if (self.chrtComboBox.currentText() == 'Yes'): self.setFlag( 'Combination Hormone Replacement Therapy will increase' ' the risk of breast cancer by 75% even if it was only' ' used for a short time.') r += 90 if (self.ehrtComboBox.currentText() == 'Yes'): self.setFlag( 'Estrogen-only combination hormone replacement therapy' ' increases risk of breast cancer if used for 10 or more' ' years.') r += 15 if (self.desComboBox.currentText() == 'Yes'): self.setFlag( 'Taking DES gives you a 20-30% increased chance of getting' ' breast cancer.') r += 45 if (self.mdesComboBox.currentText() == 'Yes'): self.setFlag('Your mother taking DES gives you a 20-30% increased ' 'chance of getting breast cancer.') r += 40 if (self.pretComboBox.currentText() == 'Premenopausal'): self.setFlag( 'Dense breast tissue is a huge risk factor for breast ' 'cancer in 39% of premenopausal women.') r += 45 elif (self.pretComboBox.currentText() == 'Postmenopausal'): self.setFlag( 'Dense breast tissue is a huge risk factor for breast ' 'cancer in 26% of postmenopausal women.') r += 40 if (self.chiComboBox.currentText() == 'After 35'): self.setFlag( 'Women who have their first child after 35 are 40% more' ' likely to develop breast cancer than if the first child' ' was born before the mother was 20.') r += 50 elif (self.chiComboBox.currentText() == 'Never had children'): self.setFlag('Women who never have children have a higher risk of ' 'breast cancer than women who have their children ' 'before 34, but a slightly lower chance of developing' ' cancer than those who have a child after 35.') r += 45 if (self.canComboBox.currentText() == '1'): self.setFlag('Having an immediate relative with a cancer increases' ' chances of getting a similar cancer dramatically.') r += 10 elif (self.canComboBox.currentText() == '2'): self.setFlag('Having an immediate relative with a cancer increases' ' chances of getting a similar cancer dramatically.') r += 20 elif (self.canComboBox.currentText() == '3'): self.setFlag('Having an immediate relative with a cancer increases' ' chances of getting a similar cancer dramatically.') r += 30 elif (self.canComboBox.currentText() == '4 or more'): self.setFlag('Having an immediate relative with a cancer increases' ' chances of getting a similar cancer dramatically.') r += 40 print(r) self.setFlag('Please consult your doctor for more accurate results on' ' cancer and your risk.') # print(self.output) self.textbox = QPlainTextEdit() if (r < 100): self.textbox.setPlainText('RISK LEVEL: LOW\nDetails:\n' + self.output) elif (r < 220): self.textbox.setPlainText('RISK LEVEL: MEDIUM\nDetails:\n' + self.output) else: self.textbox.setPlainText('RISK LEVEL: HIGH\nDetails:\n' + self.output) self.textbox.setWindowTitle('Results') self.textbox.resize(750, 750) self.textbox.show() self.output = "" def reject(self): self.close()
class SettingDialog(QDialog): updateTriggerred = pyqtSignal(dict) def __init__(self, parent=None, defSettings=None): QDialog.__init__(self, parent=parent) self.initUI(parent) self.restoreDefaultSettings(defSettings) self.updateTriggerred.connect(parent.updateSettings) def initUI(self, parent): # list views listWidget = QListWidget() # listWidget.insertItem(0, "图表") listWidget.insertItem(0, "网络结构") listWidget.insertItem(1, "训练条件") listWidget.setFixedWidth(80) # pages stackPages = self.initSettingPages(parent) listWidget.currentRowChanged.connect(stackPages.setCurrentIndex) # standard buttons self.buttonBox = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel | QDialogButtonBox.Apply | QDialogButtonBox.RestoreDefaults) self.buttonBox.clicked.connect(self.updateSettings) hbox = QHBoxLayout() hbox.addWidget(listWidget) hbox.addWidget(stackPages) topFrame = QFrame() topFrame.setLayout(hbox) mainbox = QVBoxLayout() mainbox.addWidget(topFrame) mainbox.addWidget(self.buttonBox) self.setLayout(mainbox) self.setWindowTitle("设置") def initSettingPages(self, parent): # Plot Page # label = QLabel('图表字体路径:') # self.plotFontLineEdit = QLineEdit('') # self.plotFontLineEdit.setMinimumWidth(200) # browseBtn = QPushButton('...') # browseBtn.clicked.connect(self.browseFonts) # browseBtn.setFixedWidth(40) # # plotGridBox = QGridLayout() # plotGridBox.addWidget(label, 0, 0) # plotGridBox.addWidget(self.plotFontLineEdit, 0, 1) # plotGridBox.addWidget(browseBtn, 0, 2) # plotGridBox.setColumnStretch(1, 20) # plotGridBox.setAlignment(Qt.AlignHCenter | Qt.AlignTop) # plotGrp = QGroupBox("图表设置") # plotGrp.setLayout(plotGridBox) # Network Settings self.layer0ComboBox = QComboBox() self.layer0ComboBox.addItems(['4', '8', '10']) self.layer1ComboBox = QComboBox() self.layer1ComboBox.addItems(['4', '8', '10']) networkLabels = ['隐藏层1神经元个数:', '隐藏层2神经元个数:'] networkWidgets = [self.layer0ComboBox, self.layer1ComboBox] netFrmBox = QFormLayout() for label, wd in zip(networkLabels, networkWidgets): netFrmBox.addRow(label, wd) netGrp = QGroupBox("神经网络结构设置") netGrp.setLayout(netFrmBox) netFrmBox.setRowWrapPolicy(QFormLayout.DontWrapRows) netFrmBox.setFieldGrowthPolicy(QFormLayout.AllNonFixedFieldsGrow) netFrmBox.setFormAlignment(Qt.AlignHCenter | Qt.AlignTop) netFrmBox.setLabelAlignment(Qt.AlignRight) # Training Settings self.epochLineEdit = QLineEdit('') self.retryLineEdit = QLineEdit('') self.tolLineEdit = QLineEdit('') trainLabels = ['单次迭代次数限制:', '重试次数限制:', '训练结束条件(MSE):'] trainWidgets = [ self.epochLineEdit, self.retryLineEdit, self.tolLineEdit ] trainFrmBox = QFormLayout() for label, wd in zip(trainLabels, trainWidgets): trainFrmBox.addRow(label, wd) trainGrp = QGroupBox("神经网络训练条件设置") trainGrp.setLayout(trainFrmBox) trainFrmBox.setRowWrapPolicy(QFormLayout.DontWrapRows) trainFrmBox.setFieldGrowthPolicy(QFormLayout.AllNonFixedFieldsGrow) trainFrmBox.setFormAlignment(Qt.AlignHCenter | Qt.AlignTop) trainFrmBox.setLabelAlignment(Qt.AlignRight) stackPages = QStackedWidget() # stackPages.addWidget(plotGrp) stackPages.addWidget(netGrp) stackPages.addWidget(trainGrp) return stackPages # @pyqtSlot() # def browseFonts(self): # font, ok = QFontDialog.getFont() # if ok: # print(font.family(), font.weight(), font.pointSize()) # # fname, _ = QFileDialog.getOpenFileName(self, 'Select font file', 'C:/Windows/Fonts/', 'Font file(*.ttc;*.ttf)') # # if not fname: # # return # # print(fname) @pyqtSlot(QAbstractButton) def updateSettings(self, btn): stdBtn = self.buttonBox.standardButton(btn) if stdBtn == QDialogButtonBox.Ok: self.emitSettingUpdate() self.close() elif stdBtn == QDialogButtonBox.Apply: self.emitSettingUpdate() elif stdBtn == QDialogButtonBox.RestoreDefaults: self.restoreDefaultSettings() else: self.close() def emitSettingUpdate(self): settings = { # 'font': self.plotFontLineEdit.text(), 'h0size': int(self.layer0ComboBox.currentText()), 'h1size': int(self.layer1ComboBox.currentText()), 'epoch': int(self.epochLineEdit.text()), 'retry': int(self.retryLineEdit.text()), 'tol': float(self.tolLineEdit.text()), } self.updateTriggerred.emit(settings) def restoreDefaultSettings(self, settings=None): if settings: # self.plotFontLineEdit.setText(settings['font']) id = self.layer0ComboBox.findText(str(settings['h0size'])) if id != -1: self.layer0ComboBox.setCurrentIndex(id) else: self.layer0ComboBox.setCurrentIndex(0) id = self.layer1ComboBox.findText(str(settings['h1size'])) if id != -1: self.layer1ComboBox.setCurrentIndex(id) else: self.layer1ComboBox.setCurrentIndex(0) self.epochLineEdit.setText(str(settings['epoch'])) self.retryLineEdit.setText(str(settings['retry'])) self.tolLineEdit.setText(str(settings['tol'])) else: # self.plotFontLineEdit.setText('C:/Windows/Fonts/msyh.ttc') self.layer0ComboBox.setCurrentIndex(0) self.layer1ComboBox.setCurrentIndex(0) self.epochLineEdit.setText('2000') self.retryLineEdit.setText('3') self.tolLineEdit.setText('0.5')
class SetPwdDialog(QDialog): new_infos = pyqtSignal(object) def __init__(self, parent=None): super(SetPwdDialog, self).__init__(parent) self.infos = None self.initUI() self.update_text() self.setStyleSheet(dialog_qss_style) def set_values(self, infos): self.infos = infos self.update_text() # 更新界面 def set_tip(self): # 用于提示状态 self.setWindowTitle("请稍等……") def initUI(self): self.setWindowTitle("请稍等……") self.setWindowIcon(QIcon("./icon/password.ico")) self.lb_oldpwd = QLabel() self.lb_oldpwd.setText("当前提取码:") self.lb_oldpwd.setAlignment(Qt.AlignRight | Qt.AlignTrailing | Qt.AlignVCenter) self.tx_oldpwd = QLineEdit() # 当前提取码 只读 self.tx_oldpwd.setFocusPolicy(Qt.NoFocus) self.tx_oldpwd.setReadOnly(True) self.lb_newpwd = QLabel() self.lb_newpwd.setText("新的提取码:") self.lb_newpwd.setAlignment(Qt.AlignRight | Qt.AlignTrailing | Qt.AlignVCenter) self.tx_newpwd = QLineEdit() self.buttonBox = QDialogButtonBox() self.buttonBox.setOrientation(Qt.Horizontal) self.buttonBox.setStandardButtons(QDialogButtonBox.Ok | QDialogButtonBox.Cancel) self.buttonBox.button(QDialogButtonBox.Ok).setText("确定") self.buttonBox.button(QDialogButtonBox.Cancel).setText("取消") self.grid = QGridLayout() self.grid.setSpacing(10) self.grid.addWidget(self.lb_oldpwd, 1, 0) self.grid.addWidget(self.tx_oldpwd, 1, 1) self.grid.addWidget(self.lb_newpwd, 2, 0) self.grid.addWidget(self.tx_newpwd, 2, 1) self.grid.addWidget(self.buttonBox, 3, 0, 1, 2) self.setLayout(self.grid) self.buttonBox.accepted.connect(self.btn_ok) self.buttonBox.accepted.connect(self.accept) self.buttonBox.accepted.connect(self.set_tip) self.buttonBox.rejected.connect(self.reject) self.buttonBox.rejected.connect(self.set_tip) self.setMinimumWidth(280) def update_text(self): if self.infos: if self.infos[5]: self.tx_oldpwd.setText(str(self.infos[5])) self.tx_oldpwd.setPlaceholderText("") else: self.tx_oldpwd.setText("") self.tx_oldpwd.setPlaceholderText("无") if self.infos[2]: # 文件 通过size列判断是否为文件 self.setWindowTitle("修改文件提取码") self.tx_newpwd.setPlaceholderText("2-6位字符,关闭请留空") self.tx_newpwd.setMaxLength(6) # 最长6个字符 else: # 文件夹 self.setWindowTitle("修改文件夹名提取码") self.tx_newpwd.setPlaceholderText("2-12位字符,关闭请留空") self.tx_newpwd.setMaxLength(12) # 最长12个字符 def btn_ok(self): new_pwd = self.tx_newpwd.text() if new_pwd != self.infos[5]: self.new_infos.emit( (self.infos[0], new_pwd, self.infos[2])) # 最后一位用于标示文件还是文件夹
class ColorMapsDialog(object): def __init__(self, title, message, items_selected, imageName): self.title = title self.message = message self.items_selected = items_selected #[s for s in items_selected.split(',')] self.imageName = imageName self.cmObj = ColorMaps() self.CM = self.cmObj.colorMaps form = QFormLayout() form.addRow(QLabel(message)) self.listView = QListView() form.addRow(self.listView) font = QFont() font.setBold(True) font.setPointSize(8) self.listView.setFont(font) model = QStandardItemModel(self.listView) size = QSize(60,30) for item in self.CM: # create an item with a caption standardItem = QStandardItem(item) standardItem.setCheckable(True) if item in self.items_selected: standardItem.setCheckState(True) standardItem.setSizeHint(size) model.appendRow(standardItem) self.listView.setModel(model) def setupUi(self, Dialog): Dialog.setObjectName("Dialog") Dialog.resize(530, 447) Dialog.setWindowTitle(self.title) self.buttonBox = QDialogButtonBox(Dialog) self.buttonBox.setGeometry(QRect(10, 390, 511, 32)) self.buttonBox.setOrientation(Qt.Horizontal) self.buttonBox.setStandardButtons(QDialogButtonBox.Cancel|QDialogButtonBox.Ok) self.buttonBox.setObjectName("buttonBox") self.horizontalLayoutWidget = QWidget(Dialog) self.horizontalLayoutWidget.setGeometry(QRect(9, 10, 511, 363)) self.horizontalLayoutWidget.setObjectName("horizontalLayoutWidget") self.horizontalLayout = QHBoxLayout(self.horizontalLayoutWidget) self.horizontalLayout.setContentsMargins(0, 0, 0, 0) self.horizontalLayout.setObjectName("horizontalLayout") self.horizontalLayout.addWidget(self.listView) self.label = QLabel(self.horizontalLayoutWidget) self.label.setText("") self.label.setPixmap(QPixmap(self.imageName)) self.label.setAlignment(Qt.AlignCenter) self.label.setObjectName("label") self.horizontalLayout.addWidget(self.label) self.retranslateUi(Dialog) self.buttonBox.accepted.connect(Dialog.accept) self.buttonBox.rejected.connect(Dialog.reject) QMetaObject.connectSlotsByName(Dialog) def retranslateUi(self, Dialog): _translate = QCoreApplication.translate Dialog.setWindowTitle(_translate("Dialog", self.title)) def itemsSelected(self): selected = [] model = self.listView.model() i = 0 while model.item(i): if model.item(i).checkState(): selected.append(model.item(i).text()) i += 1 return selected
class EntryDialog(QDialog, _HalWidgetBase): def __init__(self, parent=None): super(EntryDialog, self).__init__(parent) self._color = QColor(0, 0, 0, 150) self.play_sound = False self._request_name = 'ENTRY' self.title = 'Numerical Entry' self.setWindowFlags(self.windowFlags() | Qt.Tool | Qt.Dialog | Qt.WindowStaysOnTopHint | Qt.WindowSystemMenuHint) l = QVBoxLayout() self.setLayout(l) o = TouchInputWidget() l.addWidget(o) self.Num = QLineEdit() # actiate touch input self.Num.keyboard_type = 'numeric' self.Num.returnPressed.connect(lambda: self.accept()) gl = QVBoxLayout() gl.addWidget(self.Num) self.bBox = QDialogButtonBox() self.bBox.addButton('Apply', QDialogButtonBox.AcceptRole) self.bBox.addButton('Cancel', QDialogButtonBox.RejectRole) self.bBox.rejected.connect(self.reject) self.bBox.accepted.connect(self.accept) gl.addWidget(self.bBox) o.setLayout(gl) def _hal_init(self): x = self.geometry().x() y = self.geometry().y() w = self.geometry().width() h = self.geometry().height() geo = '%s %s %s %s' % (x, y, w, h) self._default_geometry = [x, y, w, h] if self.PREFS_: self._geometry_string = self.PREFS_.getpref( 'EntryDialog-geometry', geo, str, 'DIALOG_OPTIONS') else: self._geometry_string = 'default' if self.PREFS_: self.play_sound = self.PREFS_.getpref('toolDialog_play_sound', True, bool, 'DIALOG_OPTIONS') self.sound_type = self.PREFS_.getpref('toolDialog_sound_type', 'RING', str, 'DIALOG_OPTIONS') else: self.play_sound = False STATUS.connect('dialog-request', self._external_request) # this processes STATUS called dialog requests # We check the cmd to see if it was for us # then we check for a id string # if all good show the dialog # and then send back the dialog response via a general message def _external_request(self, w, message): if message.get('NAME') == self._request_name: t = message.get('TITLE') if t: self.title = t else: self.title = 'Entry' num = self.showdialog() message['RETURN'] = num STATUS.emit('general', message) def showdialog(self): STATUS.emit('focus-overlay-changed', True, 'Origin Setting', self._color) self.setWindowTitle(self.title) if self.play_sound: STATUS.emit('play-alert', self.sound_type) self.calculate_placement() retval = self.exec_() STATUS.emit('focus-overlay-changed', False, None, None) record_geometry(self, 'EntryDialog-geometry') LOG.debug("Value of pressed button: {}".format(retval)) if retval: try: return float(self.Num.text()) except Exception as e: print e return None def calculate_placement(self): geometry_parsing(self, 'EntryDialog-geometry') def getColor(self): return self._color def setColor(self, value): self._color = value def resetState(self): self._color = QColor(0, 0, 0, 150) overlay_color = pyqtProperty(QColor, getColor, setColor)
class UploadDialog(QDialog): """文件上传对话框""" new_infos = pyqtSignal(object) def __init__(self, user_home): super().__init__() self.cwd = user_home self._folder_id = -1 self._folder_name = "LanZouCloud" self.set_pwd = False self.set_desc = False self.pwd = '' self.desc = '' self.allow_big_file = False self.max_size = 100 self.selected = [] self.initUI() self.set_size() self.setStyleSheet(dialog_qss_style) def set_pwd_desc_bigfile(self, settings): self.set_pwd = settings["set_pwd"] self.set_desc = settings["set_desc"] self.pwd = settings["pwd"] self.desc = settings["desc"] self.allow_big_file = settings["allow_big_file"] self.max_size = settings["max_size"] if self.allow_big_file: self.btn_chooseMultiFile.setToolTip("") else: self.btn_chooseMultiFile.setToolTip(f"文件大小上限 {self.max_size}MB") def set_values(self, folder_name, folder_id, files): self.setWindowTitle("上传文件至 ➩ " + str(folder_name)) self._folder_id = folder_id self._folder_name = folder_name if files: self.selected = files self.show_selected() self.exec() def initUI(self): self.setWindowTitle("上传文件") self.setWindowIcon(QIcon(SRC_DIR + "upload.ico")) self.logo = QLabel() self.logo.setPixmap(QPixmap(SRC_DIR + "logo3.gif")) self.logo.setStyleSheet("background-color:rgb(0,153,255);") self.logo.setAlignment(Qt.AlignCenter) # btn 1 self.btn_chooseDir = QPushButton("选择文件夹", self) self.btn_chooseDir.setObjectName("btn_chooseDir") self.btn_chooseDir.setObjectName("btn_chooseDir") self.btn_chooseDir.setIcon(QIcon(SRC_DIR + "folder.gif")) # btn 2 self.btn_chooseMultiFile = QPushButton("选择多文件", self) self.btn_chooseDir.setObjectName("btn_chooseMultiFile") self.btn_chooseMultiFile.setObjectName("btn_chooseMultiFile") self.btn_chooseMultiFile.setIcon(QIcon(SRC_DIR + "file.ico")) # btn 3 self.btn_deleteSelect = QPushButton("移除", self) self.btn_deleteSelect.setObjectName("btn_deleteSelect") self.btn_deleteSelect.setIcon(QIcon(SRC_DIR + "delete.ico")) self.btn_deleteSelect.setToolTip("按 Delete 移除选中文件") # 列表 self.list_view = MyListView() self.list_view.drop_files.connect(self.add_drop_files) self.list_view.setViewMode(QListView.ListMode) self.slm = QStandardItem() self.model = QStandardItemModel() self.list_view.setModel(self.model) self.model.removeRows(0, self.model.rowCount()) # 清除旧的选择 self.list_view.setEditTriggers(QAbstractItemView.NoEditTriggers) self.list_view.setSelectionBehavior(QAbstractItemView.SelectRows) self.list_view.setSelectionMode(QAbstractItemView.ExtendedSelection) self.buttonBox = QDialogButtonBox() self.buttonBox.setOrientation(Qt.Horizontal) self.buttonBox.setStandardButtons(QDialogButtonBox.Ok | QDialogButtonBox.Cancel) self.buttonBox.button(QDialogButtonBox.Ok).setText("确定") self.buttonBox.button(QDialogButtonBox.Cancel).setText("取消") vbox = QVBoxLayout() hbox_head = QHBoxLayout() hbox_button = QHBoxLayout() hbox_head.addWidget(self.btn_chooseDir) hbox_head.addStretch(1) hbox_head.addWidget(self.btn_chooseMultiFile) hbox_button.addWidget(self.btn_deleteSelect) hbox_button.addStretch(1) hbox_button.addWidget(self.buttonBox) vbox.addWidget(self.logo) vbox.addLayout(hbox_head) vbox.addWidget(self.list_view) vbox.addLayout(hbox_button) self.setLayout(vbox) self.setMinimumWidth(350) # 设置信号 self.btn_chooseDir.clicked.connect(self.slot_btn_chooseDir) self.btn_chooseMultiFile.clicked.connect(self.slot_btn_chooseMultiFile) self.btn_deleteSelect.clicked.connect(self.slot_btn_deleteSelect) self.buttonBox.accepted.connect(self.slot_btn_ok) self.buttonBox.accepted.connect(self.accept) self.buttonBox.rejected.connect(self.clear_old) self.buttonBox.rejected.connect(self.reject) def set_size(self): if self.selected: h = 18 if len(self.selected) > 18 else 10 w = 40 for i in self.selected: i_len = len(i) if i_len > 100: w = 100 break if i_len > w: w = i_len self.resize(120 + w * 7, h * 30) else: self.resize(400, 300) def clear_old(self): self.selected = [] self.model.removeRows(0, self.model.rowCount()) self.set_size() def show_selected(self): self.model.removeRows(0, self.model.rowCount()) for item in self.selected: if os.path.isfile(item): self.model.appendRow( QStandardItem(QIcon(SRC_DIR + "file.ico"), item)) else: self.model.appendRow( QStandardItem(QIcon(SRC_DIR + "folder.gif"), item)) self.set_size() def backslash(self): """Windows backslash""" tasks = {} for item in self.selected: url = os.path.normpath(item) total_size = 0 total_file = 0 if os.path.isfile(url): total_size = os.path.getsize(url) total_file += 1 else: for filename in os.listdir(url): file_path = os.path.join(url, filename) if not os.path.isfile(file_path): continue # 跳过子文件夹 total_size += os.path.getsize(file_path) total_file += 1 tasks[url] = UpJob(url=url, fid=self._folder_id, folder=self._folder_name, pwd=self.pwd if self.set_pwd else None, desc=self.desc if self.set_desc else None, total_size=total_size, total_file=total_file) return tasks def slot_btn_ok(self): tasks = self.backslash() if self.selected: self.new_infos.emit(tasks) self.clear_old() def slot_btn_deleteSelect(self): _indexes = self.list_view.selectionModel().selection().indexes() if not _indexes: return indexes = [] for i in _indexes: # 获取所选行号 indexes.append(i.row()) indexes = set(indexes) for i in sorted(indexes, reverse=True): self.selected.remove(self.model.item(i, 0).text()) self.model.removeRow(i) self.set_size() def add_drop_files(self, files): for item in files: if item not in self.selected: self.selected.append(item) self.show_selected() def slot_btn_chooseDir(self): dir_choose = QFileDialog.getExistingDirectory(self, "选择文件夹", self.cwd) # 起始路径 if dir_choose == "": return if dir_choose not in self.selected: self.selected.append(dir_choose) self.cwd = os.path.dirname(dir_choose) self.show_selected() def slot_btn_chooseMultiFile(self): files, _ = QFileDialog.getOpenFileNames(self, "选择多文件", self.cwd, "All Files (*)") if len(files) == 0: return for _file in files: if _file not in self.selected: if os.path.getsize(_file) <= self.max_size * 1048576: self.selected.append(_file) elif self.allow_big_file: self.selected.append(_file) self.show_selected() def keyPressEvent(self, e): if e.key() == Qt.Key_Delete: # delete self.slot_btn_deleteSelect()
def showDetailFilter(self, checkState): detailDialog = QDialog(self.main_window) detailDialog.setWindowTitle(_("Detailed Filters")) handbox = QVBoxLayout() detailDialog.setLayout(handbox) label = QLabel(_("Hand Filters:")) handbox.addWidget(label) label.setAlignment(Qt.AlignCenter) grid = QGridLayout() handbox.addLayout(grid) for row, htest in enumerate(self.handtests): cb = QCheckBox() lbl_from = QLabel(htest[1]) lbl_tween = QLabel(_('between')) lbl_to = QLabel(_('and')) sb1 = QSpinBox() sb1.setRange(0, 10) sb1.setValue(htest[2]) sb2 = QSpinBox() sb2.setRange(2, 10) sb2.setValue(htest[3]) for df in self.detailFilters: if df[0] == htest[0]: cb.setChecked(True) break grid.addWidget(cb, row, 0) grid.addWidget(lbl_from, row, 1, Qt.AlignLeft) grid.addWidget(lbl_tween, row, 2) grid.addWidget(sb1, row, 3) grid.addWidget(lbl_to, row, 4) grid.addWidget(sb2, row, 5) htest[4:7] = [cb, sb1, sb2] label = QLabel(_('Restrict to hand types:')) handbox.addWidget(label) for ctest in self.cardstests: hbox = QHBoxLayout() handbox.addLayout(hbox) cb = QCheckBox() if ctest[0] in self.cardsFilters: cb.setChecked(True) label = QLabel(ctest[1]) hbox.addWidget(cb) hbox.addWidget(label) ctest[2:3] = [cb] btnBox = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel) handbox.addWidget(btnBox) btnBox.accepted.connect(detailDialog.accept) btnBox.rejected.connect(detailDialog.reject) response = detailDialog.exec_() if response: self.detailFilters = [] for ht in self.handtests: if ht[4].isChecked(): self.detailFilters.append( (ht[0], ht[5].value(), ht[6].value())) ht[2], ht[3] = ht[5].value(), ht[6].value() self.cardsFilters = [] for ct in self.cardstests: if ct[2].isChecked(): self.cardsFilters.append(ct[0]) self.refreshStats(None)
class _CrashDialog(QDialog): """Dialog which gets shown after there was a crash. Attributes: These are just here to have a static reference to avoid GCing. _vbox: The main QVBoxLayout _lbl: The QLabel with the static text _debug_log: The QTextEdit with the crash information _btn_box: The QDialogButtonBox containing the buttons. _url: Pastebin URL QLabel. _crash_info: A list of tuples with title and crash information. _paste_client: A PastebinClient instance to use. _pypi_client: A PyPIVersionClient instance to use. _paste_text: The text to pastebin. """ def __init__(self, debug, parent=None): """Constructor for CrashDialog. Args: debug: Whether --debug was given. """ super().__init__(parent) # We don't set WA_DeleteOnClose here as on an exception, we'll get # closed anyways, and it only could have unintended side-effects. self._crash_info = [] self._btn_box = None self._btn_report = None self._btn_cancel = None self._lbl = None self._paste_text = None self.setWindowTitle("Whoops!") self.resize(QSize(640, 600)) self._vbox = QVBoxLayout(self) http_client = httpclient.HTTPClient() self._paste_client = pastebin.PastebinClient(http_client, self) self._pypi_client = autoupdate.PyPIVersionClient(self) self._init_text() contact = QLabel( "I'd like to be able to follow up with you, to keep " "you posted on the status of this crash and get more " "information if I need it - how can I contact you?", wordWrap=True) self._vbox.addWidget(contact) self._contact = QTextEdit(tabChangesFocus=True, acceptRichText=False) try: state = objreg.get('state-config') try: self._contact.setPlainText(state['general']['contact-info']) except KeyError: self._contact.setPlaceholderText("Mail or IRC nickname") except Exception: log.misc.exception("Failed to get contact information!") self._contact.setPlaceholderText("Mail or IRC nickname") self._vbox.addWidget(self._contact, 2) info = QLabel("What were you doing when this crash/bug happened?") self._vbox.addWidget(info) self._info = QTextEdit(tabChangesFocus=True, acceptRichText=False) self._info.setPlaceholderText("- Opened http://www.example.com/\n" "- Switched tabs\n" "- etc...") self._vbox.addWidget(self._info, 5) self._vbox.addSpacing(15) self._debug_log = QTextEdit(tabChangesFocus=True, acceptRichText=False, lineWrapMode=QTextEdit.NoWrap) self._debug_log.hide() info = QLabel( "<i>You can edit the log below to remove sensitive " "information.</i>", wordWrap=True) info.hide() self._fold = miscwidgets.DetailFold("Show log", self) self._fold.toggled.connect(self._debug_log.setVisible) self._fold.toggled.connect(info.setVisible) if debug: self._fold.toggle() self._vbox.addWidget(self._fold) self._vbox.addWidget(info) self._vbox.addWidget(self._debug_log, 10) self._vbox.addSpacing(15) self._init_checkboxes() self._init_info_text() self._init_buttons() def __repr__(self): return utils.get_repr(self) def _init_text(self): """Initialize the main text to be displayed on an exception. Should be extended by subclasses to set the actual text. """ self._lbl = QLabel(wordWrap=True, openExternalLinks=True, textInteractionFlags=Qt.LinksAccessibleByMouse) self._vbox.addWidget(self._lbl) def _init_checkboxes(self): """Initialize the checkboxes.""" pass def _init_buttons(self): """Initialize the buttons.""" self._btn_box = QDialogButtonBox() self._vbox.addWidget(self._btn_box) self._btn_report = QPushButton("Report", default=True) self._btn_report.clicked.connect(self.on_report_clicked) self._btn_box.addButton(self._btn_report, QDialogButtonBox.AcceptRole) self._btn_cancel = QPushButton("Don't report", autoDefault=False) self._btn_cancel.clicked.connect(self.finish) self._btn_box.addButton(self._btn_cancel, QDialogButtonBox.RejectRole) def _init_info_text(self): """Add an info text encouraging the user to report crashes.""" info_label = QLabel( "<br/><b>Note that without your help, I can't fix " "the bug you encountered.<br/> Crash reports are " "currently publicly accessible.</b>", wordWrap=True) self._vbox.addWidget(info_label) def _gather_crash_info(self): """Gather crash information to display. Args: pages: A list of lists of the open pages (URLs as strings) cmdhist: A list with the command history (as strings) exc: An exception tuple (type, value, traceback) """ try: application = QApplication.instance() launch_time = application.launch_time.ctime() crash_time = datetime.datetime.now().ctime() text = 'Launch: {}\nCrash: {}'.format(launch_time, crash_time) self._crash_info.append(('Timestamps', text)) except Exception: self._crash_info.append(("Launch time", traceback.format_exc())) try: self._crash_info.append(("Version info", version.version())) except Exception: self._crash_info.append(("Version info", traceback.format_exc())) try: conf = objreg.get('config') self._crash_info.append(("Config", conf.dump_userconfig())) except Exception: self._crash_info.append(("Config", traceback.format_exc())) try: self._crash_info.append(("Environment", _get_environment_vars())) except Exception: self._crash_info.append(("Environment", traceback.format_exc())) def _set_crash_info(self): """Set/update the crash info.""" self._crash_info = [] self._gather_crash_info() chunks = [] for (header, body) in self._crash_info: if body is not None: h = '==== {} ===='.format(header) chunks.append('\n'.join([h, body])) text = '\n\n'.join(chunks) self._debug_log.setText(text) def _get_error_type(self): """Get the type of the error we're reporting.""" raise NotImplementedError def _get_paste_title_desc(self): """Get a short description of the paste.""" return '' def _get_paste_title(self): """Get a title for the paste.""" desc = self._get_paste_title_desc() title = "qute {} {}".format(qutebrowser.__version__, self._get_error_type()) if desc: title += ' {}'.format(desc) return title def _save_contact_info(self): """Save the contact info to disk.""" try: state = objreg.get('state-config') state['general']['contact-info'] = self._contact.toPlainText() except Exception: log.misc.exception("Failed to save contact information!") def report(self): """Paste the crash info into the pastebin.""" lines = [] lines.append("========== Report ==========") lines.append(self._info.toPlainText()) lines.append("========== Contact ==========") lines.append(self._contact.toPlainText()) lines.append("========== Debug log ==========") lines.append(self._debug_log.toPlainText()) self._paste_text = '\n\n'.join(lines) try: user = getpass.getuser() except Exception as e: log.misc.exception("Error while getting user") user = '******' try: # parent: http://p.cmpl.cc/90286958 self._paste_client.paste(user, self._get_paste_title(), self._paste_text, parent='90286958') except Exception as e: log.misc.exception("Error while paste-binning") exc_text = '{}: {}'.format(e.__class__.__name__, e) self.show_error(exc_text) @pyqtSlot() def on_report_clicked(self): """Report and close dialog if report button was clicked.""" self._btn_report.setEnabled(False) self._btn_cancel.setEnabled(False) self._btn_report.setText("Reporting...") self._paste_client.success.connect(self.on_paste_success) self._paste_client.error.connect(self.show_error) self.report() @pyqtSlot() def on_paste_success(self): """Get the newest version from PyPI when the paste is done.""" self._pypi_client.success.connect(self.on_version_success) self._pypi_client.error.connect(self.on_version_error) self._pypi_client.get_version() @pyqtSlot(str) def show_error(self, text): """Show a paste error dialog. Args: text: The paste text to show. """ error_dlg = ReportErrorDialog(text, self._paste_text, self) error_dlg.finished.connect(self.finish) error_dlg.show() @pyqtSlot(str) def on_version_success(self, newest): """Called when the version was obtained from self._pypi_client. Args: newest: The newest version as a string. """ new_version = pkg_resources.parse_version(newest) cur_version = pkg_resources.parse_version(qutebrowser.__version__) lines = ['The report has been sent successfully. Thanks!'] if new_version > cur_version: lines.append("<b>Note:</b> The newest available version is v{}, " "but you're currently running v{} - please " "update!".format(newest, qutebrowser.__version__)) text = '<br/><br/>'.join(lines) self.finish() msgbox.information(self, "Report successfully sent!", text, on_finished=self.finish, plain_text=False) @pyqtSlot(str) def on_version_error(self, msg): """Called when the version was not obtained from self._pypi_client. Args: msg: The error message to show. """ lines = ['The report has been sent successfully. Thanks!'] lines.append("There was an error while getting the newest version: " "{}. Please check for a new version on " "<a href=http://www.qutebrowser.org/>qutebrowser.org</a> " "by yourself.".format(msg)) text = '<br/><br/>'.join(lines) self.finish() msgbox.information(self, "Report successfully sent!", text, on_finished=self.finish, plain_text=False) @pyqtSlot() def finish(self): """Save contact info and close the dialog.""" self._save_contact_info() self.accept()
def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.setWindowModality(QtCore.Qt.ApplicationModal) self.setWindowTitle(translate('About', 'About Linux Show Player')) self.setMaximumSize(500, 420) self.setMinimumSize(500, 420) self.resize(500, 420) self.setLayout(QGridLayout()) self.iconLabel = QLabel(self) self.iconLabel.setPixmap( QIcon.fromTheme('linux-show-player').pixmap(100, 100)) self.layout().addWidget(self.iconLabel, 0, 0) self.shortInfo = QLabel(self) self.shortInfo.setAlignment(Qt.AlignCenter) self.shortInfo.setText('<h2>Linux Show Player {0}</h2>' 'Copyright © Francesco Ceruti'.format( str(lisp.__version__))) self.layout().addWidget(self.shortInfo, 0, 1) self.layout().addWidget(QWidget(), 1, 0, 1, 2) # Information tabs self.tabWidget = QTabWidget(self) self.layout().addWidget(self.tabWidget, 2, 0, 1, 2) self.info = QTextBrowser(self) self.info.setOpenExternalLinks(True) self.info.setHtml(''' <center><br />{0}<br /><br /> <a href="{1}">{2}</a><br /> <a href="{3}">{4}</a><br /> <a href="{5}">{6}</a><br /><center>'''.format( translate('AboutDialog', self.DESCRIPTION), self.WEB_SITE, translate('AboutDialog', 'Web site'), self.USER_GROUP, translate('AboutDialog', 'Users group'), self.SOURCE_CODE, translate('AboutDialog', 'Source code'))) self.tabWidget.addTab(self.info, translate('AboutDialog', 'Info')) self.license = QTextBrowser(self) self.license.setOpenExternalLinks(True) self.license.setHtml(self.LICENSE) self.tabWidget.addTab(self.license, translate('AboutDialog', 'License')) self.contributors = QTextBrowser(self) self.contributors.setOpenExternalLinks(True) self.contributors.setHtml(self.__contributors()) self.tabWidget.addTab(self.contributors, translate('AboutDialog', 'Contributors')) # Ok button self.buttons = QDialogButtonBox(QDialogButtonBox.Ok) self.buttons.accepted.connect(self.accept) self.layout().addWidget(self.buttons, 3, 1) self.layout().setColumnStretch(0, 1) self.layout().setColumnStretch(1, 3) self.layout().setRowStretch(0, 6) self.layout().setRowStretch(1, 1) self.layout().setRowStretch(2, 16) self.layout().setRowStretch(3, 3) self.buttons.setFocus()
def __init__(self, mainGui): QDialog.__init__(self, mainGui) logger.debug("Initialising GuiWritingStats ...") self.setObjectName("GuiWritingStats") self.mainConf = novelwriter.CONFIG self.mainGui = mainGui self.mainTheme = mainGui.mainTheme self.theProject = mainGui.theProject self.logData = [] self.filterData = [] self.timeFilter = 0.0 self.wordOffset = 0 pOptions = self.theProject.options self.setWindowTitle(self.tr("Writing Statistics")) self.setMinimumWidth(self.mainConf.pxInt(420)) self.setMinimumHeight(self.mainConf.pxInt(400)) self.resize( self.mainConf.pxInt(pOptions.getInt("GuiWritingStats", "winWidth", 550)), self.mainConf.pxInt(pOptions.getInt("GuiWritingStats", "winHeight", 500)) ) # List Box wCol0 = self.mainConf.pxInt( pOptions.getInt("GuiWritingStats", "widthCol0", 180) ) wCol1 = self.mainConf.pxInt( pOptions.getInt("GuiWritingStats", "widthCol1", 80) ) wCol2 = self.mainConf.pxInt( pOptions.getInt("GuiWritingStats", "widthCol2", 80) ) wCol3 = self.mainConf.pxInt( pOptions.getInt("GuiWritingStats", "widthCol3", 80) ) self.listBox = QTreeWidget() self.listBox.setHeaderLabels([ self.tr("Session Start"), self.tr("Length"), self.tr("Idle"), self.tr("Words"), self.tr("Histogram"), ]) self.listBox.setIndentation(0) self.listBox.setColumnWidth(self.C_TIME, wCol0) self.listBox.setColumnWidth(self.C_LENGTH, wCol1) self.listBox.setColumnWidth(self.C_IDLE, wCol2) self.listBox.setColumnWidth(self.C_COUNT, wCol3) hHeader = self.listBox.headerItem() hHeader.setTextAlignment(self.C_LENGTH, Qt.AlignRight) hHeader.setTextAlignment(self.C_IDLE, Qt.AlignRight) hHeader.setTextAlignment(self.C_COUNT, Qt.AlignRight) sortCol = checkIntRange(pOptions.getInt("GuiWritingStats", "sortCol", 0), 0, 2, 0) sortOrder = checkIntTuple( pOptions.getInt("GuiWritingStats", "sortOrder", Qt.DescendingOrder), (Qt.AscendingOrder, Qt.DescendingOrder), Qt.DescendingOrder ) self.listBox.sortByColumn(sortCol, sortOrder) self.listBox.setSortingEnabled(True) # Word Bar self.barHeight = int(round(0.5*self.mainTheme.fontPixelSize)) self.barWidth = self.mainConf.pxInt(200) self.barImage = QPixmap(self.barHeight, self.barHeight) self.barImage.fill(self.palette().highlight().color()) # Session Info self.infoBox = QGroupBox(self.tr("Sum Totals"), self) self.infoForm = QGridLayout(self) self.infoBox.setLayout(self.infoForm) self.labelTotal = QLabel(formatTime(0)) self.labelTotal.setFont(self.mainTheme.guiFontFixed) self.labelTotal.setAlignment(Qt.AlignVCenter | Qt.AlignRight) self.labelIdleT = QLabel(formatTime(0)) self.labelIdleT.setFont(self.mainTheme.guiFontFixed) self.labelIdleT.setAlignment(Qt.AlignVCenter | Qt.AlignRight) self.labelFilter = QLabel(formatTime(0)) self.labelFilter.setFont(self.mainTheme.guiFontFixed) self.labelFilter.setAlignment(Qt.AlignVCenter | Qt.AlignRight) self.novelWords = QLabel("0") self.novelWords.setFont(self.mainTheme.guiFontFixed) self.novelWords.setAlignment(Qt.AlignVCenter | Qt.AlignRight) self.notesWords = QLabel("0") self.notesWords.setFont(self.mainTheme.guiFontFixed) self.notesWords.setAlignment(Qt.AlignVCenter | Qt.AlignRight) self.totalWords = QLabel("0") self.totalWords.setFont(self.mainTheme.guiFontFixed) self.totalWords.setAlignment(Qt.AlignVCenter | Qt.AlignRight) lblTTime = QLabel(self.tr("Total Time:")) lblITime = QLabel(self.tr("Idle Time:")) lblFTime = QLabel(self.tr("Filtered Time:")) lblNvCount = QLabel(self.tr("Novel Word Count:")) lblNtCount = QLabel(self.tr("Notes Word Count:")) lblTtCount = QLabel(self.tr("Total Word Count:")) self.infoForm.addWidget(lblTTime, 0, 0) self.infoForm.addWidget(lblITime, 1, 0) self.infoForm.addWidget(lblFTime, 2, 0) self.infoForm.addWidget(lblNvCount, 3, 0) self.infoForm.addWidget(lblNtCount, 4, 0) self.infoForm.addWidget(lblTtCount, 5, 0) self.infoForm.addWidget(self.labelTotal, 0, 1) self.infoForm.addWidget(self.labelIdleT, 1, 1) self.infoForm.addWidget(self.labelFilter, 2, 1) self.infoForm.addWidget(self.novelWords, 3, 1) self.infoForm.addWidget(self.notesWords, 4, 1) self.infoForm.addWidget(self.totalWords, 5, 1) self.infoForm.setRowStretch(6, 1) # Filter Options sPx = self.mainTheme.baseIconSize self.filterBox = QGroupBox(self.tr("Filters"), self) self.filterForm = QGridLayout(self) self.filterBox.setLayout(self.filterForm) self.incNovel = QSwitch(width=2*sPx, height=sPx) self.incNovel.setChecked( pOptions.getBool("GuiWritingStats", "incNovel", True) ) self.incNovel.clicked.connect(self._updateListBox) self.incNotes = QSwitch(width=2*sPx, height=sPx) self.incNotes.setChecked( pOptions.getBool("GuiWritingStats", "incNotes", True) ) self.incNotes.clicked.connect(self._updateListBox) self.hideZeros = QSwitch(width=2*sPx, height=sPx) self.hideZeros.setChecked( pOptions.getBool("GuiWritingStats", "hideZeros", True) ) self.hideZeros.clicked.connect(self._updateListBox) self.hideNegative = QSwitch(width=2*sPx, height=sPx) self.hideNegative.setChecked( pOptions.getBool("GuiWritingStats", "hideNegative", False) ) self.hideNegative.clicked.connect(self._updateListBox) self.groupByDay = QSwitch(width=2*sPx, height=sPx) self.groupByDay.setChecked( pOptions.getBool("GuiWritingStats", "groupByDay", False) ) self.groupByDay.clicked.connect(self._updateListBox) self.showIdleTime = QSwitch(width=2*sPx, height=sPx) self.showIdleTime.setChecked( pOptions.getBool("GuiWritingStats", "showIdleTime", False) ) self.showIdleTime.clicked.connect(self._updateListBox) self.filterForm.addWidget(QLabel(self.tr("Count novel files")), 0, 0) self.filterForm.addWidget(QLabel(self.tr("Count note files")), 1, 0) self.filterForm.addWidget(QLabel(self.tr("Hide zero word count")), 2, 0) self.filterForm.addWidget(QLabel(self.tr("Hide negative word count")), 3, 0) self.filterForm.addWidget(QLabel(self.tr("Group entries by day")), 4, 0) self.filterForm.addWidget(QLabel(self.tr("Show idle time")), 5, 0) self.filterForm.addWidget(self.incNovel, 0, 1) self.filterForm.addWidget(self.incNotes, 1, 1) self.filterForm.addWidget(self.hideZeros, 2, 1) self.filterForm.addWidget(self.hideNegative, 3, 1) self.filterForm.addWidget(self.groupByDay, 4, 1) self.filterForm.addWidget(self.showIdleTime, 5, 1) self.filterForm.setRowStretch(6, 1) # Settings self.histMax = QSpinBox(self) self.histMax.setMinimum(100) self.histMax.setMaximum(100000) self.histMax.setSingleStep(100) self.histMax.setValue( pOptions.getInt("GuiWritingStats", "histMax", 2000) ) self.histMax.valueChanged.connect(self._updateListBox) self.optsBox = QHBoxLayout() self.optsBox.addStretch(1) self.optsBox.addWidget(QLabel(self.tr("Word count cap for the histogram")), 0) self.optsBox.addWidget(self.histMax, 0) # Buttons self.buttonBox = QDialogButtonBox() self.buttonBox.rejected.connect(self._doClose) self.btnClose = self.buttonBox.addButton(QDialogButtonBox.Close) self.btnClose.setAutoDefault(False) self.btnSave = self.buttonBox.addButton(self.tr("Save As"), QDialogButtonBox.ActionRole) self.btnSave.setAutoDefault(False) self.saveMenu = QMenu(self) self.btnSave.setMenu(self.saveMenu) self.saveJSON = QAction(self.tr("JSON Data File (.json)"), self) self.saveJSON.triggered.connect(lambda: self._saveData(self.FMT_JSON)) self.saveMenu.addAction(self.saveJSON) self.saveCSV = QAction(self.tr("CSV Data File (.csv)"), self) self.saveCSV.triggered.connect(lambda: self._saveData(self.FMT_CSV)) self.saveMenu.addAction(self.saveCSV) # Assemble self.outerBox = QGridLayout() self.outerBox.addWidget(self.listBox, 0, 0, 1, 2) self.outerBox.addLayout(self.optsBox, 1, 0, 1, 2) self.outerBox.addWidget(self.infoBox, 2, 0) self.outerBox.addWidget(self.filterBox, 2, 1) self.outerBox.addWidget(self.buttonBox, 3, 0, 1, 2) self.outerBox.setRowStretch(0, 1) self.setLayout(self.outerBox) logger.debug("GuiWritingStats initialisation complete") return
class GuiWritingStats(QDialog): C_TIME = 0 C_LENGTH = 1 C_IDLE = 2 C_COUNT = 3 C_BAR = 4 FMT_JSON = 0 FMT_CSV = 1 def __init__(self, mainGui): QDialog.__init__(self, mainGui) logger.debug("Initialising GuiWritingStats ...") self.setObjectName("GuiWritingStats") self.mainConf = novelwriter.CONFIG self.mainGui = mainGui self.mainTheme = mainGui.mainTheme self.theProject = mainGui.theProject self.logData = [] self.filterData = [] self.timeFilter = 0.0 self.wordOffset = 0 pOptions = self.theProject.options self.setWindowTitle(self.tr("Writing Statistics")) self.setMinimumWidth(self.mainConf.pxInt(420)) self.setMinimumHeight(self.mainConf.pxInt(400)) self.resize( self.mainConf.pxInt(pOptions.getInt("GuiWritingStats", "winWidth", 550)), self.mainConf.pxInt(pOptions.getInt("GuiWritingStats", "winHeight", 500)) ) # List Box wCol0 = self.mainConf.pxInt( pOptions.getInt("GuiWritingStats", "widthCol0", 180) ) wCol1 = self.mainConf.pxInt( pOptions.getInt("GuiWritingStats", "widthCol1", 80) ) wCol2 = self.mainConf.pxInt( pOptions.getInt("GuiWritingStats", "widthCol2", 80) ) wCol3 = self.mainConf.pxInt( pOptions.getInt("GuiWritingStats", "widthCol3", 80) ) self.listBox = QTreeWidget() self.listBox.setHeaderLabels([ self.tr("Session Start"), self.tr("Length"), self.tr("Idle"), self.tr("Words"), self.tr("Histogram"), ]) self.listBox.setIndentation(0) self.listBox.setColumnWidth(self.C_TIME, wCol0) self.listBox.setColumnWidth(self.C_LENGTH, wCol1) self.listBox.setColumnWidth(self.C_IDLE, wCol2) self.listBox.setColumnWidth(self.C_COUNT, wCol3) hHeader = self.listBox.headerItem() hHeader.setTextAlignment(self.C_LENGTH, Qt.AlignRight) hHeader.setTextAlignment(self.C_IDLE, Qt.AlignRight) hHeader.setTextAlignment(self.C_COUNT, Qt.AlignRight) sortCol = checkIntRange(pOptions.getInt("GuiWritingStats", "sortCol", 0), 0, 2, 0) sortOrder = checkIntTuple( pOptions.getInt("GuiWritingStats", "sortOrder", Qt.DescendingOrder), (Qt.AscendingOrder, Qt.DescendingOrder), Qt.DescendingOrder ) self.listBox.sortByColumn(sortCol, sortOrder) self.listBox.setSortingEnabled(True) # Word Bar self.barHeight = int(round(0.5*self.mainTheme.fontPixelSize)) self.barWidth = self.mainConf.pxInt(200) self.barImage = QPixmap(self.barHeight, self.barHeight) self.barImage.fill(self.palette().highlight().color()) # Session Info self.infoBox = QGroupBox(self.tr("Sum Totals"), self) self.infoForm = QGridLayout(self) self.infoBox.setLayout(self.infoForm) self.labelTotal = QLabel(formatTime(0)) self.labelTotal.setFont(self.mainTheme.guiFontFixed) self.labelTotal.setAlignment(Qt.AlignVCenter | Qt.AlignRight) self.labelIdleT = QLabel(formatTime(0)) self.labelIdleT.setFont(self.mainTheme.guiFontFixed) self.labelIdleT.setAlignment(Qt.AlignVCenter | Qt.AlignRight) self.labelFilter = QLabel(formatTime(0)) self.labelFilter.setFont(self.mainTheme.guiFontFixed) self.labelFilter.setAlignment(Qt.AlignVCenter | Qt.AlignRight) self.novelWords = QLabel("0") self.novelWords.setFont(self.mainTheme.guiFontFixed) self.novelWords.setAlignment(Qt.AlignVCenter | Qt.AlignRight) self.notesWords = QLabel("0") self.notesWords.setFont(self.mainTheme.guiFontFixed) self.notesWords.setAlignment(Qt.AlignVCenter | Qt.AlignRight) self.totalWords = QLabel("0") self.totalWords.setFont(self.mainTheme.guiFontFixed) self.totalWords.setAlignment(Qt.AlignVCenter | Qt.AlignRight) lblTTime = QLabel(self.tr("Total Time:")) lblITime = QLabel(self.tr("Idle Time:")) lblFTime = QLabel(self.tr("Filtered Time:")) lblNvCount = QLabel(self.tr("Novel Word Count:")) lblNtCount = QLabel(self.tr("Notes Word Count:")) lblTtCount = QLabel(self.tr("Total Word Count:")) self.infoForm.addWidget(lblTTime, 0, 0) self.infoForm.addWidget(lblITime, 1, 0) self.infoForm.addWidget(lblFTime, 2, 0) self.infoForm.addWidget(lblNvCount, 3, 0) self.infoForm.addWidget(lblNtCount, 4, 0) self.infoForm.addWidget(lblTtCount, 5, 0) self.infoForm.addWidget(self.labelTotal, 0, 1) self.infoForm.addWidget(self.labelIdleT, 1, 1) self.infoForm.addWidget(self.labelFilter, 2, 1) self.infoForm.addWidget(self.novelWords, 3, 1) self.infoForm.addWidget(self.notesWords, 4, 1) self.infoForm.addWidget(self.totalWords, 5, 1) self.infoForm.setRowStretch(6, 1) # Filter Options sPx = self.mainTheme.baseIconSize self.filterBox = QGroupBox(self.tr("Filters"), self) self.filterForm = QGridLayout(self) self.filterBox.setLayout(self.filterForm) self.incNovel = QSwitch(width=2*sPx, height=sPx) self.incNovel.setChecked( pOptions.getBool("GuiWritingStats", "incNovel", True) ) self.incNovel.clicked.connect(self._updateListBox) self.incNotes = QSwitch(width=2*sPx, height=sPx) self.incNotes.setChecked( pOptions.getBool("GuiWritingStats", "incNotes", True) ) self.incNotes.clicked.connect(self._updateListBox) self.hideZeros = QSwitch(width=2*sPx, height=sPx) self.hideZeros.setChecked( pOptions.getBool("GuiWritingStats", "hideZeros", True) ) self.hideZeros.clicked.connect(self._updateListBox) self.hideNegative = QSwitch(width=2*sPx, height=sPx) self.hideNegative.setChecked( pOptions.getBool("GuiWritingStats", "hideNegative", False) ) self.hideNegative.clicked.connect(self._updateListBox) self.groupByDay = QSwitch(width=2*sPx, height=sPx) self.groupByDay.setChecked( pOptions.getBool("GuiWritingStats", "groupByDay", False) ) self.groupByDay.clicked.connect(self._updateListBox) self.showIdleTime = QSwitch(width=2*sPx, height=sPx) self.showIdleTime.setChecked( pOptions.getBool("GuiWritingStats", "showIdleTime", False) ) self.showIdleTime.clicked.connect(self._updateListBox) self.filterForm.addWidget(QLabel(self.tr("Count novel files")), 0, 0) self.filterForm.addWidget(QLabel(self.tr("Count note files")), 1, 0) self.filterForm.addWidget(QLabel(self.tr("Hide zero word count")), 2, 0) self.filterForm.addWidget(QLabel(self.tr("Hide negative word count")), 3, 0) self.filterForm.addWidget(QLabel(self.tr("Group entries by day")), 4, 0) self.filterForm.addWidget(QLabel(self.tr("Show idle time")), 5, 0) self.filterForm.addWidget(self.incNovel, 0, 1) self.filterForm.addWidget(self.incNotes, 1, 1) self.filterForm.addWidget(self.hideZeros, 2, 1) self.filterForm.addWidget(self.hideNegative, 3, 1) self.filterForm.addWidget(self.groupByDay, 4, 1) self.filterForm.addWidget(self.showIdleTime, 5, 1) self.filterForm.setRowStretch(6, 1) # Settings self.histMax = QSpinBox(self) self.histMax.setMinimum(100) self.histMax.setMaximum(100000) self.histMax.setSingleStep(100) self.histMax.setValue( pOptions.getInt("GuiWritingStats", "histMax", 2000) ) self.histMax.valueChanged.connect(self._updateListBox) self.optsBox = QHBoxLayout() self.optsBox.addStretch(1) self.optsBox.addWidget(QLabel(self.tr("Word count cap for the histogram")), 0) self.optsBox.addWidget(self.histMax, 0) # Buttons self.buttonBox = QDialogButtonBox() self.buttonBox.rejected.connect(self._doClose) self.btnClose = self.buttonBox.addButton(QDialogButtonBox.Close) self.btnClose.setAutoDefault(False) self.btnSave = self.buttonBox.addButton(self.tr("Save As"), QDialogButtonBox.ActionRole) self.btnSave.setAutoDefault(False) self.saveMenu = QMenu(self) self.btnSave.setMenu(self.saveMenu) self.saveJSON = QAction(self.tr("JSON Data File (.json)"), self) self.saveJSON.triggered.connect(lambda: self._saveData(self.FMT_JSON)) self.saveMenu.addAction(self.saveJSON) self.saveCSV = QAction(self.tr("CSV Data File (.csv)"), self) self.saveCSV.triggered.connect(lambda: self._saveData(self.FMT_CSV)) self.saveMenu.addAction(self.saveCSV) # Assemble self.outerBox = QGridLayout() self.outerBox.addWidget(self.listBox, 0, 0, 1, 2) self.outerBox.addLayout(self.optsBox, 1, 0, 1, 2) self.outerBox.addWidget(self.infoBox, 2, 0) self.outerBox.addWidget(self.filterBox, 2, 1) self.outerBox.addWidget(self.buttonBox, 3, 0, 1, 2) self.outerBox.setRowStretch(0, 1) self.setLayout(self.outerBox) logger.debug("GuiWritingStats initialisation complete") return def populateGUI(self): """Populate list box with data from the log file. """ qApp.setOverrideCursor(QCursor(Qt.WaitCursor)) self._loadLogFile() self._updateListBox() qApp.restoreOverrideCursor() return ## # Slots ## def _doClose(self): """Save the state of the window, clear cache, end close. """ self.logData = [] winWidth = self.mainConf.rpxInt(self.width()) winHeight = self.mainConf.rpxInt(self.height()) widthCol0 = self.mainConf.rpxInt(self.listBox.columnWidth(0)) widthCol1 = self.mainConf.rpxInt(self.listBox.columnWidth(1)) widthCol2 = self.mainConf.rpxInt(self.listBox.columnWidth(2)) widthCol3 = self.mainConf.rpxInt(self.listBox.columnWidth(3)) sortCol = self.listBox.sortColumn() sortOrder = self.listBox.header().sortIndicatorOrder() incNovel = self.incNovel.isChecked() incNotes = self.incNotes.isChecked() hideZeros = self.hideZeros.isChecked() hideNegative = self.hideNegative.isChecked() groupByDay = self.groupByDay.isChecked() showIdleTime = self.showIdleTime.isChecked() histMax = self.histMax.value() pOptions = self.theProject.options pOptions.setValue("GuiWritingStats", "winWidth", winWidth) pOptions.setValue("GuiWritingStats", "winHeight", winHeight) pOptions.setValue("GuiWritingStats", "widthCol0", widthCol0) pOptions.setValue("GuiWritingStats", "widthCol1", widthCol1) pOptions.setValue("GuiWritingStats", "widthCol2", widthCol2) pOptions.setValue("GuiWritingStats", "widthCol3", widthCol3) pOptions.setValue("GuiWritingStats", "sortCol", sortCol) pOptions.setValue("GuiWritingStats", "sortOrder", sortOrder) pOptions.setValue("GuiWritingStats", "incNovel", incNovel) pOptions.setValue("GuiWritingStats", "incNotes", incNotes) pOptions.setValue("GuiWritingStats", "hideZeros", hideZeros) pOptions.setValue("GuiWritingStats", "hideNegative", hideNegative) pOptions.setValue("GuiWritingStats", "groupByDay", groupByDay) pOptions.setValue("GuiWritingStats", "showIdleTime", showIdleTime) pOptions.setValue("GuiWritingStats", "histMax", histMax) pOptions.saveSettings() self.close() return def _saveData(self, dataFmt): """Save the content of the list box to a file. """ fileExt = "" textFmt = "" if dataFmt == self.FMT_JSON: fileExt = "json" textFmt = self.tr("JSON Data File") elif dataFmt == self.FMT_CSV: fileExt = "csv" textFmt = self.tr("CSV Data File") else: return False # Generate the file name saveDir = self.mainConf.lastPath if not os.path.isdir(saveDir): saveDir = os.path.expanduser("~") fileName = "sessionStats.%s" % fileExt savePath = os.path.join(saveDir, fileName) savePath, _ = QFileDialog.getSaveFileName( self, self.tr("Save Data As"), savePath, "%s (*.%s)" % (textFmt, fileExt) ) if not savePath: return False self.mainConf.setLastPath(savePath) # Do the actual writing wSuccess = False errMsg = "" try: with open(savePath, mode="w", encoding="utf-8") as outFile: if dataFmt == self.FMT_JSON: jsonData = [] for _, sD, tT, wD, wA, wB, tI in self.filterData: jsonData.append({ "date": sD, "length": tT, "newWords": wD, "novelWords": wA, "noteWords": wB, "idleTime": tI, }) json.dump(jsonData, outFile, indent=2) wSuccess = True if dataFmt == self.FMT_CSV: outFile.write( '"Date","Length (sec)","Words Changed",' '"Novel Words","Note Words","Idle Time (sec)"\n' ) for _, sD, tT, wD, wA, wB, tI in self.filterData: outFile.write(f'"{sD}",{tT:.0f},{wD},{wA},{wB},{tI}\n') wSuccess = True except Exception as exc: errMsg = formatException(exc) wSuccess = False # Report to user if wSuccess: self.mainGui.makeAlert([ self.tr("{0} file successfully written to:").format(textFmt), savePath ], nwAlert.INFO) else: self.mainGui.makeAlert([ self.tr("Failed to write {0} file.").format(textFmt), errMsg ], nwAlert.ERROR) return wSuccess ## # Internal Functions ## def _loadLogFile(self): """Load the content of the log file into a buffer. """ logger.debug("Loading session log file") self.logData = [] self.wordOffset = 0 ttNovel = 0 ttNotes = 0 ttTime = 0 ttIdle = 0 logFile = os.path.join(self.theProject.projMeta, nwFiles.SESS_STATS) if not os.path.isfile(logFile): logger.info("This project has no writing stats logfile") return False try: with open(logFile, mode="r", encoding="utf-8") as inFile: for inLine in inFile: if inLine.startswith("#"): if inLine.startswith("# Offset"): self.wordOffset = checkInt(inLine[9:].strip(), 0) logger.verbose( "Initial word count when log was started is %d" % self.wordOffset ) continue inData = inLine.split() if len(inData) < 6: continue dStart = datetime.fromisoformat(" ".join(inData[0:2])) dEnd = datetime.fromisoformat(" ".join(inData[2:4])) sIdle = 0 if len(inData) > 6: sIdle = checkInt(inData[6], 0) tDiff = dEnd - dStart sDiff = tDiff.total_seconds() ttTime += sDiff ttIdle += sIdle wcNovel = int(inData[4]) wcNotes = int(inData[5]) ttNovel = wcNovel ttNotes = wcNotes self.logData.append((dStart, sDiff, wcNovel, wcNotes, sIdle)) except Exception as exc: self.mainGui.makeAlert(self.tr( "Failed to read session log file." ), nwAlert.ERROR, exception=exc) return False ttWords = ttNovel + ttNotes self.labelTotal.setText(formatTime(round(ttTime))) self.labelIdleT.setText(formatTime(round(ttIdle))) self.novelWords.setText(f"{ttNovel:n}") self.notesWords.setText(f"{ttNotes:n}") self.totalWords.setText(f"{ttWords:n}") return True ## # Slots ## def _updateListBox(self): """Load/reload the content of the list box. """ self.listBox.clear() self.timeFilter = 0.0 incNovel = self.incNovel.isChecked() incNotes = self.incNotes.isChecked() hideZeros = self.hideZeros.isChecked() hideNegative = self.hideNegative.isChecked() groupByDay = self.groupByDay.isChecked() histMax = self.histMax.value() # Group the data if groupByDay: tempData = [] sessDate = None sessTime = 0 sessIdle = 0 lstNovel = 0 lstNotes = 0 for n, (dStart, sDiff, wcNovel, wcNotes, sIdle) in enumerate(self.logData): if n == 0: sessDate = dStart.date() if sessDate != dStart.date(): tempData.append((sessDate, sessTime, lstNovel, lstNotes, sessIdle)) sessDate = dStart.date() sessTime = sDiff sessIdle = sIdle lstNovel = wcNovel lstNotes = wcNotes else: sessTime += sDiff sessIdle += sIdle lstNovel = wcNovel lstNotes = wcNotes if sessDate is not None: tempData.append((sessDate, sessTime, lstNovel, lstNotes, sessIdle)) else: tempData = self.logData # Calculate Word Diff self.filterData = [] pcTotal = 0 listMax = 0 isFirst = True for dStart, sDiff, wcNovel, wcNotes, sIdle in tempData: wcTotal = 0 if incNovel: wcTotal += wcNovel if incNotes: wcTotal += wcNotes dwTotal = wcTotal - pcTotal if hideZeros and dwTotal == 0: continue if hideNegative and dwTotal < 0: pcTotal = wcTotal continue if isFirst: # Subtract the offset from the first list entry dwTotal -= self.wordOffset dwTotal = max(dwTotal, 1) # Don't go zero or negative isFirst = False if groupByDay: sStart = dStart.strftime(nwConst.FMT_DSTAMP) else: sStart = dStart.strftime(nwConst.FMT_TSTAMP) self.filterData.append((dStart, sStart, sDiff, dwTotal, wcNovel, wcNotes, sIdle)) listMax = min(max(listMax, dwTotal), histMax) pcTotal = wcTotal # Populate the list showIdleTime = self.showIdleTime.isChecked() for _, sStart, sDiff, nWords, _, _, sIdle in self.filterData: if showIdleTime: idleEntry = formatTime(sIdle) else: sRatio = sIdle/sDiff if sDiff > 0.0 else 0.0 idleEntry = "%d %%" % round(100.0 * sRatio) newItem = QTreeWidgetItem() newItem.setText(self.C_TIME, sStart) newItem.setText(self.C_LENGTH, formatTime(round(sDiff))) newItem.setText(self.C_IDLE, idleEntry) newItem.setText(self.C_COUNT, f"{nWords:n}") if nWords > 0 and listMax > 0: theBar = self.barImage.scaled( int(200*min(nWords, histMax)/listMax), self.barHeight, Qt.IgnoreAspectRatio, Qt.FastTransformation ) newItem.setData(self.C_BAR, Qt.DecorationRole, theBar) newItem.setTextAlignment(self.C_LENGTH, Qt.AlignRight) newItem.setTextAlignment(self.C_IDLE, Qt.AlignRight) newItem.setTextAlignment(self.C_COUNT, Qt.AlignRight) newItem.setTextAlignment(self.C_BAR, Qt.AlignLeft | Qt.AlignVCenter) newItem.setFont(self.C_TIME, self.mainTheme.guiFontFixed) newItem.setFont(self.C_LENGTH, self.mainTheme.guiFontFixed) newItem.setFont(self.C_COUNT, self.mainTheme.guiFontFixed) if showIdleTime: newItem.setFont(self.C_IDLE, self.mainTheme.guiFontFixed) else: newItem.setFont(self.C_IDLE, self.mainTheme.guiFont) self.listBox.addTopLevelItem(newItem) self.timeFilter += sDiff self.labelFilter.setText(formatTime(round(self.timeFilter))) return True
def __init__(self): if version_info[0] == 3: super().__init__() else: super(SurveyWindow, self).__init__() # Establish basic window shape self.setWindowTitle('Survey') self.setStyleSheet('background-color: rgb(255,180,188);') self.output = "" self.layout = QVBoxLayout() self.setLayout(self.layout) # Alteration on BRCA1 in1label = QLabel() in1label.setText('Do you have an inherited alteration on the BRCA1 ' 'gene?') self.inherit1ComboBox = QComboBox() self.inherit1ComboBox.setStyleSheet('background-color: white;') self.inherit1ComboBox.addItems(['', 'Yes', 'No', 'I don\'t know']) brca1layout = QHBoxLayout() brca1layout.addWidget(in1label) brca1layout.addWidget(self.inherit1ComboBox) self.layout.addLayout(brca1layout) # self.layout.addSpace(15) # Alteration on BRCA2 in2label = QLabel() in2label.setText('Do you have an inherited alteration on the BRCA2 ' 'gene?') self.inherit2ComboBox = QComboBox() self.inherit2ComboBox.setStyleSheet('background-color: white;') self.inherit2ComboBox.addItems(['', 'Yes', 'No', 'I don\'t know']) brca2layout = QHBoxLayout() brca2layout.addWidget(in2label) brca2layout.addWidget(self.inherit2ComboBox) self.layout.addLayout(brca2layout) # Ethnicity ethlabel = QLabel() ethlabel.setText('What is your ethnicity?') self.ethComboBox = QComboBox() self.ethComboBox.setStyleSheet('background-color: white;') self.ethComboBox.addItems([ '', 'White', 'Hispanic', 'Asian/Pacific Islander', 'Black', 'Other' ]) ethlayout = QHBoxLayout() ethlayout.addWidget(ethlabel) ethlayout.addWidget(self.ethComboBox) self.layout.addLayout(ethlayout) # Age agelabel = QLabel() agelabel.setText('What range best represents your age?') self.ageComboBox = QComboBox() self.ageComboBox.setStyleSheet('background-color: white;') self.ageComboBox.addItems([ '', '18 or younger', '19-29', '30-39', '40-50', '51-60', '61-70', '70+' ]) agelayout = QHBoxLayout() agelayout.addWidget(agelabel) agelayout.addWidget(self.ageComboBox) self.layout.addLayout(agelayout) # Menstruation menslabel = QLabel() menslabel.setText('Did you start menstruation before 12 years old?') self.mensComboBox = QComboBox() self.mensComboBox.setStyleSheet('background-color: white;') self.mensComboBox.addItems(['', 'Yes', 'No', 'Does not apply to me']) menslayout = QHBoxLayout() menslayout.addWidget(menslabel) menslayout.addWidget(self.mensComboBox) self.layout.addLayout(menslayout) # Menopause menolabel = QLabel() menolabel.setText('Did you begin menopause after age 55?') self.menoComboBox = QComboBox() self.menoComboBox.setStyleSheet('background-color: white;') self.menoComboBox.addItems(['', 'Yes', 'No', 'Does not apply to me']) menolayout = QHBoxLayout() menolayout.addWidget(menolabel) menolayout.addWidget(self.menoComboBox) self.layout.addLayout(menolayout) # HRT chrtlabel = QLabel() chrtlabel.setText('Have you taken combination hormone replacement ' 'therapy, even for a short time?') self.chrtComboBox = QComboBox() self.chrtComboBox.setStyleSheet('background-color: white;') self.chrtComboBox.addItems(['', 'Yes', 'No']) chrtlayout = QHBoxLayout() chrtlayout.addWidget(chrtlabel) chrtlayout.addWidget(self.chrtComboBox) self.layout.addLayout(chrtlayout) # EHRT ehrtlabel = QLabel() ehrtlabel.setText('Have you taken estrogen hormone replacement therapy' ' for 10 or more years?') self.ehrtComboBox = QComboBox() self.ehrtComboBox.setStyleSheet('background-color: white;') self.ehrtComboBox.addItems(['', 'Yes', 'No']) ehrtlayout = QHBoxLayout() ehrtlayout.addWidget(ehrtlabel) ehrtlayout.addWidget(self.ehrtComboBox) self.layout.addLayout(ehrtlayout) # des deslabel = QLabel() deslabel.setText('Have you taken diethylstillbestrol (DES)?') self.desComboBox = QComboBox() self.desComboBox.setStyleSheet('background-color: white;') self.desComboBox.addItems(['', 'Yes', 'No', 'I don\'t know']) deslayout = QHBoxLayout() deslayout.addWidget(deslabel) deslayout.addWidget(self.desComboBox) self.layout.addLayout(deslayout) # mothers des mdeslabel = QLabel() mdeslabel.setText('Has your mother taken diethylstillbestrol (DES) ' 'between 1940-1971?') self.mdesComboBox = QComboBox() self.mdesComboBox.setStyleSheet('background-color: white;') self.mdesComboBox.addItems(['', 'Yes', 'No', 'I don\'t know']) mdeslayout = QHBoxLayout() mdeslayout.addWidget(mdeslabel) mdeslayout.addWidget(self.mdesComboBox) self.layout.addLayout(mdeslayout) # dense tissue pretlabel = QLabel() pretlabel.setText('Do you have dense breast tissue, and at what age?') self.pretComboBox = QComboBox() self.pretComboBox.setStyleSheet('background-color: white;') self.pretComboBox.addItems( ['', 'Premenopausal', 'Postmenopausal', 'No', 'I don\'t know']) pretlayout = QHBoxLayout() pretlayout.addWidget(pretlabel) pretlayout.addWidget(self.pretComboBox) self.layout.addLayout(pretlayout) # Children chilabel = QLabel() chilabel.setText('When did you give birth to your first child?') self.chiComboBox = QComboBox() self.chiComboBox.setStyleSheet('background-color: white;') self.chiComboBox.addItems( ['', 'before 20', '21-34', 'After 35', 'Never had children']) chilayout = QHBoxLayout() chilayout.addWidget(chilabel) chilayout.addWidget(self.chiComboBox) self.layout.addLayout(chilayout) canlabel = QLabel() canlabel.setText( 'How many of your close relatives have had breast, ovarian, ' 'or prostate cancer?') self.canComboBox = QComboBox() self.canComboBox.setStyleSheet('background-color: white;') self.canComboBox.addItems(['', '0', '1', '2', '3', '4 or more']) canlayout = QHBoxLayout() canlayout.addWidget(canlabel) canlayout.addWidget(self.canComboBox) self.layout.addLayout(canlayout) # End self.buttonBox = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel) self.buttonBox.setStyleSheet('background-color: white;') self.buttonBox.accepted.connect(self.submit_it) self.buttonBox.rejected.connect(self.reject) self.layout.addWidget(self.buttonBox)
class DeleteDialog(QDialog): new_infos = pyqtSignal(object) def __init__(self, infos, parent=None): super(DeleteDialog, self).__init__(parent) self.infos = infos self.out = [] self.initUI() self.setStyleSheet(dialog_qss_style) def set_file_icon(self, name): suffix = name.split(".")[-1] ico_path = "./icon/{}.gif".format(suffix) if os.path.isfile(ico_path): return QIcon(ico_path) else: return QIcon("./icon/file.ico") def initUI(self): self.setWindowTitle("确认删除") self.setWindowIcon(QIcon("./icon/delete.ico")) self.layout = QVBoxLayout() self.list_view = QListView() self.list_view.setViewMode(QListView.ListMode) # 列表 self.slm = QStandardItem() self.model = QStandardItemModel() max_len = 10 count = 0 for i in self.infos: if i[2]: # 有大小,是文件 self.model.appendRow( QStandardItem(self.set_file_icon(i[1]), i[1])) else: self.model.appendRow( QStandardItem(QIcon("./icon/folder.gif"), i[1])) self.out.append({ 'fid': i[0], 'is_file': True if i[2] else False, 'name': i[1] }) # id,文件标示, 文件名 count += 1 if max_len < len(i[1]): # 使用最大文件名长度 max_len = len(i[1]) self.list_view.setModel(self.model) self.lb_name = QLabel("尝试删除以下{}个文件(夹):".format(count)) self.buttonBox = QDialogButtonBox() self.buttonBox.setOrientation(Qt.Horizontal) self.buttonBox.setStandardButtons(QDialogButtonBox.Ok | QDialogButtonBox.Cancel) self.buttonBox.button(QDialogButtonBox.Ok).setText("确定") self.buttonBox.button(QDialogButtonBox.Cancel).setText("取消") self.layout.addWidget(self.lb_name) self.layout.addWidget(self.list_view) self.layout.addWidget(self.buttonBox) self.setLayout(self.layout) self.buttonBox.accepted.connect(self.btn_ok) self.buttonBox.accepted.connect(self.accept) self.buttonBox.rejected.connect(self.reject) self.setMinimumWidth(400) self.resize(int(max_len * 8), int(count * 34 + 60)) def btn_ok(self): self.new_infos.emit(self.out)
def maybeHideClose(bbox: QDialogButtonBox) -> None: if isMac: b = bbox.button(QDialogButtonBox.Close) if b: bbox.removeButton(b)
def showDialog(self, currentCard=None): if currentCard: self.did = currentCard.did elif mw._selectedDeck(): self.did = mw._selectedDeck()['id'] else: return if not self._getCardInfo(self.did): showInfo('Please select an Incremental Reading deck.') return dialog = QDialog(mw) layout = QVBoxLayout() self.cardListWidget = QListWidget() self.cardListWidget.setAlternatingRowColors(True) self.cardListWidget.setSelectionMode( QAbstractItemView.ExtendedSelection) self.cardListWidget.setWordWrap(True) self.cardListWidget.itemDoubleClicked.connect(lambda: showBrowser( self.cardListWidget.currentItem().data(Qt.UserRole)['nid'])) self._updateListItems() upButton = QPushButton('Up') upButton.clicked.connect(self._moveUp) downButton = QPushButton('Down') downButton.clicked.connect(self._moveDown) topButton = QPushButton('Top') topButton.clicked.connect(self._moveToTop) bottomButton = QPushButton('Bottom') bottomButton.clicked.connect(self._moveToBottom) randomizeButton = QPushButton('Randomize') randomizeButton.clicked.connect(self._randomize) controlsLayout = QHBoxLayout() controlsLayout.addWidget(topButton) controlsLayout.addWidget(upButton) controlsLayout.addWidget(downButton) controlsLayout.addWidget(bottomButton) controlsLayout.addStretch() controlsLayout.addWidget(randomizeButton) buttonBox = QDialogButtonBox(QDialogButtonBox.Close | QDialogButtonBox.Save) buttonBox.accepted.connect(dialog.accept) buttonBox.rejected.connect(dialog.reject) buttonBox.setOrientation(Qt.Horizontal) layout.addLayout(controlsLayout) layout.addWidget(self.cardListWidget) layout.addWidget(buttonBox) dialog.setLayout(layout) dialog.setWindowModality(Qt.WindowModal) dialog.resize(500, 500) choice = dialog.exec_() if choice == 1: cids = [] for i in range(self.cardListWidget.count()): card = self.cardListWidget.item(i).data(Qt.UserRole) cids.append(card['id']) self.reorder(cids)
def initUI(self): self.setWindowTitle("设置") logo = QLabel() # logo logo.setPixmap(QPixmap("./icon/logo2.gif")) logo.setStyleSheet("background-color:rgb(255,255,255);") logo.setAlignment(Qt.AlignCenter) self.rar_tool_lb = QLabel("rar路径") # rar路径 # self.rar_tool_var = MyLineEdit(self) # self.rar_tool_var.clicked.connect(self.set_rar_path) # self.rar_tool_var.setPlaceholderText("用于大文件分卷压缩与分卷合并") # self.rar_tool_var.setToolTip("用于大文件分卷压缩与分卷合并") self.download_threads_lb = QLabel("同时下载文件数") # about self.download_threads_var = QLineEdit() self.download_threads_var.setPlaceholderText("范围:1-9") self.download_threads_var.setToolTip("范围:1-9") self.download_threads_var.setInputMask("D") self.max_size_lb = QLabel("分卷大小(MB)") self.max_size_var = QLineEdit() self.max_size_var.setPlaceholderText("普通用户最大100,vip用户根据具体情况设置") self.max_size_var.setToolTip("普通用户最大100,vip用户根据具体情况设置") self.max_size_var.setInputMask("D99") self.timeout_lb = QLabel("请求超时(秒)") self.timeout_var = QLineEdit() self.timeout_var.setPlaceholderText("范围:1-99") self.timeout_var.setToolTip("范围:1-99") self.timeout_var.setInputMask("D9") self.guise_suffix_lb = QLabel("假后缀") self.guise_suffix_var = QLineEdit() self.guise_suffix_var.setPlaceholderText("让不支持的文件类型改成该后缀名,蒙混过关") self.guise_suffix_var.setToolTip("让不支持的文件类型改成该后缀名,蒙混过关") self.rar_part_name_lb = QLabel("rar分卷名") self.rar_part_name_var = QLineEdit() self.rar_part_name_var.setPlaceholderText("大文件分卷标识字符串,对抗封禁") self.rar_part_name_var.setToolTip("大文件分卷标识字符串,对抗封禁") self.dl_path_lb = QLabel("下载保存路径") self.dl_path_var = MyLineEdit(self) self.dl_path_var.clicked.connect(self.set_download_path) self.time_fmt_box = QCheckBox("使用[年-月-日]时间格式") self.time_fmt_box.toggle() self.time_fmt_box.stateChanged.connect(self.change_time_fmt) buttonBox = QDialogButtonBox() buttonBox.setOrientation(Qt.Horizontal) buttonBox.setStandardButtons(QDialogButtonBox.Reset | QDialogButtonBox.Save | QDialogButtonBox.Cancel) buttonBox.button(QDialogButtonBox.Reset).setText("重置") buttonBox.button(QDialogButtonBox.Save).setText("保存") buttonBox.button(QDialogButtonBox.Cancel).setText("取消") buttonBox.button(QDialogButtonBox.Reset).clicked.connect( lambda: self.set_values(reset=True)) buttonBox.button(QDialogButtonBox.Save).clicked.connect(self.slot_save) buttonBox.rejected.connect(self.reject) form = QFormLayout() form.setSpacing(10) form.addRow(self.download_threads_lb, self.download_threads_var) form.addRow(self.timeout_lb, self.timeout_var) form.addRow(self.max_size_lb, self.max_size_var) # form.addRow(self.guise_suffix_lb, self.guise_suffix_var) # form.addRow(self.rar_part_name_lb, self.rar_part_name_var) # form.addRow(self.rar_tool_lb, self.rar_tool_var) form.addRow(self.dl_path_lb, self.dl_path_var) vbox = QVBoxLayout() vbox.addWidget(logo) vbox.addStretch(1) vbox.addLayout(form) vbox.addStretch(1) vbox.addWidget(self.time_fmt_box) vbox.addStretch(1) vbox.addWidget(buttonBox) self.setLayout(vbox) self.setMinimumWidth(500)
class MoveFileDialog(QDialog): '''移动文件对话框''' new_infos = pyqtSignal(object) def __init__(self, infos, all_dirs_dict, parent=None): super(MoveFileDialog, self).__init__(parent) self.infos = infos self.dirs = all_dirs_dict self.initUI() self.setStyleSheet(dialog_qss_style) def initUI(self): for i in self.infos: if not i[2]: # 非文件 self.infos.remove(i) self.setWindowTitle("移动文件") self.setWindowIcon(QIcon("./icon/move.ico")) self.lb_name = QLabel() self.lb_name.setText("文件路径:") self.lb_name.setAlignment(Qt.AlignRight | Qt.AlignTrailing | Qt.AlignVCenter) self.tx_name = QLineEdit() names = " | ".join([i[1] for i in self.infos]) names_tip = "\n".join([i[1] for i in self.infos]) self.tx_name.setText(names) self.tx_name.setToolTip(names_tip) # 只读 self.tx_name.setFocusPolicy(Qt.NoFocus) self.tx_name.setReadOnly(True) self.lb_new_path = QLabel() self.lb_new_path.setText("目标文件夹:") self.lb_new_path.setAlignment(Qt.AlignRight | Qt.AlignTrailing | Qt.AlignVCenter) self.tx_new_path = QComboBox() f_icon = QIcon("./icon/folder.gif") for f_name, fid in self.dirs.items(): if len(f_name) > 50: # 防止文件夹名字过长? f_name = f_name[:47] + "..." self.tx_new_path.addItem(f_icon, "id:{:>8},name:{}".format(fid, f_name)) self.buttonBox = QDialogButtonBox() self.buttonBox.setOrientation(Qt.Horizontal) self.buttonBox.setStandardButtons(QDialogButtonBox.Ok | QDialogButtonBox.Cancel) self.buttonBox.button(QDialogButtonBox.Ok).setText("确定") self.buttonBox.button(QDialogButtonBox.Cancel).setText("取消") self.grid = QGridLayout() self.grid.setSpacing(10) self.grid.addWidget(self.lb_name, 1, 0) self.grid.addWidget(self.tx_name, 1, 1) self.grid.addWidget(self.lb_new_path, 2, 0) self.grid.addWidget(self.tx_new_path, 2, 1) self.grid.addWidget(self.buttonBox, 3, 0, 1, 2) self.setLayout(self.grid) self.buttonBox.accepted.connect(self.btn_ok) self.buttonBox.accepted.connect(self.accept) self.buttonBox.rejected.connect(self.reject) self.setMinimumWidth(280) def btn_ok(self): selected = self.tx_new_path.currentText().split(",")[0].split(":")[1] self.new_infos.emit([(info[0], selected, info[1]) for info in self.infos])
def __init__(self, parent, url, text, wait_time=150, monitor=False): """ Parameters ---------- parent The parent of this dialog window. url: str The url of the page to check for 'text'. text: str The text to search for on the page. wait_time: int The time to wait for the text to be present. default = 150 seconds Returns ------- QDialog.Accepted if the text is found. QDialog.Rejected if dialog is cancelled. WaitForTextOnPage.WAIT_TIME_EXPIRED if 'wait_time' has elapsed. """ super().__init__(parent) settings = QSettings() self.url = url self.text = text self.wait_time = wait_time self.monitor = monitor self.is_running = False self.request_timeout = int(settings.value("main/request_timeout")) self.check_interval = 10 self.check_interval_remaining = self.check_interval self.setWindowTitle("Low Amperage Boot") self.main_layout = QVBoxLayout() self.serial_label_layout = QHBoxLayout() self.message_label_layout = QHBoxLayout() self.lbl_hourglass = QLabel() self.movie_hourglass = QMovie( r"laboot\resources\images\animations\activity_green_fast.gif") self.lbl_hourglass.setMovie(self.movie_hourglass) self.lbl_hourglass.setAlignment(Qt.AlignHCenter) self.lbl_serial_detect = QLabel( f"Serial number {self.text} was not detected.") font = self.lbl_serial_detect.font() font.setPointSize(10) self.lbl_serial_detect.setFont(font) self.lbl_serial_detect.setAlignment(Qt.AlignHCenter) text = ("Monitoring collector for refresh of serial numbers." if monitor else "Waiting for collector to refresh serial numbers.") self.lbl_main_message = QLabel(text) self.lbl_main_message.setFont(font) self.lbl_main_message.setAlignment(Qt.AlignHCenter) self.lbl_separator = QLabel("_" * 50) self.lbl_separator.setAlignment(Qt.AlignHCenter) btns = QDialogButtonBox() btns.setStandardButtons(QDialogButtonBox.Cancel) btns.rejected.connect(lambda: self.done(WaitForTextOnPage.REJECTED)) self.main_layout.addWidget(self.lbl_hourglass, Qt.AlignHCenter) self.serial_label_layout.addWidget(self.lbl_serial_detect, Qt.AlignCenter) self.main_layout.addLayout(self.serial_label_layout, stretch=1) self.message_label_layout.addWidget(self.lbl_main_message, Qt.AlignCenter) self.main_layout.addLayout(self.message_label_layout, stretch=1) self.main_layout.addWidget(self.lbl_separator, Qt.AlignCenter) self.main_layout.addWidget(btns) self.check_page_timer = QTimer(self) self.check_page_timer.timeout.connect(self._check_page) self.setLayout(self.main_layout)
def setupUi(self, Dialog): self.source_dir = '' self.result_dir = '' self.color_map = '' self.scale = '' self.CM =['AUTUMN','BONE','JET','WINTER','RAINBOW','OCEAN', 'SUMMER','SPRING','COOL','HSV','PINK','HOT'] self.dataList = [*range(12)] Dialog.setObjectName("Dialog") Dialog.resize(446, 316) self.buttonBox = QDialogButtonBox(Dialog) self.buttonBox.setGeometry(QRect(20, 250, 381, 32)) self.buttonBox.setOrientation(Qt.Horizontal) self.buttonBox.setStandardButtons(QDialogButtonBox.Cancel|QDialogButtonBox.Ok) self.buttonBox.setObjectName("buttonBox") self.gridLayoutWidget = QWidget(Dialog) self.gridLayoutWidget.setGeometry(QRect(20, 10, 381, 211)) self.gridLayoutWidget.setObjectName("gridLayoutWidget") self.gridLayout = QGridLayout(self.gridLayoutWidget) self.gridLayout.setContentsMargins(0, 0, 0, 0) self.gridLayout.setObjectName("gridLayout") self.sourceDirectoryLineEdit = QLineEdit(self.gridLayoutWidget) self.sourceDirectoryLineEdit.setObjectName("sourceDirectoryLineEdit") self.gridLayout.addWidget(self.sourceDirectoryLineEdit, 0, 1, 1, 1) self.resultDirectoryLineEdit = QLineEdit(self.gridLayoutWidget) self.resultDirectoryLineEdit.setObjectName("resultDirectoryLineEdit") self.gridLayout.addWidget(self.resultDirectoryLineEdit, 1, 1, 1, 1) self.resultsDirectoryLabel = QLabel(self.gridLayoutWidget) self.resultsDirectoryLabel.setObjectName("resultsDirectoryLabel") self.gridLayout.addWidget(self.resultsDirectoryLabel, 1, 0, 1, 1) self.sourceDirectoryToolButton = QToolButton(self.gridLayoutWidget) self.sourceDirectoryToolButton.setObjectName("sourceDirectoryToolButton") self.gridLayout.addWidget(self.sourceDirectoryToolButton, 0, 2, 1, 1) self.resultDirectoryToolButton = QToolButton(self.gridLayoutWidget) self.resultDirectoryToolButton.setObjectName("resultDirectoryToolButton") self.gridLayout.addWidget(self.resultDirectoryToolButton, 1, 2, 1, 1) self.scaleSpinBox = QDoubleSpinBox(self.gridLayoutWidget) self.scaleSpinBox.setMaximumSize(QSize(50, 20)) font = QFont() font.setBold(True) font.setWeight(75) self.scaleSpinBox.setFont(font) self.scaleSpinBox.setMinimum(0.01) self.scaleSpinBox.setMaximum(10.0) self.scaleSpinBox.setSingleStep(0.05) self.scaleSpinBox.setProperty("value", 1.0) self.scaleSpinBox.setObjectName("scaleSpinBox") self.gridLayout.addWidget(self.scaleSpinBox, 4, 1, 1, 1) self.sourceDirectoryLabel = QLabel(self.gridLayoutWidget) self.sourceDirectoryLabel.setObjectName("sourceDirectoryLabel") self.gridLayout.addWidget(self.sourceDirectoryLabel, 0, 0, 1, 1) self.scaleLabel = QLabel(self.gridLayoutWidget) self.scaleLabel.setObjectName("scaleLabel") self.gridLayout.addWidget(self.scaleLabel, 4, 0, 1, 1) self.colorMapLabel = QLabel(self.gridLayoutWidget) self.colorMapLabel.setObjectName("colorMapLabel") self.gridLayout.addWidget(self.colorMapLabel, 2, 0, 1, 1) self.CMcomboBox = CheckableComboBox(self.gridLayoutWidget) self.CMcomboBox.setObjectName("CMcomboBox") self.gridLayout.addWidget(self.CMcomboBox, 2, 1, 1, 1) self.retranslateUi(Dialog) self.buttonBox.accepted.connect(self.acceptAndSave) self.buttonBox.rejected.connect(Dialog.reject) QMetaObject.connectSlotsByName(Dialog) self.sourceDirectoryToolButton.clicked.connect(self._source_dir_dialog) self.resultDirectoryToolButton.clicked.connect(self._result_dir_dialog) self.readINI()
def initUI(self): self.setWindowTitle("上传文件") self.setWindowIcon(QIcon("./icon/upload.ico")) self.logo = QLabel() self.logo.setPixmap(QPixmap("./icon/logo3.gif")) self.logo.setStyleSheet("background-color:rgb(0,153,255);") self.logo.setAlignment(Qt.AlignCenter) # btn 1 self.btn_chooseDir = QPushButton("选择文件夹", self) self.btn_chooseDir.setObjectName("btn_chooseDir") self.btn_chooseDir.setObjectName("btn_chooseDir") self.btn_chooseDir.setIcon(QIcon("./icon/folder.gif")) # btn 2 self.btn_chooseMutiFile = QPushButton("选择多文件", self) self.btn_chooseDir.setObjectName("btn_chooseMutiFile") self.btn_chooseMutiFile.setObjectName("btn_chooseMutiFile") self.btn_chooseMutiFile.setIcon(QIcon("./icon/file.ico")) # btn 3 self.btn_deleteSelect = QPushButton("移除", self) self.btn_deleteSelect.setObjectName("btn_deleteSelect") self.btn_deleteSelect.setIcon(QIcon("./icon/delete.ico")) # 列表 self.list_view = QListView(self) self.list_view.setViewMode(QListView.ListMode) self.slm = QStandardItem() self.model = QStandardItemModel() self.list_view.setModel(self.model) self.model.removeRows(0, self.model.rowCount()) # 清除旧的选择 self.list_view.setEditTriggers(QAbstractItemView.NoEditTriggers) self.list_view.setSelectionBehavior(QAbstractItemView.SelectRows) self.list_view.setSelectionMode(QAbstractItemView.ExtendedSelection) self.buttonBox = QDialogButtonBox() self.buttonBox.setOrientation(Qt.Horizontal) self.buttonBox.setStandardButtons(QDialogButtonBox.Ok | QDialogButtonBox.Cancel) self.buttonBox.button(QDialogButtonBox.Ok).setText("确定") self.buttonBox.button(QDialogButtonBox.Cancel).setText("取消") grid = QGridLayout() grid.setSpacing(10) grid.addWidget(self.logo, 1, 0, 1, 3) grid.addWidget(self.btn_chooseDir, 2, 0) grid.addWidget(self.btn_chooseMutiFile, 2, 2) grid.addWidget(self.list_view, 3, 0, 2, 3) grid.addWidget(self.btn_deleteSelect, 5, 0) grid.addWidget(self.buttonBox, 5, 1, 1, 2) self.setLayout(grid) self.setMinimumWidth(350) # 设置信号 self.btn_chooseDir.clicked.connect(self.slot_btn_chooseDir) self.btn_chooseMutiFile.clicked.connect(self.slot_btn_chooseMutiFile) self.btn_deleteSelect.clicked.connect(self.slot_btn_deleteSelect) self.buttonBox.accepted.connect(self.slot_btn_ok) self.buttonBox.accepted.connect(self.accept) self.buttonBox.rejected.connect(self.clear_old) self.buttonBox.rejected.connect(self.reject)
class Ui_INI_Dialog(object): def setupUi(self, Dialog): self.source_dir = '' self.result_dir = '' self.color_map = '' self.scale = '' self.CM =['AUTUMN','BONE','JET','WINTER','RAINBOW','OCEAN', 'SUMMER','SPRING','COOL','HSV','PINK','HOT'] self.dataList = [*range(12)] Dialog.setObjectName("Dialog") Dialog.resize(446, 316) self.buttonBox = QDialogButtonBox(Dialog) self.buttonBox.setGeometry(QRect(20, 250, 381, 32)) self.buttonBox.setOrientation(Qt.Horizontal) self.buttonBox.setStandardButtons(QDialogButtonBox.Cancel|QDialogButtonBox.Ok) self.buttonBox.setObjectName("buttonBox") self.gridLayoutWidget = QWidget(Dialog) self.gridLayoutWidget.setGeometry(QRect(20, 10, 381, 211)) self.gridLayoutWidget.setObjectName("gridLayoutWidget") self.gridLayout = QGridLayout(self.gridLayoutWidget) self.gridLayout.setContentsMargins(0, 0, 0, 0) self.gridLayout.setObjectName("gridLayout") self.sourceDirectoryLineEdit = QLineEdit(self.gridLayoutWidget) self.sourceDirectoryLineEdit.setObjectName("sourceDirectoryLineEdit") self.gridLayout.addWidget(self.sourceDirectoryLineEdit, 0, 1, 1, 1) self.resultDirectoryLineEdit = QLineEdit(self.gridLayoutWidget) self.resultDirectoryLineEdit.setObjectName("resultDirectoryLineEdit") self.gridLayout.addWidget(self.resultDirectoryLineEdit, 1, 1, 1, 1) self.resultsDirectoryLabel = QLabel(self.gridLayoutWidget) self.resultsDirectoryLabel.setObjectName("resultsDirectoryLabel") self.gridLayout.addWidget(self.resultsDirectoryLabel, 1, 0, 1, 1) self.sourceDirectoryToolButton = QToolButton(self.gridLayoutWidget) self.sourceDirectoryToolButton.setObjectName("sourceDirectoryToolButton") self.gridLayout.addWidget(self.sourceDirectoryToolButton, 0, 2, 1, 1) self.resultDirectoryToolButton = QToolButton(self.gridLayoutWidget) self.resultDirectoryToolButton.setObjectName("resultDirectoryToolButton") self.gridLayout.addWidget(self.resultDirectoryToolButton, 1, 2, 1, 1) self.scaleSpinBox = QDoubleSpinBox(self.gridLayoutWidget) self.scaleSpinBox.setMaximumSize(QSize(50, 20)) font = QFont() font.setBold(True) font.setWeight(75) self.scaleSpinBox.setFont(font) self.scaleSpinBox.setMinimum(0.01) self.scaleSpinBox.setMaximum(10.0) self.scaleSpinBox.setSingleStep(0.05) self.scaleSpinBox.setProperty("value", 1.0) self.scaleSpinBox.setObjectName("scaleSpinBox") self.gridLayout.addWidget(self.scaleSpinBox, 4, 1, 1, 1) self.sourceDirectoryLabel = QLabel(self.gridLayoutWidget) self.sourceDirectoryLabel.setObjectName("sourceDirectoryLabel") self.gridLayout.addWidget(self.sourceDirectoryLabel, 0, 0, 1, 1) self.scaleLabel = QLabel(self.gridLayoutWidget) self.scaleLabel.setObjectName("scaleLabel") self.gridLayout.addWidget(self.scaleLabel, 4, 0, 1, 1) self.colorMapLabel = QLabel(self.gridLayoutWidget) self.colorMapLabel.setObjectName("colorMapLabel") self.gridLayout.addWidget(self.colorMapLabel, 2, 0, 1, 1) self.CMcomboBox = CheckableComboBox(self.gridLayoutWidget) self.CMcomboBox.setObjectName("CMcomboBox") self.gridLayout.addWidget(self.CMcomboBox, 2, 1, 1, 1) self.retranslateUi(Dialog) self.buttonBox.accepted.connect(self.acceptAndSave) self.buttonBox.rejected.connect(Dialog.reject) QMetaObject.connectSlotsByName(Dialog) self.sourceDirectoryToolButton.clicked.connect(self._source_dir_dialog) self.resultDirectoryToolButton.clicked.connect(self._result_dir_dialog) self.readINI() def retranslateUi(self, Dialog): _translate = QCoreApplication.translate Dialog.setWindowTitle(_translate("Dialog", "Default Values")) self.resultsDirectoryLabel.setText(_translate("Dialog", "Results Directory")) self.sourceDirectoryToolButton.setText(_translate("Dialog", "...")) self.resultDirectoryToolButton.setText(_translate("Dialog", "...")) self.sourceDirectoryLabel.setText(_translate("Dialog", "Source Directory")) self.scaleLabel.setText(_translate("Dialog", "Scale")) self.colorMapLabel.setText(_translate("Dialog", "Default Color Map")) def acceptAndSave(self): source_dir = self.sourceDirectoryLineEdit.text() result_dir = self.resultDirectoryLineEdit.text() color_map = self.CMcomboBox.currentData() scale = str(self.scaleSpinBox.value()) f = open("elilik.ini", "w") f.write(f"source_dir : {source_dir}\n") f.write(f"result_dir : {result_dir}\n") f.write(f"color_map : {color_map}\n") f.write(f"scale : {scale}\n") f.close() msg = QMessageBox() msg.setIcon(QMessageBox.Information) msg.setText("Default values successfully updated!") msg.setWindowTitle("Saved") msg.setStandardButtons(QMessageBox.Ok) msg.exec_() def readINI(self): if os.path.exists("elilik.ini"): f = open("elilik.ini", "r") Lines = f.readlines() # Strips the newline character for line in Lines: l = line.strip() if "source_dir : " in l: self.source_dir = l.replace("source_dir : ","").strip() elif "result_dir : " in l: self.result_dir = l.replace("result_dir : ","").strip() elif "color_map : " in l: self.color_map = l.replace("color_map : ","").strip() elif "scale : " in l: self.scale = l.replace("scale : ","").strip() else: ... self.sourceDirectoryLineEdit.setText(self.source_dir) self.resultDirectoryLineEdit.setText(self.result_dir) self.scaleSpinBox.setValue(float(self.scale)) self.CMcomboBox.addItems(self.CM,None,self.color_map) def _source_dir_dialog(self): directory = str(QFileDialog.getExistingDirectory()) self.sourceDirectoryLineEdit.setText('{}'.format(directory)) def _result_dir_dialog(self): directory = str(QFileDialog.getExistingDirectory()) self.resultDirectoryLineEdit.setText('{}'.format(directory))
def initUI(self): self.setWindowTitle("上传文件") self.setWindowIcon(QIcon(SRC_DIR + "upload.ico")) self.logo = QLabel() self.logo.setPixmap(QPixmap(SRC_DIR + "logo3.gif")) self.logo.setStyleSheet("background-color:rgb(0,153,255);") self.logo.setAlignment(Qt.AlignCenter) # btn 1 self.btn_chooseDir = QPushButton("选择文件夹", self) self.btn_chooseDir.setObjectName("btn_chooseDir") self.btn_chooseDir.setObjectName("btn_chooseDir") self.btn_chooseDir.setIcon(QIcon(SRC_DIR + "folder.gif")) # btn 2 self.btn_chooseMultiFile = QPushButton("选择多文件", self) self.btn_chooseDir.setObjectName("btn_chooseMultiFile") self.btn_chooseMultiFile.setObjectName("btn_chooseMultiFile") self.btn_chooseMultiFile.setIcon(QIcon(SRC_DIR + "file.ico")) # btn 3 self.btn_deleteSelect = QPushButton("移除", self) self.btn_deleteSelect.setObjectName("btn_deleteSelect") self.btn_deleteSelect.setIcon(QIcon(SRC_DIR + "delete.ico")) self.btn_deleteSelect.setToolTip("按 Delete 移除选中文件") # 列表 self.list_view = MyListView() self.list_view.drop_files.connect(self.add_drop_files) self.list_view.setViewMode(QListView.ListMode) self.slm = QStandardItem() self.model = QStandardItemModel() self.list_view.setModel(self.model) self.model.removeRows(0, self.model.rowCount()) # 清除旧的选择 self.list_view.setEditTriggers(QAbstractItemView.NoEditTriggers) self.list_view.setSelectionBehavior(QAbstractItemView.SelectRows) self.list_view.setSelectionMode(QAbstractItemView.ExtendedSelection) self.buttonBox = QDialogButtonBox() self.buttonBox.setOrientation(Qt.Horizontal) self.buttonBox.setStandardButtons(QDialogButtonBox.Ok | QDialogButtonBox.Cancel) self.buttonBox.button(QDialogButtonBox.Ok).setText("确定") self.buttonBox.button(QDialogButtonBox.Cancel).setText("取消") vbox = QVBoxLayout() hbox_head = QHBoxLayout() hbox_button = QHBoxLayout() hbox_head.addWidget(self.btn_chooseDir) hbox_head.addStretch(1) hbox_head.addWidget(self.btn_chooseMultiFile) hbox_button.addWidget(self.btn_deleteSelect) hbox_button.addStretch(1) hbox_button.addWidget(self.buttonBox) vbox.addWidget(self.logo) vbox.addLayout(hbox_head) vbox.addWidget(self.list_view) vbox.addLayout(hbox_button) self.setLayout(vbox) self.setMinimumWidth(350) # 设置信号 self.btn_chooseDir.clicked.connect(self.slot_btn_chooseDir) self.btn_chooseMultiFile.clicked.connect(self.slot_btn_chooseMultiFile) self.btn_deleteSelect.clicked.connect(self.slot_btn_deleteSelect) self.buttonBox.accepted.connect(self.slot_btn_ok) self.buttonBox.accepted.connect(self.accept) self.buttonBox.rejected.connect(self.clear_old) self.buttonBox.rejected.connect(self.reject)
class RenameDialog(QDialog): out = pyqtSignal(object) def __init__(self, parent=None): super(RenameDialog, self).__init__(parent) self.infos = None self.min_width = 400 self.initUI() self.update_text() self.setStyleSheet(dialog_qss_style) def set_values(self, infos): self.infos = infos self.update_text() # 更新界面 def initUI(self): self.setWindowIcon(QIcon("./icon/desc.ico")) self.lb_name = QLabel() self.lb_name.setText("文件夹名:") self.lb_name.setAlignment(Qt.AlignRight | Qt.AlignTrailing | Qt.AlignVCenter) self.tx_name = QLineEdit() self.lb_desc = QLabel() self.tx_desc = QTextEdit() self.lb_desc.setText("描 述:") self.lb_desc.setAlignment(Qt.AlignRight | Qt.AlignTrailing | Qt.AlignVCenter) self.buttonBox = QDialogButtonBox() self.buttonBox.setOrientation(Qt.Horizontal) self.buttonBox.setStandardButtons(QDialogButtonBox.Ok | QDialogButtonBox.Cancel) self.buttonBox.button(QDialogButtonBox.Ok).setText("确定") self.buttonBox.button(QDialogButtonBox.Cancel).setText("取消") self.grid = QGridLayout() self.grid.setSpacing(10) self.grid.addWidget(self.lb_name, 1, 0) self.grid.addWidget(self.tx_name, 1, 1) self.grid.addWidget(self.lb_desc, 2, 0) self.grid.addWidget(self.tx_desc, 2, 1, 5, 1) self.grid.addWidget(self.buttonBox, 7, 1, 1, 1) self.setLayout(self.grid) self.buttonBox.accepted.connect(self.btn_ok) self.buttonBox.accepted.connect(self.accept) self.buttonBox.rejected.connect(self.reject) def update_text(self): if self.infos: self.buttonBox.button(QDialogButtonBox.Ok).setToolTip( "") # 去除新建文件夹影响 self.buttonBox.button(QDialogButtonBox.Ok).setEnabled( True) # 去除新建文件夹影响 self.setWindowTitle("修改文件夹名与描述") self.tx_name.setText(str(self.infos[1])) if self.infos[6]: self.tx_desc.setText(str(self.infos[6])) self.tx_desc.setToolTip('原描述:' + str(self.infos[6])) else: self.tx_desc.setText("无") self.tx_desc.setToolTip('') self.tx_desc.setPlaceholderText("无") self.min_width = len(str(self.infos[1])) * 8 if self.infos[2]: # 文件无法重命名,由 infos[2] size表示文件 self.setWindowTitle("修改文件描述") self.tx_name.setFocusPolicy(Qt.NoFocus) self.tx_name.setReadOnly(True) else: self.tx_name.setFocusPolicy(Qt.StrongFocus) self.tx_name.setReadOnly(False) else: self.setWindowTitle("新建文件夹") self.tx_name.setText("") self.buttonBox.button(QDialogButtonBox.Ok).setEnabled(False) self.buttonBox.button(QDialogButtonBox.Ok).setToolTip("请先输入文件名!") self.tx_name.textChanged.connect(self.slot_new_ok_btn) self.tx_name.setPlaceholderText("不支持空格,如有会被自动替换成 _") self.tx_name.setFocusPolicy(Qt.StrongFocus) self.tx_name.setReadOnly(False) self.tx_desc.setPlaceholderText("可选项,建议160字数以内。") if self.min_width < 400: self.min_width = 400 self.resize(self.min_width, 200) def slot_new_ok_btn(self): """新建文件夹槽函数""" self.buttonBox.button(QDialogButtonBox.Ok).setEnabled(True) self.buttonBox.button(QDialogButtonBox.Ok).setToolTip("") def btn_ok(self): new_name = self.tx_name.text() new_desc = self.tx_desc.toPlainText() if not self.infos: # 在 work_id 新建文件夹 if new_name: self.out.emit(("new", "", new_name, new_desc)) else: return elif new_name != self.infos[1] or new_desc != self.infos[6]: if self.infos[2]: # 文件 self.out.emit(("file", self.infos[0], new_name, new_desc)) else: self.out.emit(("folder", self.infos[0], new_name, new_desc))
class AboutDialog(QDialog): out = pyqtSignal(object) def __init__(self, parent=None): super(AboutDialog, self).__init__(parent) self.initUI() self.setStyleSheet(dialog_qss_style) def set_values(self, version): self.lb_name_text.setText("<font color=blue>" + version + "</font>") # 更新版本 def initUI(self): about = ''' 本项目使用PyQt5实现图形界面,可以完成蓝奏云的大部分功能<br/> 得益于 API 的功能,可以间接突破单文件最大 100MB 的限制,同时增加了批量上传/下载的功能<br/> Python 依赖见<a href="https://github.com/rachpt/lanzou-gui/blob/master/requirements.txt">requirements.txt</a>,<a href="https://github.com/rachpt/lanzou-gui/releases">releases</a> 有打包好了的 Windows 可执行程序,但可能不是最新的 ''' project_url = ''' 主 repo : <a href="https://github.com/rachpt/lanzou-gui">https://github.com/rachpt/lanzou-gui</a><br/> 镜像 repo : <a href="https://gitee.com/rachpt/lanzou-gui">https://gitee.com/rachpt/lanzou-gui</a> ''' self.setWindowTitle("关于 lanzou-gui") self.logo = QLabel() # logo self.logo.setPixmap(QPixmap("./icon/logo2.gif")) self.logo.setStyleSheet("background-color:rgb(255,255,255);") self.logo.setAlignment(Qt.AlignCenter) self.lb_name = QLabel("版本") # 版本 self.lb_name_text = QLabel("") # 版本 self.lb_about = QLabel("About") # about self.lb_about_text = QTextEdit(about) # about self.lb_about_text.setFocusPolicy(Qt.NoFocus) self.lb_about_text.setReadOnly(True) # self.lb_about_text.setOpenExternalLinks(True) self.lb_author = QLabel("Author") # author self.lb_author_mail = QLabel("*****@*****.**") # author self.lb_update = QLabel("更新地址") # 更新 self.lb_update_url = QLabel(project_url) self.lb_update_url.setOpenExternalLinks(True) self.buttonBox = QDialogButtonBox() self.buttonBox.setOrientation(Qt.Horizontal) self.buttonBox.setStandardButtons(QDialogButtonBox.Close) self.buttonBox.button(QDialogButtonBox.Close).setText("关闭") self.buttonBox.accepted.connect(self.accept) self.buttonBox.rejected.connect(self.reject) self.grid = QGridLayout() self.grid.setSpacing(10) self.grid.addWidget(self.logo, 1, 0, 2, 3) self.grid.addWidget(self.lb_name, 3, 0) self.grid.addWidget(self.lb_name_text, 3, 1) self.grid.addWidget(self.lb_about, 4, 0) self.grid.addWidget(self.lb_about_text, 4, 1, 3, 2) self.grid.addWidget(self.lb_author, 7, 0) self.grid.addWidget(self.lb_author_mail, 7, 1) self.grid.addWidget(self.lb_update, 8, 0) self.grid.addWidget(self.lb_update_url, 8, 1, 2, 2) self.grid.addWidget(self.buttonBox, 10, 2) self.setLayout(self.grid) self.setFixedSize(660, 300)
def showText( txt: str, parent: Optional[QWidget] = None, type: str = "text", run: bool = True, geomKey: Optional[str] = None, minWidth: int = 500, minHeight: int = 400, title: str = "Anki", copyBtn: bool = False, plain_text_edit: bool = False, ) -> Optional[Tuple[QDialog, QDialogButtonBox]]: if not parent: parent = aqt.mw.app.activeWindow() or aqt.mw diag = QDialog(parent) diag.setWindowTitle(title) disable_help_button(diag) layout = QVBoxLayout(diag) diag.setLayout(layout) text: Union[QPlainTextEdit, QTextBrowser] if plain_text_edit: # used by the importer text = QPlainTextEdit() text.setReadOnly(True) text.setWordWrapMode(QTextOption.NoWrap) text.setPlainText(txt) else: text = QTextBrowser() text.setOpenExternalLinks(True) if type == "text": text.setPlainText(txt) else: text.setHtml(txt) layout.addWidget(text) box = QDialogButtonBox(QDialogButtonBox.Close) layout.addWidget(box) if copyBtn: def onCopy() -> None: QApplication.clipboard().setText(text.toPlainText()) btn = QPushButton(tr(TR.QT_MISC_COPY_TO_CLIPBOARD)) qconnect(btn.clicked, onCopy) box.addButton(btn, QDialogButtonBox.ActionRole) def onReject() -> None: if geomKey: saveGeom(diag, geomKey) QDialog.reject(diag) qconnect(box.rejected, onReject) def onFinish() -> None: if geomKey: saveGeom(diag, geomKey) qconnect(box.accepted, onFinish) diag.setMinimumHeight(minHeight) diag.setMinimumWidth(minWidth) if geomKey: restoreGeom(diag, geomKey) if run: diag.exec_() return None else: return diag, box
def __init__(self, width, height): super().__init__() self.SettingsChanged = False self.setWindowTitle('Settings') self.setGeometry(QRect(round((width - 400) / 2), round((height - 200) / 2), 400, 100)) hBox1 = QHBoxLayout() self.lbPath = QLabel(self) self.lbPath.setText('File path:') self.lnEdit = QLineEdit(self) self.lnEdit.setText(output_path) self.lnEdit.setToolTip('Edit path') self.btnOpen = QPushButton(self) self.btnOpen.setIcon(QIcon(':/folder-icon')) self.btnOpen.setIconSize(QSize(24, 24)) self.btnOpen.setToolTip('Choose folder to save downloaded files') self.btnOpen.clicked.connect(self.onOpenClicked) hBox1.addWidget(self.lbPath, 0) hBox1.addWidget(self.lnEdit, 1) hBox1.addWidget(self.btnOpen, 0) gbStream = QGroupBox(self) gbStream.setTitle('Stream type:') hBox2 = QHBoxLayout() self.btnProgressive = QRadioButton(self) self.btnProgressive.setText('progressive') self.btnProgressive.setToolTip('Streams with both audio and video tracks') self.btnProgressive.toggled.connect(lambda: self.onStreamType(self.btnProgressive.text())) self.btnAdaptive = QRadioButton(self) self.btnAdaptive.setText('adaptive') self.btnAdaptive.setToolTip('Streams with only audio or video track') self.btnAdaptive.toggled.connect(lambda: self.onStreamType(self.btnAdaptive.text())) self.btnAllStream = QRadioButton(self) self.btnAllStream.setText('all') self.btnAllStream.setToolTip('Lists all available downloads') self.btnAllStream.toggled.connect(lambda: self.onStreamType(self.btnAllStream.text())) if stream_type == 'progressive': self.btnProgressive.setChecked(True) elif stream_type == 'adaptive': self.btnAdaptive.setChecked(True) else: self.btnAllStream.setChecked(True) hBox2.addWidget(self.btnProgressive) hBox2.addWidget(self.btnAdaptive) hBox2.addWidget(self.btnAllStream) gbStream.setLayout(hBox2) gbSubtype = QGroupBox(self) gbSubtype.setTitle('Subtype') hBox3 = QHBoxLayout() self.btn3Gpp = QRadioButton(self) self.btn3Gpp.setText('3gpp') self.btn3Gpp.toggled.connect(lambda: self.onSubType(self.btn3Gpp.text())) self.btnMp4 = QRadioButton(self) self.btnMp4.setText('mp4') self.btnMp4.toggled.connect(lambda: self.onSubType(self.btnMp4.text())) self.btnWebm = QRadioButton(self) self.btnWebm.setText('webm') self.btnWebm.toggled.connect(lambda: self.onSubType(self.btnWebm.text())) hBox3.addWidget(self.btn3Gpp) hBox3.addWidget(self.btnMp4) hBox3.addWidget(self.btnWebm) gbSubtype.setLayout(hBox3) if subtype == '3gpp': self.btn3Gpp.setChecked(True) if subtype == 'webm': self.btnWebm.setChecked(True) else: self.btnMp4.setChecked(True) self.chbDlCap = QCheckBox(self) self.chbDlCap.setText('Download a caption if available') self.chbDlCap.setChecked(dl_cap) vBox = QVBoxLayout() vBox.addLayout(hBox1) vBox.addWidget(gbStream) vBox.addWidget(gbSubtype) vBox.addWidget(self.chbDlCap) self.btnBox = QDialogButtonBox(self) sizePolicy = QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.btnBox.sizePolicy().hasHeightForWidth()) self.btnBox.setSizePolicy(sizePolicy) self.btnBox.setOrientation(Qt.Horizontal) self.btnBox.setStandardButtons(QDialogButtonBox.Ok | QDialogButtonBox.Cancel) self.btnBox.accepted.connect(self.onOk) self.btnBox.rejected.connect(self.onCancel) vBox.addWidget(self.btnBox) self.setLayout(vBox)
def createUI(self): vl = VLayout() self.setLayout(vl) # Wifi groupbox self.gbWifi = QGroupBox('WiFi') self.gbWifi.setCheckable(True) self.gbWifi.setChecked(False) flWifi = QFormLayout() self.leAP = QLineEdit() self.leAPPwd = QLineEdit() self.leAPPwd.setEchoMode(QLineEdit.Password) flWifi.addRow('SSID', self.leAP) flWifi.addRow('Password', self.leAPPwd) self.gbWifi.setLayout(flWifi) # Recovery Wifi groupbox self.gbRecWifi = QGroupBox('Recovery WiFi') self.gbRecWifi.setCheckable(True) self.gbRecWifi.setChecked(False) flRecWifi = QFormLayout() lbRecAP = QLabel('Recovery') lbRecAP.setAlignment(Qt.AlignVCenter | Qt.AlignRight) lbRecAPPwd = QLabel('a1b2c3d4') lbRecAPPwd.setAlignment(Qt.AlignVCenter | Qt.AlignRight) flRecWifi.addRow('SSID', lbRecAP) flRecWifi.addRow('Password', lbRecAPPwd) self.gbRecWifi.setLayout(flRecWifi) vl_wifis = VLayout(0) vl_wifis.addWidgets([self.gbWifi, self.gbRecWifi]) # MQTT groupbox self.gbMQTT = QGroupBox('MQTT') self.gbMQTT.setCheckable(True) self.gbMQTT.setChecked(False) flMQTT = QFormLayout() self.leBroker = QLineEdit() self.sbPort = SpinBox() self.sbPort.setValue(1883) self.leTopic = QLineEdit() self.leTopic.setText('tasmota') self.leFullTopic = QLineEdit() self.leFullTopic.setText('%prefix%/%topic%/') self.leFriendlyName = QLineEdit() self.leMQTTUser = QLineEdit() self.leMQTTPass = QLineEdit() self.leMQTTPass.setEchoMode(QLineEdit.Password) flMQTT.addRow('Host', self.leBroker) flMQTT.addRow('Port', self.sbPort) flMQTT.addRow('Topic', self.leTopic) flMQTT.addRow('FullTopic', self.leFullTopic) flMQTT.addRow('FriendlyName', self.leFriendlyName) flMQTT.addRow('User [optional]', self.leMQTTUser) flMQTT.addRow('Password [optional]', self.leMQTTPass) self.gbMQTT.setLayout(flMQTT) # Module/template groupbox self.gbModule = GroupBoxV('Module/template') self.gbModule.setCheckable(True) self.gbModule.setChecked(False) hl_m_rb = HLayout() self.rbModule = QRadioButton('Module') self.rbModule.setChecked(True) self.rbTemplate = QRadioButton('Template') hl_m_rb.addWidgets([self.rbModule, self.rbTemplate]) self.rbgModule = QButtonGroup(self.gbModule) self.rbgModule.addButton(self.rbModule, 0) self.rbgModule.addButton(self.rbTemplate, 1) self.cbModule = QComboBox() for mod_id, mod_name in MODULES.items(): self.cbModule.addItem(mod_name, mod_id) self.leTemplate = QLineEdit() self.leTemplate.setPlaceholderText('Paste template string here') self.leTemplate.setVisible(False) self.gbModule.addLayout(hl_m_rb) self.gbModule.addWidgets([self.cbModule, self.leTemplate]) self.rbgModule.buttonClicked[int].connect(self.setModuleMode) # layout all widgets hl_wifis_mqtt = HLayout(0) hl_wifis_mqtt.addLayout(vl_wifis) hl_wifis_mqtt.addWidget(self.gbMQTT) vl.addLayout(hl_wifis_mqtt) vl.addWidget(self.gbModule) btns = QDialogButtonBox(QDialogButtonBox.Save | QDialogButtonBox.Close) btns.accepted.connect(self.accept) btns.rejected.connect(self.reject) vl.addWidget(btns)
class ArtisanDialog(QDialog): def __init__(self, parent=None, aw = None): super(ArtisanDialog,self).__init__(parent) self.aw = aw # the Artisan application window # IMPORTANT NOTE: if dialog items have to be access after it has been closed, this Qt.WA_DeleteOnClose attribute # has to be set to False explicitly in its initializer (like in comportDlg) to avoid the early GC and one might # want to use a dialog.deleteLater() call to explicitly have the dialog and its widgets GCe # or rather use sip.delete(dialog) if the GC via .deleteLater() is prevented by a link to a parent object (parent not None) self.setAttribute(Qt.WA_DeleteOnClose, True) # if platf == 'Windows': # setting those Windows flags could be the reason for some instabilities on Windows # windowFlags = self.windowFlags() # #windowFlags &= ~Qt.WindowContextHelpButtonHint # remove help button # #windowFlags &= ~Qt.WindowMaximizeButtonHint # remove maximise button # #windowFlags &= ~Qt.WindowMinMaxButtonsHint # remove min/max combo # #windowFlags |= Qt.WindowMinimizeButtonHint # Add minimize button # windowFlags |= Qt.WindowSystemMenuHint # Adds a window system menu, and possibly a close button # windowFlags |= Qt.WindowMinMaxButtonsHint # add min/max combo # self.setWindowFlags(windowFlags) # configure standard dialog buttons self.dialogbuttons = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel,Qt.Horizontal) self.dialogbuttons.button(QDialogButtonBox.Ok).setDefault(True) self.dialogbuttons.button(QDialogButtonBox.Ok).setAutoDefault(True) self.dialogbuttons.button(QDialogButtonBox.Cancel).setDefault(False) self.dialogbuttons.button(QDialogButtonBox.Cancel).setAutoDefault(False) self.dialogbuttons.button(QDialogButtonBox.Ok).setFocusPolicy(Qt.StrongFocus) # to add to tab focus switch for btn,txt,trans in [ (self.dialogbuttons.button(QDialogButtonBox.Ok),"OK", QApplication.translate("Button","OK", None)), (self.dialogbuttons.button(QDialogButtonBox.Cancel),"Cancel",QApplication.translate("Button","Cancel", None))]: self.setButtonTranslations(btn,txt,trans) # add additional CMD-. shortcut to close the dialog self.dialogbuttons.button(QDialogButtonBox.Cancel).setShortcut(QKeySequence("Ctrl+.")) # add additional CMD-W shortcut to close this dialog (ESC on Mac OS X) cancelAction = QAction(self, triggered=lambda _:self.dialogbuttons.rejected.emit()) try: cancelAction.setShortcut(QKeySequence.Cancel) except: pass self.dialogbuttons.button(QDialogButtonBox.Cancel).addActions([cancelAction]) def setButtonTranslations(self,btn,txt,trans): current_trans = btn.text() if txt == current_trans: # if standard qtbase tanslations fail, revert to artisan translations current_trans = trans if txt != current_trans: btn.setText(current_trans) def closeEvent(self,_): self.dialogbuttons.rejected.emit() def keyPressEvent(self,event): key = int(event.key()) #uncomment next line to find the integer value of a key #print(key) #modifiers = QApplication.keyboardModifiers() modifiers = event.modifiers() if key == 16777216 or (key == 87 and modifiers == Qt.ControlModifier): #ESCAPE or CMD-W self.close() else: super(ArtisanDialog, self).keyPressEvent(event)
class UploadDialog(QDialog): """文件上传对话框""" new_infos = pyqtSignal(object) def __init__(self): super().__init__() self.cwd = os.getcwd() self.selected = [] self.max_len = 400 self.initUI() self.set_size() self.setStyleSheet(dialog_qss_style) def set_values(self, folder_name): self.setWindowTitle("上传文件至 ➩ " + str(folder_name)) def initUI(self): self.setWindowTitle("上传文件") self.setWindowIcon(QIcon("./icon/upload.ico")) self.logo = QLabel() self.logo.setPixmap(QPixmap("./icon/logo3.gif")) self.logo.setStyleSheet("background-color:rgb(0,153,255);") self.logo.setAlignment(Qt.AlignCenter) # btn 1 self.btn_chooseDir = QPushButton("选择文件夹", self) self.btn_chooseDir.setObjectName("btn_chooseDir") self.btn_chooseDir.setObjectName("btn_chooseDir") self.btn_chooseDir.setIcon(QIcon("./icon/folder.gif")) # btn 2 self.btn_chooseMutiFile = QPushButton("选择多文件", self) self.btn_chooseDir.setObjectName("btn_chooseMutiFile") self.btn_chooseMutiFile.setObjectName("btn_chooseMutiFile") self.btn_chooseMutiFile.setIcon(QIcon("./icon/file.ico")) # btn 3 self.btn_deleteSelect = QPushButton("移除", self) self.btn_deleteSelect.setObjectName("btn_deleteSelect") self.btn_deleteSelect.setIcon(QIcon("./icon/delete.ico")) # 列表 self.list_view = QListView(self) self.list_view.setViewMode(QListView.ListMode) self.slm = QStandardItem() self.model = QStandardItemModel() self.list_view.setModel(self.model) self.model.removeRows(0, self.model.rowCount()) # 清除旧的选择 self.list_view.setEditTriggers(QAbstractItemView.NoEditTriggers) self.list_view.setSelectionBehavior(QAbstractItemView.SelectRows) self.list_view.setSelectionMode(QAbstractItemView.ExtendedSelection) self.buttonBox = QDialogButtonBox() self.buttonBox.setOrientation(Qt.Horizontal) self.buttonBox.setStandardButtons(QDialogButtonBox.Ok | QDialogButtonBox.Cancel) self.buttonBox.button(QDialogButtonBox.Ok).setText("确定") self.buttonBox.button(QDialogButtonBox.Cancel).setText("取消") grid = QGridLayout() grid.setSpacing(10) grid.addWidget(self.logo, 1, 0, 1, 3) grid.addWidget(self.btn_chooseDir, 2, 0) grid.addWidget(self.btn_chooseMutiFile, 2, 2) grid.addWidget(self.list_view, 3, 0, 2, 3) grid.addWidget(self.btn_deleteSelect, 5, 0) grid.addWidget(self.buttonBox, 5, 1, 1, 2) self.setLayout(grid) self.setMinimumWidth(350) # 设置信号 self.btn_chooseDir.clicked.connect(self.slot_btn_chooseDir) self.btn_chooseMutiFile.clicked.connect(self.slot_btn_chooseMutiFile) self.btn_deleteSelect.clicked.connect(self.slot_btn_deleteSelect) self.buttonBox.accepted.connect(self.slot_btn_ok) self.buttonBox.accepted.connect(self.accept) self.buttonBox.rejected.connect(self.clear_old) self.buttonBox.rejected.connect(self.reject) def set_size(self): rows = self.model.rowCount() for i in range(rows): m_len = int(len(self.model.item(i, 0).text()) * 4) if m_len > self.max_len: self.max_len = m_len rows = 10 if rows >= 10 else rows # 限制最大高度 self.resize(self.max_len, 250 + rows * 28) def clear_old(self): self.selected = [] self.model.removeRows(0, self.model.rowCount()) self.set_size() def slot_btn_ok(self): if self.selected: self.new_infos.emit(self.selected) self.clear_old() def slot_btn_deleteSelect(self): _indexes = self.list_view.selectionModel().selection().indexes() if not _indexes: return indexes = [] for i in _indexes: # 获取所选行号 indexes.append(i.row()) indexes = set(indexes) for i in sorted(indexes, reverse=True): self.selected.remove(self.model.item(i, 0).text()) self.model.removeRow(i) self.set_size() def slot_btn_chooseDir(self): dir_choose = QFileDialog.getExistingDirectory(self, "选择文件夹", self.cwd) # 起始路径 if dir_choose == "": return if dir_choose not in self.selected: self.selected.append(dir_choose) self.model.appendRow( QStandardItem(QIcon("./icon/folder.gif"), dir_choose)) self.set_size() def slot_btn_chooseMutiFile(self): files, _ = QFileDialog.getOpenFileNames(self, "选择多文件", self.cwd, "All Files (*)") if len(files) == 0: return for _file in files: if _file not in self.selected: self.selected.append(_file) self.model.appendRow( QStandardItem(QIcon("./icon/file.ico"), _file)) self.set_size()
def __init__(self, parent=None): super(Sender, self).__init__(parent) self.statusLabel = QLabel("Ready to broadcast datagrams on port 45454") self.startButton = QPushButton("&Start") quitButton = QPushButton("&Quit") buttonBox = QDialogButtonBox() buttonBox.addButton(self.startButton, QDialogButtonBox.ActionRole) buttonBox.addButton(quitButton, QDialogButtonBox.RejectRole) self.timer = QTimer(self) self.udpSocket = QUdpSocket(self) self.messageNo = 1 self.startButton.clicked.connect(self.startBroadcasting) quitButton.clicked.connect(self.close) self.timer.timeout.connect(self.broadcastDatagramm) mainLayout = QVBoxLayout() mainLayout.addWidget(self.statusLabel) mainLayout.addWidget(buttonBox) self.setLayout(mainLayout) self.setWindowTitle("Broadcast Sender")