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, 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 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 __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 _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 _createEarlyCrashDialog(self): dialog = QDialog() dialog.setMinimumWidth(500) dialog.setMinimumHeight(170) dialog.setWindowTitle(catalog.i18nc("@title:window", "Cura Crashed")) dialog.finished.connect(self._closeEarlyCrashDialog) layout = QVBoxLayout(dialog) label = QLabel() label.setText( catalog.i18nc( "@label crash message", """<p><b>A fatal error has occurred.</p></b> <p>Unfortunately, Cura encountered an unrecoverable error during start up. It was possibly caused by some incorrect configuration files. We suggest to backup and reset your configuration.</p> <p>Backups can be found in the configuration folder.</p> <p>Please send us this Crash Report to fix the problem.</p> """)) label.setWordWrap(True) layout.addWidget(label) # "send report" check box and show details self._send_report_checkbox = QCheckBox( catalog.i18nc("@action:button", "Send crash report to Ultimaker"), dialog) self._send_report_checkbox.setChecked(True) show_details_button = QPushButton( catalog.i18nc("@action:button", "Show detailed crash report"), dialog) show_details_button.setMaximumWidth(200) show_details_button.clicked.connect(self._showDetailedReport) show_configuration_folder_button = QPushButton( catalog.i18nc("@action:button", "Show configuration folder"), dialog) show_configuration_folder_button.setMaximumWidth(200) show_configuration_folder_button.clicked.connect( self._showConfigurationFolder) layout.addWidget(self._send_report_checkbox) layout.addWidget(show_details_button) layout.addWidget(show_configuration_folder_button) # "backup and start clean" and "close" buttons buttons = QDialogButtonBox() buttons.addButton(QDialogButtonBox.Close) buttons.addButton( catalog.i18nc("@action:button", "Backup and Reset Configuration"), QDialogButtonBox.AcceptRole) buttons.rejected.connect(self._closeEarlyCrashDialog) buttons.accepted.connect(self._backupAndStartClean) layout.addWidget(buttons) return dialog
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()
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 show(exception_type, value, tb): debug_mode = False if QCoreApplication.instance(): debug_mode = QCoreApplication.instance().getCommandLineOption( "debug-mode", False) traceback.print_exception(exception_type, value, tb) if not debug_mode: 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>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(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 show_buttons(self): save_button = QDialogButtonBox.Save if self.data is None else QDialogButtonBox.Apply cancel_button = QDialogButtonBox.Cancel buttonBox = QDialogButtonBox(Qt.Horizontal) buttonBox.addButton(save_button).clicked.connect(self.accept) buttonBox.addButton(cancel_button).clicked.connect(self.reject) if self.data is not None: delete_button = buttonBox.addButton(QDialogButtonBox.Discard) delete_button.setText("Delete") delete_button.clicked.connect(self.delete_event) self.layout.addWidget(buttonBox)
def __init__(self, parent, icons, edit=False, username='', password='', api=''): QDialog.__init__(self, parent) self.edit = edit # Build UI layout = QVBoxLayout() formlayout = QFormLayout() self.lbl_username = QLabel('Username:'******'Password:'******'Request PIN') self.api_auth.setTextFormat(QtCore.Qt.RichText) self.api_auth.setTextInteractionFlags(QtCore.Qt.TextBrowserInteraction) self.api_auth.setOpenExternalLinks(True) pin_layout.addWidget(self.password) pin_layout.addWidget(self.api_auth) formlayout.addRow(QLabel('Site:'), self.api) formlayout.addRow(self.lbl_username, self.username) formlayout.addRow(self.lbl_password, pin_layout) bottombox = QDialogButtonBox() bottombox.addButton(QDialogButtonBox.Save) bottombox.addButton(QDialogButtonBox.Cancel) bottombox.accepted.connect(self.validate) bottombox.rejected.connect(self.reject) # Populate APIs for libname, lib in sorted(utils.available_libs.items()): self.api.addItem(icons[libname], lib[0], libname) if self.edit: self.username.setEnabled(False) self.api.setCurrentIndex(self.api.findData(api, QtCore.Qt.UserRole)) self.api.setEnabled(False) # Finish layouts layout.addLayout(formlayout) layout.addWidget(bottombox) self.setLayout(layout)
def __init__(self, device, *args, **kwargs): super(TemplateDialog, self).__init__(*args, **kwargs) self.setWindowTitle("Template [{}]".format(device.p['FriendlyName1'])) self.setMinimumWidth(300) self.device = device self.gb = {} gpios = {"255": "User"} gpios.update(self.device.gpios) btns = QDialogButtonBox(QDialogButtonBox.Cancel) btns.rejected.connect(self.reject) gbxTmpl = QGroupBox("Configure template") fl = QFormLayout() if self.device.p['Template']: btns.addButton(QDialogButtonBox.Save) btns.accepted.connect(self.accept) tpl = self.device.p['Template'] print(tpl) self.leName = QLineEdit() self.leName.setMaxLength(14) self.leName.setText(tpl['NAME']) fl.addRow("Name", self.leName) self.gbxBase = DictComboBox(self.device.modules) self.gbxBase.setCurrentText(self.device.modules[str(tpl['BASE'])]) fl.addRow("Based on", self.gbxBase) for i, g in enumerate( [0, 1, 2, 3, 4, 5, 9, 10, 12, 13, 14, 15, 16]): gbx = DictComboBox(gpios) gbx.setCurrentText(gpios.get(str(tpl['GPIO'][i]))) fl.addRow( "<font color='{}'>GPIO{}</font>".format( 'red' if g in [9, 10] else 'black', g), gbx) self.gb[i] = gbx self.gbxADC = DictComboBox(template_adc) fl.addRow("ADC0", self.gbxADC) else: fl.addWidget( QLabel( "Templates not supported.\nUpgrade firmware to versions above 6.5" )) gbxTmpl.setLayout(fl) vl = VLayout() vl.addWidgets([gbxTmpl, btns]) self.setLayout(vl)
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
class CalendarDialog(QDialog): def __init__(self, xlim): super(CalendarDialog, self).__init__() self.initUI(xlim) def initUI(self, xlim): Vl = QVBoxLayout() Grid = QGridLayout() ## number of Headerlines Grid.addWidget(QLabel('Select start time'), 0, 0) Grid.addWidget(QLabel('Select end time'), 0, 1) xs = num2date(xlim[0]) xt = num2date(xlim[1]) xmin = QDate(xs.year, xs.month, xs.day) xmax = QDate(xt.year, xt.month, xt.day) self.tstart = QCalendarWidget() self.tstart.setDateRange(xmin, xmax) self.tstart.setSelectedDate(xmin) self.tend = QCalendarWidget() self.tend.setDateRange(xmin, xmax) self.tend.setSelectedDate(xmax) Grid.addWidget(self.tstart, 1, 0) Grid.addWidget(self.tend, 1, 1) Vl.addLayout(Grid) self.buttons = QDialogButtonBox() self.ok_button = self.buttons.addButton(self.buttons.Ok) self.buttons.addButton(self.buttons.Cancel) self.buttons.accepted.connect(self.accept) self.buttons.rejected.connect(self.closeWindow) Vl.addWidget(self.buttons) self.setLayout(Vl) self.setWindowTitle('Select time') self.setGeometry(300, 300, 250, 150) self.show() def getResults(self): if self.exec_() == QDialog.Accepted: # get all values tstart = self.tstart.selectedDate().getDate() tend = self.tend.selectedDate().getDate() return tstart, tend else: return None def closeWindow(self): self.close() return None
class LoginDialog(QDialog): def __init__(self, parent=None): super().__init__(parent) self._username = None self._password = None self.label_username = QLabel(self) self.label_username.setText("Username") self.text_username = QLineEdit(self) self.label_password = QLabel(self) self.label_password.setText("Password") self.text_password = QLineEdit(self) self.text_password.setEchoMode(QLineEdit.Password) self.buttons = QDialogButtonBox(self) self.buttons.addButton(QDialogButtonBox.Ok) self.buttons.addButton(QDialogButtonBox.Cancel) self.buttons.button(QDialogButtonBox.Ok).clicked.connect( self.ok_pressed) self.buttons.button(QDialogButtonBox.Cancel).clicked.connect( self.cancel_pressed) layout = QGridLayout(self) layout.addWidget(self.label_username, 0, 0) layout.addWidget(self.text_username, 0, 1) layout.addWidget(self.label_password, 1, 0) layout.addWidget(self.text_password, 1, 1) layout.addWidget(self.buttons, 2, 0, 1, 2) @property def username(self): return self._username @property def password(self): return self._password @property def has_values(self): return self._username != None and self._password != None def ok_pressed(self): self._username = self.text_username.text() self._password = self.text_password.text() self.accept() def cancel_pressed(self): self.close()
class PeaksDialog(QDialog): def __init__(self): super(PeaksDialog, self).__init__() self.paramters = [ 'height', 'threshold', 'distance', 'prominence', 'width', 'wlen', 'rel_height', 'plateau_size' ] self.initUI() def initUI(self): Vl = QVBoxLayout() Grid = QGridLayout() self.param = [] for i, param in enumerate(self.paramters): Grid.addWidget(QLabel(param), i, 0) ql = QLineEdit(None) ql.setValidator(QDoubleValidator()) ql.setFixedWidth(100) Grid.addWidget(ql, i, 1) self.param.append(ql) Vl.addLayout(Grid) self.buttons = QDialogButtonBox() self.ok_button = self.buttons.addButton(self.buttons.Ok) self.buttons.addButton(self.buttons.Cancel) self.buttons.accepted.connect(self.accept) self.buttons.rejected.connect(self.closeWindow) Vl.addWidget(self.buttons) self.setLayout(Vl) self.setWindowTitle('Select peaks') self.setGeometry(300, 300, 250, 150) self.show() def closeWindow(self): self.close() return None def getResults(self): if self.exec_() == QDialog.Accepted: # get all values val = {} for i, param in enumerate(self.paramters): val[param] = strx(self.param[i].text()) return val else: return None
class VCDoubleInputDialog(QDialog): def __init__(self, parent: QWidget, title: str, label: str, value: float, minval: float, maxval: float, decimals: int, step: float, desc: str = None, suffix: str = None): super(VCDoubleInputDialog, self).__init__(parent, Qt.Dialog | Qt.WindowCloseButtonHint) self._spinbox = QDoubleSpinBox(self) self._spinbox.setStyle(QStyleFactory.create('Fusion')) self._spinbox.setAttribute(Qt.WA_MacShowFocusRect, False) self._spinbox.setDecimals(decimals) self._spinbox.setRange(minval, maxval) self._spinbox.setSingleStep(step) if suffix is not None: self._spinbox.setSuffix(' {}'.format(suffix)) self.value = value startbutton = QPushButton('Start') startbutton.setDefault(True) self.buttons = QDialogButtonBox(self) self.buttons.addButton(startbutton, QDialogButtonBox.AcceptRole) self.buttons.addButton(QDialogButtonBox.Cancel) self.buttons.rejected.connect(self.close) fieldlayout = QHBoxLayout() fieldlayout.addWidget(QLabel(label, self)) fieldlayout.addWidget(self._spinbox) layout = QVBoxLayout() layout.addLayout(fieldlayout) if desc is not None: desc_label = QLabel(desc, self) desc_label.setTextFormat(Qt.RichText) desc_label.setObjectName('dialogdesc') desc_label.setWordWrap(True) layout.addWidget(desc_label) layout.addWidget(self.buttons) self.setLayout(layout) self.setWindowTitle(title) @property def value(self) -> float: return self._spinbox.value() @value.setter def value(self, val: float) -> None: self._spinbox.setValue(val)
def _make_gui(self) -> None: self.setWindowTitle("Error on file transfer") # Widgets move_icon = QLabel() move_icon.setPixmap(QIcon.fromTheme("error").pixmap(48)) move_icon.setAlignment(Qt.AlignTop | Qt.AlignHCenter) header = QLabel( "<big>An error occured while accessing '{}'</big>".format( html.escape(self._source_file))) header.setTextFormat(Qt.RichText) error_widget = QPlainTextEdit() error_widget.setReadOnly(True) error_widget.setPlainText(self._error_msg) subheader = QLabel("Do you want to skip it?") # Widgets.ButtonBox button_box = QDialogButtonBox(self) button_box.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed) btn_cancel = button_box.addButton(QDialogButtonBox.Cancel) btn_skip = QPushButton("Skip") btn_retry = QPushButton("Retry") button_box.addButton(btn_skip, QDialogButtonBox.AcceptRole) button_box.addButton(btn_retry, QDialogButtonBox.AcceptRole) btn_skip.setDefault(True) # Layout subvbox = QVBoxLayout() subvbox.addWidget(header) subvbox.addWidget(error_widget) subvbox.addWidget(subheader) hbox = QHBoxLayout() hbox.addWidget(move_icon) hbox.addLayout(subvbox) vbox = QVBoxLayout() vbox.addLayout(hbox) vbox.addWidget(button_box) self.setLayout(vbox) # Signals btn_skip.clicked.connect(lambda: self.done(TransferErrorDialog.Skip)) btn_retry.clicked.connect(lambda: self.done(TransferErrorDialog.Retry)) btn_cancel.clicked.connect( lambda: self.done(TransferErrorDialog.Cancel))
def createUI(self): """ Создание интерфейса """ # контролы lblChooseBase = QLabel("Выбор базы данных") # установим жирный шрифт boldFont = QFont() boldFont.setBold(True) lblChooseBase.setFont(boldFont) self.cbbChooseBase = QComboBox() # заполняем комбобокс self.cbbChooseBase.addItems(self.getDatabaseList()) # указываем политику изменения размера для ComboBox sizePolicy = QSizePolicy(QSizePolicy.Minimum, QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth( self.cbbChooseBase.sizePolicy().hasHeightForWidth()) self.cbbChooseBase.setSizePolicy(sizePolicy) # кнопки btnOK = QPushButton(self.tr("&OK")) btnOK.setDefault(True) btnCancel = QPushButton(self.tr("&Cancel")) btnDialogs = QDialogButtonBox(Qt.Horizontal) btnDialogs.addButton(btnOK, QDialogButtonBox.AcceptRole) btnDialogs.addButton(btnCancel, QDialogButtonBox.RejectRole) # layout grid = QGridLayout() grid.addWidget(lblChooseBase, 0, 0, Qt.AlignVCenter | Qt.AlignHCenter) grid.addWidget(self.cbbChooseBase, 1, 0) layout = QVBoxLayout() layout.addLayout(grid) layout.addWidget(btnDialogs) self.setLayout(layout) # параметры окна self.setGeometry(0, 0, 450, 100) self.setWindowIcon(QIcon("BookManager.ico")) self.setWindowTitle("Соединение") # запрет показа кнопки "?" в заголовке окна self.setWindowFlags(Qt.WindowSystemMenuHint | Qt.WindowTitleHint) # запрет изменения размера self.setFixedSize(self.size()) self.center() self.setWindowIcon(QIcon(r"image\BookManager.ico")) # обработчики событий btnDialogs.accepted.connect(self.accept) btnDialogs.rejected.connect(self.reject)
def __init__(self, title, entry_type, value, parent, image_data=None, prefill_text=None): super().__init__(parent) self.value = value self.entry_type = entry_type self.setWindowTitle(title) layout = QVBoxLayout() if entry_type == self.LINE_EDIT: self.entry_widget = QLineEdit(self) if prefill_text: self.entry_widget.setText(prefill_text) elif entry_type == self.TEXT_EDIT: self.entry_widget = QTextEdit(self) if prefill_text: self.entry_widget.setText(prefill_text) elif entry_type == self.SPIN_BOX: self.entry_widget = QSpinBox(self) self.entry_widget.setRange(-1000000000, 1000000000) self.entry_widget.setFocus() elif entry_type == self.IMAGE: self.filename = None image_button = QPushButton('Choose Image', self) image_button.clicked.connect(self.open_image_file) self.entry_widget = QLabel(self) pixmap = get_pixmap_from_base64(image_data) self.entry_widget.setPixmap(pixmap) layout.addWidget(image_button) layout.addWidget(self.entry_widget, 0, QtCore.Qt.AlignCenter) button_frame = QDialogButtonBox(self) ok_button = QPushButton('OK', self) cancel_button = QPushButton('Cancel', self) ok_button.setDefault(True) button_frame.addButton(ok_button, QDialogButtonBox.AcceptRole) button_frame.addButton(cancel_button, QDialogButtonBox.RejectRole) button_frame.accepted.connect(self.ok_pressed) button_frame.rejected.connect(self.cancel_pressed) layout.addWidget(button_frame) layout.setSizeConstraint(QLayout.SetFixedSize) self.setLayout(layout)
def createButtonBox(self, cmd_fct): def clicked(button): command = button.text() specsheet = self.specsheet_dict[self.conjugate_type] if cmd_fct: try: cmd_fct(self, command, specsheet) except: QMessageBox.warning( self, self.tr("Ray-Optics"), self.tr("Please provide correct inputs.")) else: print(button.text(), 'button pressed') buttonbox = QDialogButtonBox(qt.Horizontal, self) buttonbox.addButton('New', QDialogButtonBox.ApplyRole) buttonbox.addButton(QDialogButtonBox.Apply) buttonbox.addButton('Update', QDialogButtonBox.ApplyRole) buttonbox.addButton(QDialogButtonBox.Close) for b in buttonbox.buttons(): b.setAutoDefault(False) # buttonbox.setCenterButtons(True) buttonbox.clicked.connect(clicked) return 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)
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, title, message, parent): super().__init__(parent) self.setWindowTitle(title) layout = QVBoxLayout() message_label = QLabel(message, self) ok_button = QPushButton('OK', self) button_frame = QDialogButtonBox(self) layout.addWidget(message_label) ok_button.setDefault(True) button_frame.addButton(ok_button, QDialogButtonBox.AcceptRole) button_frame.accepted.connect(self.accept) layout.addWidget(button_frame) layout.setSizeConstraint(QLayout.SetFixedSize) self.setLayout(layout)
def __buildButtonBox(self, control): """Constructs a button box for the dialog. """ buttonBox = QDialogButtonBox() buttonBox.addButton("Save", QDialogButtonBox.AcceptRole) buttonBox.accepted.connect(control.update) buttonBox.accepted.connect(super().accept) buttonBox.addButton("Cancel", QDialogButtonBox.RejectRole) buttonBox.rejected.connect(control.reset) buttonBox.rejected.connect(super().reject) return buttonBox
class StarDialog(QDialog): def __init__(self): super(StarDialog, self).__init__() self.is_star = False self.setWindowTitle('点亮TkPy的Star - 登录Github') self.star_process = StarProcess() self.star_process.ok.connect(self.close) self.git_layout = QFormLayout() self.username = QLineEdit() self.password = QLineEdit() self.username.setPlaceholderText('用户名') self.password.setPlaceholderText('密码') self.button_box = QDialogButtonBox() self.button_box.addButton('登录并点亮Star', QDialogButtonBox.AcceptRole) self.button_box.addButton('取消', QDialogButtonBox.RejectRole) self.button_box.accepted.connect(self.star) self.button_box.rejected.connect(self.close) self.init_ui() def init_ui(self): self.setLayout(self.git_layout) self.git_layout.addRow('用户名: ', self.username) self.git_layout.addRow('密码: ', self.password) self.git_layout.addWidget(self.button_box) self.password.setEchoMode(QLineEdit.Password) def star(self): res = QMessageBox.question(self, '问题', '确认账号和密码?') if res == QMessageBox.No: return if self.is_star: return self.is_star = True self.star_process.user_name = self.username.text() self.star_process.password = self.password.text() self.star_process.start() self.setEnabled(False) self.setWindowTitle('操作中... ...') def closeEvent(self, event: QCloseEvent) -> None: if self.is_star: event.accept() else: res = QMessageBox.question(self, '问题', '是否退出?', QMessageBox.No | QMessageBox.Yes, QMessageBox.No) if res == QMessageBox.Yes: event.accept() else: event.ignore()
def __init__(self, parent=None): super(ReferenceDataDlg, self).__init__(parent) self.model = QSqlTableModel(self) self.model.setTable("reference") self.model.setSort(ID, Qt.AscendingOrder) self.model.setHeaderData(ID, Qt.Horizontal, "ID") self.model.setHeaderData(CATEGORY, Qt.Horizontal, "Category") self.model.setHeaderData(SHORTDESC, Qt.Horizontal, "Short Desc.") self.model.setHeaderData(LONGDESC, Qt.Horizontal, "Long Desc.") self.model.select() self.view = QTableView() self.view.setModel(self.model) self.view.setSelectionMode(QTableView.SingleSelection) self.view.setSelectionBehavior(QTableView.SelectRows) self.view.setColumnHidden(ID, True) self.view.resizeColumnsToContents() buttonBox = QDialogButtonBox() addButton = buttonBox.addButton("&Add", QDialogButtonBox.ActionRole) deleteButton = buttonBox.addButton("&Delete", QDialogButtonBox.ActionRole) sortButton = buttonBox.addButton("&Sort", QDialogButtonBox.ActionRole) if not MAC: addButton.setFocusPolicy(Qt.NoFocus) deleteButton.setFocusPolicy(Qt.NoFocus) sortButton.setFocusPolicy(Qt.NoFocus) menu = QMenu(self) sortByCategoryAction = menu.addAction("Sort by &Category") sortByDescriptionAction = menu.addAction("Sort by &Description") sortByIDAction = menu.addAction("Sort by &ID") sortButton.setMenu(menu) closeButton = buttonBox.addButton(QDialogButtonBox.Close) layout = QVBoxLayout() layout.addWidget(self.view) layout.addWidget(buttonBox) self.setLayout(layout) addButton.clicked.connect(self.addRecord) deleteButton.clicked.connect(self.deleteRecord) sortByCategoryAction.triggered.connect(lambda: self.sort(CATEGORY)) sortByDescriptionAction.triggered.connect(lambda: self.sort(SHORTDESC)) sortByIDAction.triggered.connect(lambda: self.sort(ID)) closeButton.clicked.connect(self.accept) self.setWindowTitle("Reference Data")
class LoginDialog(QDialog): def __init__(self, playerCore): super().__init__() self.player = playerCore self.ui() def ui(self): self.formGridLayout = QGridLayout() self.usernameEdit = QLineEdit() self.passwordEdit = QLineEdit() self.passwordEdit.setEchoMode(QLineEdit.Password) self.labelUsername = QLabel("Username") self.labelPassword = QLabel("Password") self.labelUsername.setBuddy(self.usernameEdit) self.labelPassword.setBuddy(self.passwordEdit) self.buttons = QDialogButtonBox() self.buttons.addButton(QDialogButtonBox.Ok) self.buttons.addButton(QDialogButtonBox.Cancel) self.buttons.button(QDialogButtonBox.Ok).setText("Login") self.buttons.button(QDialogButtonBox.Cancel).setText("Abort") self.buttons.button( QDialogButtonBox.Cancel).clicked.connect(self.close) self.buttons.button( QDialogButtonBox.Ok).clicked.connect(self.slotAcceptLogin) self.formGridLayout.addWidget(self.labelUsername, 0, 0) self.formGridLayout.addWidget(self.usernameEdit, 0, 1) self.formGridLayout.addWidget(self.labelPassword, 1, 0) self.formGridLayout.addWidget(self.passwordEdit, 1, 1) self.formGridLayout.addWidget(self.buttons, 2, 0, 1, 2) self.setLayout(self.formGridLayout) self.setWindowTitle('Login') self.show() def slotAcceptLogin(self): username = self.usernameEdit.text() password = self.passwordEdit.text() self.close() logged = self.player.login(username, password) if not logged: self.errorWindow = Window( 'Error', 'Login failed! Try again later.') else: self.successful = Window( 'Success', 'Welcome, {}!'.format(username))
def proxyAuthentication(self, proxyHost, auth, parent=None): ''' @param: proxyHost QString @param: auth QAuthenticator ''' proxy = QNetworkProxy.applicationProxy() if proxy.user() and proxy.password(): auth.setUser(proxy.user()) auth.setPassword(proxy.password()) return dialog = QDialog(parent) dialog.setWindowTitle(_('Proxy authorization required')) formLa = QFormLayout(dialog) label = QLabel(dialog) userLab = QLabel(dialog) passLab = QLabel(dialog) userLab.setText(_('Username: '******'Password: '******'A username and password are being requested by proxy %s. ') % proxyHost) formLa.addRow(label) formLa.addRow(userLab, user) formLa.addRow(passLab, pass_) formLa.addWidget(box) if dialog.exec_() != QDialog.Accepted: auth = QAuthenticator del dialog return auth # TODO: C++ return, but should assign auth, try return auth in python, to be check auth.setUser(user.text()) auth.setPassword(pass_.text()) del dialog
def __init__(self, parent=None): super(HttpWindow, self).__init__(parent) self.url = QUrl() self.qnam = QNetworkAccessManager() self.reply = None self.outFile = None self.httpGetId = 0 self.httpRequestAborted = False self.urlLineEdit = QLineEdit('https://www.qt.io') urlLabel = QLabel("&URL:") urlLabel.setBuddy(self.urlLineEdit) self.statusLabel = QLabel( "Please enter the URL of a file you want to download.") self.statusLabel.setWordWrap(True) self.downloadButton = QPushButton("Download") self.downloadButton.setDefault(True) self.quitButton = QPushButton("Quit") self.quitButton.setAutoDefault(False) buttonBox = QDialogButtonBox() buttonBox.addButton(self.downloadButton, QDialogButtonBox.ActionRole) buttonBox.addButton(self.quitButton, QDialogButtonBox.RejectRole) self.progressDialog = QProgressDialog(self) self.urlLineEdit.textChanged.connect(self.enableDownloadButton) self.qnam.authenticationRequired.connect( self.slotAuthenticationRequired) self.qnam.sslErrors.connect(self.sslErrors) self.progressDialog.canceled.connect(self.cancelDownload) self.downloadButton.clicked.connect(self.downloadFile) self.quitButton.clicked.connect(self.close) topLayout = QHBoxLayout() topLayout.addWidget(urlLabel) topLayout.addWidget(self.urlLineEdit) mainLayout = QVBoxLayout() mainLayout.addLayout(topLayout) mainLayout.addWidget(self.statusLabel) mainLayout.addWidget(buttonBox) self.setLayout(mainLayout) self.setWindowTitle("HTTP") self.urlLineEdit.setFocus()
def __init__(self, parent=None): super(ReferenceDataDlg, self).__init__(parent) self.model = QSqlTableModel(self) self.model.setTable("reference") self.model.setSort(ID, Qt.AscendingOrder) self.model.setHeaderData(ID, Qt.Horizontal, "ID") self.model.setHeaderData(CATEGORY, Qt.Horizontal, "小车编号") self.model.setHeaderData(SHORTDESC, Qt.Horizontal, "检查记录") self.model.setHeaderData(LONGDESC, Qt.Horizontal, "巡检日期") self.model.select() self.view = QTableView() self.view.setModel(self.model) self.view.setSelectionMode(QTableView.SingleSelection) self.view.setSelectionBehavior(QTableView.SelectRows) self.view.setColumnHidden(ID, True) self.view.resizeColumnsToContents() buttonBox = QDialogButtonBox() addButton = buttonBox.addButton("&添加", QDialogButtonBox.ActionRole) deleteButton = buttonBox.addButton("&删除", QDialogButtonBox.ActionRole) sortButton = buttonBox.addButton("&排序", QDialogButtonBox.ActionRole) if not MAC: addButton.setFocusPolicy(Qt.NoFocus) deleteButton.setFocusPolicy(Qt.NoFocus) sortButton.setFocusPolicy(Qt.NoFocus) menu = QMenu(self) sortByCategoryAction = menu.addAction("按小车编号排序") sortByDescriptionAction = menu.addAction("按检查记录排序") sortByIDAction = menu.addAction("按编号顺序排序") sortButton.setMenu(menu) closeButton = buttonBox.addButton(QDialogButtonBox.Close) layout = QVBoxLayout() layout.addWidget(self.view) layout.addWidget(buttonBox) self.setLayout(layout) addButton.clicked.connect(self.addRecord) deleteButton.clicked.connect(self.deleteRecord) sortByCategoryAction.triggered.connect(lambda: self.sort(CATEGORY)) sortByDescriptionAction.triggered.connect(lambda: self.sort(SHORTDESC)) sortByIDAction.triggered.connect(lambda: self.sort(ID)) closeButton.clicked.connect(self.accept) self.setWindowTitle("巡检历史数据") self.setWindowIcon( QtGui.QIcon('icon/update_128px_1156069_easyicon.net.ico'))
class MyWidget(QWidget): def __init__(self): super(MyWidget, self).__init__() self.setWindowTitle('Timer') self.setMinimumSize(500, 500) self.move(50, 50) self.label = QLabel('This timer example') self.startButton = QPushButton('Start') self.stopButton = QPushButton('Stop') self.quitButton = QPushButton('Quit') self.buttonBox = QDialogButtonBox() self.buttonBox.addButton(self.startButton, QDialogButtonBox.ActionRole) self.buttonBox.addButton(self.stopButton, QDialogButtonBox.ActionRole) self.buttonBox.addButton(self.quitButton, QDialogButtonBox.RejectRole) self.startButton.clicked.connect(self.start) self.stopButton.clicked.connect(self.stop) self.quitButton.clicked.connect(self.close) mainLayout = QVBoxLayout() mainLayout.addWidget(self.label) mainLayout.addWidget(self.buttonBox) self.setLayout(mainLayout) def start(self): print('start') self.timer_id = self.startTimer(500) # timer of QWidget # create a timer self.timer = QtCore.QTimer() self.timer.timeout.connect(self.timerEvent2) self.timer.start(500) def stop(self): print('stop') self.killTimer(self.timer_id) self.timer.stop() def timerEvent(self, event): print('timerEvent') def timerEvent2(self): print('timerEvent2')
def __init__(self, parent: QWidget = None): super().__init__(parent) self._in = QDataStream() self.blockSize = 0 self.currentFortune = "" self.hostLineEdit = QLineEdit("fortune") self.getFortuneButton = QPushButton(self.tr("Get Fortune")) self.statusLabel = QLabel( self. tr("This examples requires that you run the Local Fortune Server example as well." )) self.socket = QLocalSocket(self) self.setWindowFlags(self.windowFlags() & ~Qt.WindowContextHelpButtonHint) hostLabel = QLabel(self.tr("&Server name:")) hostLabel.setBuddy(self.hostLineEdit) self.statusLabel.setWordWrap(True) self.getFortuneButton.setDefault(True) quitButton = QPushButton(self.tr("Quit")) buttonBox = QDialogButtonBox() buttonBox.addButton(self.getFortuneButton, QDialogButtonBox.ActionRole) buttonBox.addButton(quitButton, QDialogButtonBox.RejectRole) self._in.setDevice(self.socket) self._in.setVersion(QDataStream.Qt_5_10) self.hostLineEdit.textChanged.connect(self.enableGetFortuneButton) self.getFortuneButton.clicked.connect(self.requestNewFortune) quitButton.clicked.connect(self.close) self.socket.readyRead.connect(self.readFortune) self.socket.errorOccurred.connect(self.displayError) mainLayout = QGridLayout(self) mainLayout.addWidget(hostLabel, 0, 0) mainLayout.addWidget(self.hostLineEdit, 0, 1) mainLayout.addWidget(self.statusLabel, 2, 0, 1, 2) mainLayout.addWidget(buttonBox, 3, 0, 1, 2) self.setWindowTitle(QGuiApplication.applicationDisplayName()) self.hostLineEdit.setFocus()
class DialogSubpackage(QtWidgets.QDialog): def __init__(self, Dialog, Wizard, parent=None): super(DialogSubpackage, self).__init__(parent) self.wizard = Wizard # Settings self.setMinimumSize(QtCore.QSize(350, 150)) self.setMaximumSize(QtCore.QSize(500, 600)) # Setting labels nameLabel = QLabel("Name") groupLabel = QLabel("Group") summaryLabel = QLabel("Summary") descriptionLabel = QLabel("Description") # Setting text editors self.nameEdit = QLineEdit() self.groupEdit = QComboBox() self.summaryEdit = QLineEdit() self.descriptionEdit = QPlainTextEdit() # Setting 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) # Setting layout mainLayout = QVBoxLayout() mainLayout.addWidget(nameLabel) mainLayout.addWidget(self.nameEdit) mainLayout.addWidget(groupLabel) mainLayout.addWidget(self.groupEdit) mainLayout.addWidget(summaryLabel) mainLayout.addWidget(self.summaryEdit) mainLayout.addWidget(descriptionLabel) mainLayout.addWidget(self.descriptionEdit) mainLayout.addWidget(self.boxButtons) self.setLayout(mainLayout) def acceptIt(self): self.wizard.tree.addSubpackage(self.nameEdit.text()) self.accept()
def _make_gui(self) -> None: self.setWindowTitle("Error on file transfer") # Widgets move_icon = QLabel() move_icon.setPixmap(QIcon.fromTheme("error").pixmap(48)) move_icon.setAlignment(Qt.AlignTop | Qt.AlignHCenter) header = QLabel("<big>An error occured while accessing '{}'</big>".format(html.escape(self._source_file))) header.setTextFormat(Qt.RichText) error_widget = QPlainTextEdit() error_widget.setReadOnly(True) error_widget.setPlainText(self._error_msg) subheader = QLabel("Do you want to skip it?") # Widgets.ButtonBox button_box = QDialogButtonBox(self) button_box.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed) btn_cancel = button_box.addButton(QDialogButtonBox.Cancel) btn_skip = QPushButton("Skip") btn_retry = QPushButton("Retry") button_box.addButton(btn_skip, QDialogButtonBox.AcceptRole) button_box.addButton(btn_retry, QDialogButtonBox.AcceptRole) btn_skip.setDefault(True) # Layout subvbox = QVBoxLayout() subvbox.addWidget(header) subvbox.addWidget(error_widget) subvbox.addWidget(subheader) hbox = QHBoxLayout() hbox.addWidget(move_icon) hbox.addLayout(subvbox) vbox = QVBoxLayout() vbox.addLayout(hbox) vbox.addWidget(button_box) self.setLayout(vbox) # Signals btn_skip.clicked.connect(lambda: self.done(TransferErrorDialog.Skip)) btn_retry.clicked.connect(lambda: self.done(TransferErrorDialog.Retry)) btn_cancel.clicked.connect(lambda: self.done(TransferErrorDialog.Cancel))
class ConfScreen(QWidget): close_requested = pyqtSignal() def __init__(self, parent: QWidget = None) -> None: super().__init__(parent) self._vbox = QVBoxLayout(self) self._edit = QTextEdit() self._edit.setStyleSheet("font-family: monospace;") self._edit.setAcceptRichText(False) self._vbox.addWidget(self._edit) self._conf_file: pathlib.Path = settings.get_config_file_path() self._buttons = QDialogButtonBox() self._cancel_button: QPushButton = self._buttons.addButton( "Abbrechen", QDialogButtonBox.DestructiveRole) self._save_button: QPushButton = self._buttons.addButton( "Speichern", QDialogButtonBox.ApplyRole) self._back_button: QPushButton = self._buttons.addButton( "Speichern und zurück", QDialogButtonBox.AcceptRole) self._vbox.addWidget(self._buttons) self._cancel_button.clicked.connect(self.close_requested) self._save_button.clicked.connect( functools.partial(self.save, close=False)) self._back_button.clicked.connect( functools.partial(self.save, close=True)) def load_file(self) -> None: try: self._edit.setPlainText(self._conf_file.read_text('utf-8')) except FileNotFoundError: pass def save(self, close: bool) -> None: text: str = self._edit.toPlainText() self._conf_file.write_text(text, encoding='utf-8') try: syncing.validate_config(self._conf_file) except (utils.InvalidSettingsError, yaml.YAMLError) as ex: QMessageBox.critical(self, "Failed to validate config", str(ex)) return if close: self.close_requested.emit()
def __init__(self, cubeTable, fields, routeHandler, parent=None): super().__init__(parent) self.setMinimumSize(QSize(640, 330)) self.manualBB = QPushButton('Ir a manual') buttonBox = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel) buttonBox.addButton(self.manualBB, QDialogButtonBox.ActionRole) buttonBox.accepted.connect(self.accept) buttonBox.rejected.connect(self.reject) buttonBox.clicked.connect(self.procBotones) self.msgLine = QLabel() titleLabel = QLabel('Nombre de la guia') destLabel = QLabel('Tabla por la que queremos agrupar') destFLabel = QLabel('Campos por los que queremos agrupar') routeLabel = QLabel('Ruta para acceder a al tabla destino') self.titleText = QLineEdit() self.titleText.setStyleSheet("background-color:yellow;") self.destTable = QComboBox() self.destField = WComboMulti() self.destRoutes = QComboBox() meatlayout = QGridLayout() x = 0 meatlayout.addWidget(titleLabel, x, 0) meatlayout.addWidget(self.titleText, x, 1) x += 1 meatlayout.addWidget(destLabel, x, 0) meatlayout.addWidget(self.destTable, x, 1) x += 1 meatlayout.addWidget(destFLabel, x, 0) meatlayout.addWidget(self.destField, x, 1) x += 1 meatlayout.addWidget(routeLabel, x, 0) meatlayout.addWidget(self.destRoutes, x, 1, 1, 2) x += 2 meatlayout.addWidget(self.msgLine, x, 0) x += 1 meatlayout.addWidget(buttonBox, x, 1) self.setLayout(meatlayout) self.prepareData(cubeTable, fields, routeHandler) self.manual = False
class AddNewSubjectDialog(QDialog): def __init__(self): super().__init__() self.setupUi() self.buttonBox.accepted.connect(self.apply_button_clicked) self.buttonBox.rejected.connect(self.cancel_button_clicked) self.text = '' # self.pushButton.clicked.connect(self.close) def setupUi(self): self.setWindowTitle('Add New Subject') self.subject_name = QLabel() self.subject_input = CustQLineEdit() self.subject_name.setText("Subject Name") self.buttonBox = QDialogButtonBox() self.buttonBox.addButton("Submit", QDialogButtonBox.AcceptRole) self.buttonBox.addButton("Cancel", QDialogButtonBox.RejectRole) grid_box = QGridLayout() grid_box.addWidget(self.subject_name) grid_box.addWidget(self.subject_input) grid_box.addWidget(self.buttonBox) self.setLayout(grid_box) self.shortcut = QShortcut(QKeySequence('Ctrl+Return'), self) self.shortcut.activated.connect(self.apply_button_clicked) # button # button action def apply_button_clicked(self): self.text = self.subject_input.text() if self.text == '': self.close() msg = MessageBox('Please enter subject') msg.exec_() else: sql_conn = SqliteConnection() sql_conn.add_subject_to_db(self.text) self.close() def cancel_button_clicked(self): self.close() def getLabelText(self): text = subject_input.text() return text
def __init__(self, text, apply_callback): super().__init__() self.apply_callback = apply_callback self.textbox = QPlainTextEdit() self.textbox.setFont(monospace()) self.linenos = LineNumberBar(self.textbox) buttons = QDialogButtonBox() buttons.addButton(buttons.Ok).clicked.connect(self.accept) self.setLayout( VBoxLayout([ HBoxLayout([self.linenos, self.textbox], tight=True), buttons, ])) self.setSizeGripEnabled(True) self.resize(QSize(600, 400)) self.textbox.appendPlainText(text)
def initUI(self): self.resize(400,300) ## self.setSizePolicy(QSizePolicy.Fixed, ## QSizePolicy.Fixed ## self.setSizePolicy(QSizePolicy.Maximum, ## QSizePolicy.Maximum ## ) ## ## const base = QWidget(self) ## base.setSizePolicy(QSizePolicy.Maximum, ## QSizePolicy.Maximum ## ) scrollarea = QScrollArea(base) label = QLabel() scrollarea.setWidget(label) scrollarea.setWidgetResizable(True) scrollarea.setAlignment(Qt.AlignHCenter|Qt.AlignVCenter) label.setSizePolicy(QSizePolicy.Maximum, QSizePolicy.MinimumExpanding ) label.setAlignment(Qt.AlignLeft|Qt.AlignTop) label.setWordWrap(True) self.scrollarea = scrollarea self.label = label label_buttons = QDialogButtonBox(parent=self) for i,s in enumerate(self.labels): btn = label_buttons.addButton(s, QDialogButtonBox.ActionRole) btn.setShortcut(QKeySequence(str(i+1))) ## print(s) ## dir(btn) label_buttons.clicked.connect(self.process) ## print(label_buttons.buttons()) cancelbutton = QPushButton("Cancel",parent=base) #### startbutton = QPushButton("start", parent=base) #### startbutton.setEnabled(False) self.cancelbutton = cancelbutton #### startbutton.clicked.connect(self.step) #### self.activate = lambda: startbutton.setEnabled(True) cancelbutton.clicked.connect(self.exit) self.end.connect(lambda: print("end")) ## arrange self.setCentralWidget(base) baseLO = QVBoxLayout(base) baseLO.setSizeConstraint(QLayout.SetMinimumSize) baseLO.addWidget(scrollarea) buttomLO = QHBoxLayout() buttomLO.addWidget(label_buttons) buttomLO.addStretch() #### buttomLO.addWidget(startbutton) buttomLO.addWidget(cancelbutton) baseLO.addLayout(buttomLO)
def __init__(self, pluginEntry): super().__init__() self._pluginEntry = pluginEntry # Should be set to 150, when there a some kind of info link / button. self.setMaximumHeight(300) bottom = QWidget() hbox = QHBoxLayout() bottom_label = QLabel(pluginEntry["author"]) bottom_label.setMargin(0) bottom_label.setIndent(0) hbox.addWidget(bottom_label) button_box = QDialogButtonBox(self) self.startStopButton = button_box.addButton( 'Enable', QDialogButtonBox.DestructiveRole ) self.startStopButton.setCheckable(True) self._setStartStopButton() self.startStopButton.clicked.connect(self._onStartStopButtonClicked) uninstallButton = button_box.addButton( 'Uninstall', QDialogButtonBox.ActionRole ) uninstallButton.setIcon( self.style().standardIcon(getattr(QStyle, 'SP_TrashIcon')) ) uninstallButton.clicked.connect(self._onUninstallButtonClicked) hbox.addWidget(button_box) bottom.setLayout(hbox) bottom.setContentsMargins(0, 0, 0, 0) pluginInfoLabel = QLabel( """ <h2>%s <small>%s</small></h2> <p>%s</p> <p></p>""" % (pluginEntry["pluginname"], pluginEntry["version"], pluginEntry["doc"])) pluginInfoLabel.setWordWrap(True) vbox = QVBoxLayout() vbox.addWidget(pluginInfoLabel) vbox.addWidget(bottom) self.setLayout(vbox)
class InputStringDialog(QDialog): def __init__(self, parent: QWidget = None): super(InputStringDialog, self).__init__(parent) self._value = "" # layout self._layout = QVBoxLayout() self.setLayout(self._layout) self._hlayout1 = QHBoxLayout() self._hlayout2 = QHBoxLayout() # input controls self._lbl_prompt = QLabel(self) self._le_text = QLineEdit(self) # buttons # self._btn_ok = QPushButton(self.tr('OK'), self) # self._btn_cancel = QPushButton(self.tr('Cancel'), self) self._btnbox = QDialogButtonBox(self) self._btnbox.addButton(QDialogButtonBox.Ok) self._btnbox.addButton(QDialogButtonBox.Cancel) self._btnbox.accepted.connect(self.on_ok) self._btnbox.rejected.connect(self.on_cancel) # # finalize layout self._hlayout1.addWidget(self._lbl_prompt) self._hlayout1.addWidget(self._le_text) self._hlayout2.addWidget(self._btnbox) self._layout.addLayout(self._hlayout1) self._layout.addLayout(self._hlayout2) def value(self) -> str: return self._value def setValue(self, v: str): self._value = v self._le_text.setText(self._value) def setPrompt(self, p: str): self._lbl_prompt.setText(p) @pyqtSlot() def on_ok(self): self._value = self._le_text.text() self.accept() @pyqtSlot() def on_cancel(self): self.reject()
def __init__(self, parent=None): super(MusicPreviewDialog, self).__init__(parent) layout = QVBoxLayout() self.setLayout(layout) self._widget = MusicPreviewWidget() layout.addWidget(self._widget) layout.addWidget(widgets.Separator()) b = QDialogButtonBox() layout.addWidget(b) b.addButton(QDialogButtonBox.Close) b.rejected.connect(self.accept) self._printButton = b.addButton('', QDialogButtonBox.ActionRole) self._printButton.setIcon(icons.get("document-print")) self._printButton.clicked.connect(self._widget.print_) self._printButton.hide() qutil.saveDialogSize(self, "musicpreview/dialog/size", QSize(500, 350)) app.translateUI(self)
def __init__(self, unsaved_files, parent=None): super().__init__(parent) self._ninja = parent self.setWindowTitle(translations.TR_IDE_CONFIRM_EXIT_TITLE) vbox = QVBoxLayout(self) self._unsave_files_list = QListWidget() self._unsave_files_list.setSelectionMode(QListWidget.ExtendedSelection) vbox.addWidget(QLabel(translations.TR_IDE_CONFIRM_EXIT_BODY)) vbox.addWidget(self._unsave_files_list) button_box = QDialogButtonBox(self) standard_icon = self.style().standardIcon btn = button_box.addButton( translations.TR_CANCEL, QDialogButtonBox.RejectRole) btn.setIcon(standard_icon(self.style().SP_DialogCloseButton)) self._btn_save_selected = button_box.addButton( translations.TR_SAVE_SELECTED, QDialogButtonBox.AcceptRole) self._btn_save_selected.setIcon( standard_icon(self.style().SP_DialogSaveButton)) btn_save_all = button_box.addButton( translations.TR_SAVE_ALL, QDialogButtonBox.AcceptRole) btn_save_all.setIcon(standard_icon(self.style().SP_DialogApplyButton)) btn_donot_save = button_box.addButton( translations.TR_DONOT_SAVE, QDialogButtonBox.DestructiveRole) btn_donot_save.setIcon(standard_icon(self.style().SP_DialogNoButton)) vbox.addWidget(button_box) for nfile in unsaved_files: item = QListWidgetItem(nfile.display_name) item.setData(Qt.UserRole, nfile) item.setToolTip(nfile.file_path) self._unsave_files_list.addItem(item) # Connections button_box.rejected.connect(self.reject) button_box.accepted.connect(self._save_selected) btn_donot_save.clicked.connect(self._discard) btn_save_all.clicked.connect(self._save_all) self._unsave_files_list.itemSelectionChanged.connect( self._on_selection_changed) self._unsave_files_list.selectAll()
def _createEarlyCrashDialog(self): dialog = QDialog() dialog.setMinimumWidth(500) dialog.setMinimumHeight(170) dialog.setWindowTitle(catalog.i18nc("@title:window", "Cura can't start")) dialog.finished.connect(self._closeEarlyCrashDialog) layout = QVBoxLayout(dialog) label = QLabel() label.setText(catalog.i18nc("@label crash message", """<p><b>Oops, Ultimaker Cura has encountered something that doesn't seem right.</p></b> <p>We encountered an unrecoverable error during start up. It was possibly caused by some incorrect configuration files. We suggest to backup and reset your configuration.</p> <p>Backups can be found in the configuration folder.</p> <p>Please send us this Crash Report to fix the problem.</p> """)) label.setWordWrap(True) layout.addWidget(label) # "send report" check box and show details self._send_report_checkbox = QCheckBox(catalog.i18nc("@action:button", "Send crash report to Ultimaker"), dialog) self._send_report_checkbox.setChecked(True) show_details_button = QPushButton(catalog.i18nc("@action:button", "Show detailed crash report"), dialog) show_details_button.setMaximumWidth(200) show_details_button.clicked.connect(self._showDetailedReport) show_configuration_folder_button = QPushButton(catalog.i18nc("@action:button", "Show configuration folder"), dialog) show_configuration_folder_button.setMaximumWidth(200) show_configuration_folder_button.clicked.connect(self._showConfigurationFolder) layout.addWidget(self._send_report_checkbox) layout.addWidget(show_details_button) layout.addWidget(show_configuration_folder_button) # "backup and start clean" and "close" buttons buttons = QDialogButtonBox() buttons.addButton(QDialogButtonBox.Close) buttons.addButton(catalog.i18nc("@action:button", "Backup and Reset Configuration"), QDialogButtonBox.AcceptRole) buttons.rejected.connect(self._closeEarlyCrashDialog) buttons.accepted.connect(self._backupAndStartClean) layout.addWidget(buttons) return dialog
def show(type, value, tb): if not hasattr(sys, "frozen"): traceback.print_exception(type, value, tb) 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("@info", "<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(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(self._i18n_catalog.i18nc("action:button", "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_() sys.exit(1)
def __init__(self, parent=None): super(Client, self).__init__(parent) self.blockSize = 0 self.currentFortune = None hostLabel = QLabel("&Server name:") self.hostLineEdit = QLineEdit("fortune") hostLabel.setBuddy(self.hostLineEdit) self.statusLabel = QLabel( "This examples requires that you run the Fortune Server " "example as well.") self.statusLabel.setWordWrap(True) self.getFortuneButton = QPushButton("Get Fortune") self.getFortuneButton.setDefault(True) quitButton = QPushButton("Quit") buttonBox = QDialogButtonBox() buttonBox.addButton(self.getFortuneButton, QDialogButtonBox.ActionRole) buttonBox.addButton(quitButton, QDialogButtonBox.RejectRole) self.socket = QLocalSocket() self.hostLineEdit.textChanged.connect(self.enableGetFortuneButton) self.getFortuneButton.clicked.connect(self.requestNewFortune) quitButton.clicked.connect(self.close) self.socket.readyRead.connect(self.readFortune) self.socket.error.connect(self.displayError) mainLayout = QGridLayout() mainLayout.addWidget(hostLabel, 0, 0) mainLayout.addWidget(self.hostLineEdit, 0, 1) mainLayout.addWidget(self.statusLabel, 2, 0, 1, 2) mainLayout.addWidget(buttonBox, 3, 0, 1, 2) self.setLayout(mainLayout) self.setWindowTitle("Fortune Client") self.hostLineEdit.setFocus()
class LineUI: """ Set up the folder widgets """ def __init__(self, name, value, method=None, button_text="Select..."): self.label = QLabel(name + ":") self.line = QLineEdit(value) self.line.setMinimumWidth(600) # swag self.select_button = QDialogButtonBox() self.line.setReadOnly(True) # guide user via dialog boxes - don't allow them to just type anything in if method: self.select_button.addButton(button_text, QDialogButtonBox.AcceptRole) self.select_button.accepted.connect(method) def layout(self, grid, column): grid.addWidget(self.label, column, 0) grid.addWidget(self.line, column, 1) grid.addWidget(self.select_button, column, 2) def get(self): return self.line.text()
class DialogSRPM(QtWidgets.QDialog): def __init__(self, Dialog, Wizard, parent=None): super(DialogSRPM, self).__init__(parent) # Setting self.setMinimumSize(QtCore.QSize(350, 150)) self.setMaximumSize(QtCore.QSize(500, 300)) # Setting label SrpmLabel = QLabel("Do you wish to edit source code?") # Setting buttons self.editButton = QPushButton("Edit") self.editButton.clicked.connect(self.openFileBrowser) 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) # Setting layout mainLayout = QVBoxLayout() mainLayout.addWidget(SrpmLabel) mainLayout.addWidget(self.editButton) mainLayout.addWidget(self.boxButtons) self.setLayout(mainLayout) def openFileBrowser(self): ''' If user clicked "Edit" button''' brows = QFileDialog() brows.getOpenFileName(self, "/home") def acceptIt(self): ''' If user clicked "OK" button ''' self.accept()
def __init__(self, parent=None): super(Dialog, self).__init__(parent) self.tcpServer = QTcpServer() self.tcpClient = QTcpSocket() self.bytesToWrite = 0 self.bytesWritten = 0 self.bytesReceived = 0 self.clientProgressBar = QProgressBar() self.clientStatusLabel = QLabel("Client ready") self.serverProgressBar = QProgressBar() self.serverStatusLabel = QLabel("Server ready") self.startButton = QPushButton("&Start") self.quitButton = QPushButton("&Quit") buttonBox = QDialogButtonBox() buttonBox.addButton(self.startButton, QDialogButtonBox.ActionRole) buttonBox.addButton(self.quitButton, QDialogButtonBox.RejectRole) self.startButton.clicked.connect(self.start) self.quitButton.clicked.connect(self.close) self.tcpServer.newConnection.connect(self.acceptConnection) self.tcpClient.connected.connect(self.startTransfer) self.tcpClient.bytesWritten.connect(self.updateClientProgress) self.tcpClient.error.connect(self.displayError) mainLayout = QVBoxLayout() mainLayout.addWidget(self.clientProgressBar) mainLayout.addWidget(self.clientStatusLabel) mainLayout.addWidget(self.serverProgressBar) mainLayout.addWidget(self.serverStatusLabel) mainLayout.addStretch(1) mainLayout.addSpacing(10) mainLayout.addWidget(buttonBox) self.setLayout(mainLayout) self.setWindowTitle("Loopback")
def initUI(self): StoryTypeLayer = FlowLayout() for key in WdStoryType.keys(): widget = QCheckBox(WdStoryType[key][1] if WdStoryType[key][1] != "" else WdStoryType[key][0]) widget.setObjectName("WdStoryType." + str(key)) widget.setCheckState(WdStoryType[key][2]) widget.setEnabled(widget.checkState() != 1) widget.setMinimumWidth(230) StoryTypeLayer.addWidget(widget) self.StoryTypeWdgList.append(widget) self.apply() hbox = QVBoxLayout() hbox.addLayout(StoryTypeLayer) btnGrp = QDialogButtonBox() btnClose = QPushButton("Закрыть") btnGrp.addButton(btnClose, QDialogButtonBox.ActionRole) hbox.addWidget(btnGrp) btnClose.clicked.connect(self.close) self.setLayout(hbox) self.setGeometry(500, 100, 500, 400) self.setWindowTitle("Опции") self.setWindowFlags(Qt.Dialog | Qt.WindowMinMaxButtonsHint | Qt.WindowCloseButtonHint)
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")