def _setup_ui(self): btn_layout = self.findChild(QWidget, 'btn_layout') conn_name = self.findChild(QWidget, 'name_txt') conn_name_validator = QRegExpValidator(conn_name) conn_name_validator.setRegExp(QtCore.QRegExp('([a-zA-Z]{2})(.*)')) conn_name.setValidator(conn_name_validator) self.findChild(QWidget, 'name_txt').setText(self.old_conn_name) self.findChild(QWidget, 'conf_dir_txt').setText(self.conn['conf-dir']) self.findChild(QWidget, 'ovpn_file_txt').setText(self.conn['ovpn-file']) self.findChild(QWidget, 'title_lbl').setText('Edit Connection') btn_layout.setStandardButtons(QDialogButtonBox.Save | QDialogButtonBox.Close) self.setWindowTitle('Edit Connection')
def __init__(self): """ Constructor """ super(CooperationPage, self).__init__() self.setupUi(self) self.setObjectName("CooperationPage") self.__bannedUserValidator = QRegExpValidator( QRegExp("[a-zA-Z0-9.-]+@" "(?:(?:2(?:[0-4][0-9]|5[0-5])|[01]?[0-9]{1,2})\.){3}" "(?:2(?:[0-4][0-9]|5[0-5])|[01]?[0-9]{1,2})"), self.bannedUserEdit) self.bannedUserEdit.setValidator(self.__bannedUserValidator) # set initial values self.autostartCheckBox.setChecked( Preferences.getCooperation("AutoStartServer")) self.otherPortsCheckBox.setChecked( Preferences.getCooperation("TryOtherPorts")) self.serverPortSpin.setValue( Preferences.getCooperation("ServerPort")) self.portToTrySpin.setValue( Preferences.getCooperation("MaxPortsToTry")) self.autoAcceptCheckBox.setChecked( Preferences.getCooperation("AutoAcceptConnections")) self.bannedUsersList.addItems(sorted( Preferences.getCooperation("BannedUsers")))
class SpinBoxHex(QSpinBox): def __init__(self, parent=None, default_value=0): super().__init__(parent) self.validator = QRegExpValidator(QRegExp('^([ ]*[0-9A-Fa-f][ ]*){1,8}$'), self) self.setValue(default_value) def validate(self, text, pos): return self.validator.validate(text, pos) def valueFromText(self, text): return min(int(text.replace(' ', ''), 16), (1 << 31) - 1) def textFromValue(self, value): s = '' for i, c in enumerate(reversed(hex(value).replace('0x', '').upper())): if i % 2 == 0: s = ' ' + s s = c + s s = s.strip() if len(s.replace(' ', '')) % 2 == 1: s = '0' + s return s
class TimeSpinBox(QSpinBox): """Custom widget to collect an interval in time, used primarily in the settings dialog""" SUFFIXES = {'s': 1, 'm':60, 'h':60*60, 'd':60*60*24} def __init__(self, parent=None, time=900): super(TimeSpinBox, self).__init__(parent) self.validator = QRegExpValidator(QRegExp(r'(\d+\s*[{}]\s*)+'.format(''.join([key for key in self.SUFFIXES.keys()]), Qt.CaseInsensitive))) self.setMaximum(60*60*24*7 - 1) self.setValue(time) def validate(self, text, pos): '''Overriden validation alidate using regex''' return self.validator.validate(text, pos) def textFromValue(self, value): '''Overriden method to get the line edit's text from a value in seconds''' text = '' # add a #s entry to the text per suffix for suffix in sorted(self.SUFFIXES): if value >= self.SUFFIXES[suffix]: text += '{}{}{}'.format('' if text == '' else ' ', value//self.SUFFIXES[suffix], suffix) value %= self.SUFFIXES[suffix] elif text != '': text += ' 0{}'.format(suffix) return text def valueFromText(self, value): '''Overriden method to get the value in seconds from the line edit's text''' num = 0 # get the number of each extension and multiply by their value in SUFFIXES for suffix in self.SUFFIXES: entry = re.search(r"(\d+)\s*{}".format(suffix), value) if entry: num += int(entry.group(1))*self.SUFFIXES[suffix] return num
def __init__(self, parent=None): super(lineEditDemo, self).__init__(parent) self.setWindowTitle("QLineEdit例子") flo = QFormLayout() pIntLineEdit = QLineEdit( ) pDoubleLineEdit = QLineEdit() pValidatorLineEdit = QLineEdit( ) flo.addRow("整形", pIntLineEdit) flo.addRow("浮点型", pDoubleLineEdit) flo.addRow("字母和数字", pValidatorLineEdit) pIntLineEdit.setPlaceholderText("整形"); pDoubleLineEdit.setPlaceholderText("浮点型"); pValidatorLineEdit.setPlaceholderText("字母和数字"); # 整形 范围:[1, 99] pIntValidator = QIntValidator(self) pIntValidator.setRange(1, 99) # 浮点型 范围:[-360, 360] 精度:小数点后2位 pDoubleValidator = QDoubleValidator(self) pDoubleValidator.setRange(-360, 360) pDoubleValidator.setNotation(QDoubleValidator.StandardNotation) pDoubleValidator.setDecimals(2) # 字符和数字 reg = QRegExp("[a-zA-Z0-9]+$") pValidator = QRegExpValidator(self) pValidator.setRegExp(reg) # 设置验证器 pIntLineEdit.setValidator(pIntValidator) pDoubleLineEdit.setValidator(pDoubleValidator) pValidatorLineEdit.setValidator(pValidator) self.setLayout(flo)
def __init__(self): super(UCastApp, self).__init__() self.ui = gui.Ui_MainWindow() self.ui.setupUi(self) self.cubes = [] for i in range(8): self.ui.tableFiles.horizontalHeader().setSectionResizeMode( i, QHeaderView.Stretch) # Signals self.ui.btnLoadDay.clicked.connect(self._loadDayPressed) self.ui.btnSaveClean.clicked.connect(self._saveFile) self.ui.btnUnload.clicked.connect(self._unloadPressed) self.ui.btnPlot.clicked.connect(self.plotPressed) self.ui.btnTrain.clicked.connect(self.trainPressed) self.ui.btnPredict.clicked.connect(self.predictPressed) self.ui.btnClean.clicked.connect(self.cleanPressed) self.ui.btnTruncate.clicked.connect(self.truncatePressed) self.ui.ddFeature.activated['QString'].connect( lambda text: self.ui.gbFeatures.hide() if text == "VIL" else self.ui.gbFeatures.show()) # Validators self.ui.txtEpoch.setValidator(QIntValidator(0, 10000, self.ui.txtEpoch)) re_int_list = QRegExp("([0-9]+,)*[0-9]+") valid_re_int_list = QRegExpValidator(re_int_list) self.ui.txtTrainTimestamps.setValidator(valid_re_int_list) self.ui.txtPredictTimestamps.setValidator(valid_re_int_list) truncate_validator = QIntValidator(0, 1000) self.ui.txtTimestampStart.setValidator(truncate_validator) self.ui.txtTimestampEnd.setValidator(truncate_validator) self.ui.txtXStart.setValidator(truncate_validator) self.ui.txtXEnd.setValidator(truncate_validator) self.ui.txtYStart.setValidator(truncate_validator) self.ui.txtYEnd.setValidator(truncate_validator) self.populate_list()
def createEditor(self, parent, option, index): if index.column() != 2: return None originalValue = index.model().data(index, Qt.UserRole) if not self.isSupportedType(originalValue): return None lineEdit = QLineEdit(parent) lineEdit.setFrame(False) if isinstance(originalValue, bool): regExp = self.boolExp elif isinstance(originalValue, float): regExp = self.doubleExp elif isinstance(originalValue, int): regExp = self.signedIntegerExp elif isinstance(originalValue, QByteArray): regExp = self.byteArrayExp elif isinstance(originalValue, QColor): regExp = self.colorExp elif isinstance(originalValue, QDate): regExp = self.dateExp elif isinstance(originalValue, QDateTime): regExp = self.dateTimeExp elif isinstance(originalValue, QTime): regExp = self.timeExp elif isinstance(originalValue, QPoint): regExp = self.pointExp elif isinstance(originalValue, QRect): regExp = self.rectExp elif isinstance(originalValue, QSize): regExp = self.sizeExp else: regExp = QRegExp() if not regExp.isEmpty(): validator = QRegExpValidator(regExp, lineEdit) lineEdit.setValidator(validator) return lineEdit
def __init__(self, project_manager: ProjectManager, is_tx: bool, backend_handler: BackendHandler = None, continuous_send_mode=False, parent=None): super().__init__(parent) self.ui = Ui_FormDeviceSettings() self.ui.setupUi(self) self.__device = None # type: VirtualDevice self.is_tx = is_tx self.is_rx = not is_tx if backend_handler is None: self.backend_handler = BackendHandler() else: self.backend_handler = backend_handler if self.is_rx: self.ui.spinBoxNRepeat.hide() self.ui.labelNRepeat.hide() else: self.ui.labelDCCorrection.hide() self.ui.checkBoxDCCorrection.hide() self.bw_sr_are_locked = constants.SETTINGS.value("lock_bandwidth_sample_rate", True, bool) self.ui.cbDevice.clear() items = self.get_devices_for_combobox(continuous_send_mode) self.ui.cbDevice.addItems(items) self.bootstrap(project_manager.device_conf, enforce_default=True) self.ui.btnLockBWSR.setChecked(self.bw_sr_are_locked) self.on_btn_lock_bw_sr_clicked() ip_range = "(?:[0-1]?[0-9]?[0-9]|2[0-4][0-9]|25[0-5])" ip_regex = QRegExp("^" + ip_range + "\\." + ip_range + "\\." + ip_range + "\\." + ip_range + "$") self.ui.lineEditIP.setValidator(QRegExpValidator(ip_regex)) self.create_connects() self.sync_gain_sliders()
def initUI(self): self.resize(350, 100) self.setWindowTitle("密码输入框") self.lb = QLabel("请输入密码:", self) self.edit = QLineEdit(self) self.edit.installEventFilter(self) self.bt1 = QPushButton("确定", self) self.bt2 = QPushButton("取消", self) hbox = QHBoxLayout() hbox.addStretch(1) hbox.addWidget(self.bt1) hbox.addStretch(1) hbox.addWidget(self.bt2) hbox.addStretch(1) vbox = QVBoxLayout() vbox.addWidget(self.lb) vbox.addWidget(self.edit) vbox.addStretch(1) vbox.addLayout(hbox) self.setLayout(vbox) self.edit.setContextMenuPolicy(Qt.NoContextMenu) self.edit.setPlaceholderText("密码不超15位,只能有数字和字母,必须以字母开头") self.edit.setEchoMode(QLineEdit.Password) regx = QRegExp("^[a-zA-Z][0-9A-Za-z]{14}$") print('111') validator = QRegExpValidator(regx, self.edit) print('222') self.edit.setValidator(validator) self.bt1.clicked.connect(self.Ok) self.bt2.clicked.connect(self.Cancel) object = QObject()
def __init__(self, i): super().__init__() font = QFont("MS Shell Dig 2", 14) self.layout = QHBoxLayout() self.setLayout(self.layout) self.i = i self.label = QLabel(f'a{i}') self.label.setFont(font) self.value_label = QLineEdit() self.value_label.setValidator( QRegExpValidator(QRegExp(r'(0([\.|,]\d{1,4})?|1([\.|,]0{1,4})?)'))) self.value_label.setFont(font) self.value_label.setFixedWidth(110) self.layout.addWidget(self.label) self.layout.addWidget(self.value_label) self.value_label.editingFinished.connect( lambda: self.text_changed.emit(self))
def __init_filter_grid(self, title: str): local_layout = QVBoxLayout() local_layout.setAlignment(Qt.AlignBottom) frame = QGroupBox(title) grid = QGridLayout() # Regular expresion that will allow to input only int or float (dot seperated) regex = QRegExp(r"[-+]?\d*\.\d+|\d+") self.__kernel_matrix = [ [QLineEdit() for _ in range(self.__options['INPUTS_WIDTH'])] for _ in range(self.__options['INPUTS_WIDTH']) ] for i, row in enumerate(self.__kernel_matrix): for j, input_elem in enumerate(row): input_elem.setValidator(QRegExpValidator(regex)) grid.addWidget(input_elem, i, j) frame.setLayout(grid) local_layout.addWidget(frame) self.__main_grid.addLayout(local_layout)
def __init__(self, parent=None, *args, **kwargs): super().__init__(parent, *args, **kwargs) self.resize(400, 400) self.btn = QPushButton(self) self.btn.resize(60, 40) self.btn.move(340, 360) self.btn.setText("测试") self.te = QLabel(self) self.le = QLineEdit(self) self.le.move(0,20) # self.setting = QSettings("cctv.dat",QSettings.InvalidFormat self.timeTd = TimeThread() self.timeTd.start() # 正则表达式 pattern = QRegExp('^([1-9]|[1-9]\\d{3}|[1-6][0-5][0-5][0-3][0-5])$') portValidator = QRegExpValidator(pattern) self.le.setValidator(portValidator) self.btn.clicked.connect(self.test7) self.timeTd.show_time_signal.connect(self.display_time)
def __init__(self, checksum_label: ChecksumLabel, message: Message, proto_view: int, parent=None): super().__init__(parent) self.ui = Ui_ChecksumOptions() self.ui.setupUi(self) self.checksum_label = checksum_label self.data_range_table_model = self.RangeTableModel(checksum_label, message, proto_view, parent=self) self.ui.tableViewDataRanges.setItemDelegateForColumn(0, SpinBoxDelegate(1, 999999, self)) self.ui.tableViewDataRanges.setItemDelegateForColumn(1, SpinBoxDelegate(1, 999999, self)) self.ui.tableViewDataRanges.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch) self.ui.tableViewDataRanges.setModel(self.data_range_table_model) self.ui.tableViewDataRanges.setEditTriggers(QAbstractItemView.AllEditTriggers) self.display_crc_data_ranges_in_table() self.ui.comboBoxCRCFunction.addItems([crc_name for crc_name in GenericCRC.DEFAULT_POLYNOMIALS]) self.ui.comboBoxCRCFunction.addItems([special_crc_name for special_crc_name in self.SPECIAL_CRCS]) self.ui.lineEditCRCPolynomial.setValidator(QRegExpValidator(QRegExp("[0-9,a-f]*"))) self.ui.comboBoxCategory.clear() for _, member in self.checksum_label.Category.__members__.items(): self.ui.comboBoxCategory.addItem(member.value) self.set_ui_for_category() self.setFocus() self.create_connects()
def at_time(self): logging.debug('at_time() called') self.at_time_input = QWidget() self.at_time_layout = QVBoxLayout(self.at_time_input) self.time_text = QLabel() self.time_text.setText(QC.translate('', 'At:')) self.time_input = QLineEdit() regexp_validator = QRegExp('^([0-9]|0[0-9]|1[0-9]|2[0-3]):[0-5][0-9]$') self.time_validator = QRegExpValidator(regexp_validator) self.time_input.setValidator(self.time_validator) self.time_input.setPlaceholderText(QC.translate('', 'hh:mm')) self.at_time_layout.addWidget(self.time_text) self.at_time_layout.addWidget(self.time_input) self.at_time_input.hide() self.options_box_layout.addWidget(self.at_time_input)
class RomanSpinBox(QSpinBox): def __init__(self, parent=None): super(RomanSpinBox, self).__init__(parent) regex = QRegExp(r"^M?M?M?(?:CM|CD|D?C?C?C?)" r"(?:XC|XL|L?X?X?X?)(?:IX|IV|V?I?I?I?)$") regex.setCaseSensitivity(Qt.CaseInsensitive) self.validator = QRegExpValidator(regex, self) self.setRange(1, 3999) self.valueChanged[str].connect(self.fixCase) def fixCase(self, text): self.lineEdit().setText(text.upper()) def validate(self, text, pos): return self.validator.validate(text, pos) def valueFromText(self, text): return intFromRoman(str(text)) def textFromValue(self, value): return romanFromInt(value)
def connectToComboBox(self, comboBox): if (self.mComboBox): self.mComboBox.disconnect() if (self.mComboBox.lineEdit()): self.mComboBox.lineEdit().disconnect() self.mComboBox.setValidator(None) self.mComboBox = comboBox if type(comboBox) is QComboBox: self.mComboBox.clear() for scale in self.mZoomFactors: self.mComboBox.addItem(scaleToString(scale), scale) self.syncComboBox() self.mComboBox.activated.connect(self.comboActivated) self.mComboBox.setEditable(True) self.mComboBox.setInsertPolicy(QComboBox.NoInsert) self.mComboBox.lineEdit().editingFinished.connect(self.comboEdited) if (not self.mComboValidator): self.mComboValidator = QRegExpValidator( self.mComboRegExp, self) self.mComboBox.setValidator(self.mComboValidator)
def __init__(self, *args, **kwargs): QtWidgets.QMainWindow.__init__(self, *args, **kwargs) self.setupUi(self) #Inicializando botones y esas weas self.threadpool = QThreadPool() #rx = QRegExp("[0-9]\.?[0-9]*") #validator = QRegExpValidator(rx, self) #self.lineCelda.setValidator(validator) self.lineXPunto.setText('1') self.lineYPunto.setText('1') rx2 = QRegExp("[+-]?[0-9]*\.[0-9]*") validator2 = QRegExpValidator(rx2, self) self.lineXPunto.setValidator(validator2) self.lineYPunto.setValidator(validator2) #self.comboSeparador.addItems([';',',','Tab','Espacio']) #self.separadores = {',':',',';':';','Tab':'\t','Espacio':' '} self.diccionario = {} self.datos = None self.archivo = None self.grafico2D = pyplot.figure(figsize=(8, 8)) self.canvas = FigureCanvas(self.grafico2D) self.toolbar = NavigationToolbar(self.canvas, self) layout = QVBoxLayout() layout.addWidget(self.toolbar) layout.addWidget(self.canvas) self.widgetGrafico.setLayout(layout) self.colores = list(colors.TABLEAU_COLORS) self.btnInsertarPunto.clicked.connect(lambda: self.insertarPunto( self.lineXPunto.text(), self.lineYPunto.text()))
def __init__(self, parent=None, index=None, codes_analytiques=None, datas=None): self.parent = parent self.index = index self.model = parent.model self.codes_analytiques = codes_analytiques self.product = QLineEdit() self.prix = QLineEdit() self.code_analytique_box = QComboBox() self.code_compta_box = QComboBox() self.remove_button = QPushButton("-") self.layout = QHBoxLayout() self.product.setPlaceholderText("Désignation") self.refresh_code_analytique() self.refresh_code_compta() for widget in (self.prix, self.product, self.code_compta_box, self.code_analytique_box): widget.setStyleSheet(':disabled {color:#333}') regexp = QRegExp('\d[\d\.]+') self.prix.setValidator(QRegExpValidator(regexp)) self.prix.setPlaceholderText("Prix") self.remove_button.setMaximumWidth(20) self.remove_button.clicked.connect(self.clear_layout) self.code_analytique_box.currentIndexChanged.connect( self.refresh_code_compta) self.layout.addWidget(self.product, stretch=8) self.layout.addWidget(self.prix, stretch=3) self.layout.addWidget(self.code_analytique_box, stretch=5) self.layout.addWidget(self.code_compta_box, stretch=10) self.layout.addWidget(self.remove_button, stretch=1) if datas: self.populate(datas)
def input_fields_group(self): # Function for the input fields group self.input_fields_group_box = QGroupBox("User Input Fields") self.loan_amount_label = QLabel("Loan Amount: ") self.interest_rate_label = QLabel("Interest Rate (%): ") self.number_of_years_label = QLabel("Number of Years: ") self.number_of_payment_per_year_label = QLabel( "No. of Payments Per Year: ") self.loan_amount_edit = QLineEdit() self.loan_amount_edit.setMaxLength(9) self.loan_amount_edit.setValidator(QDoubleValidator(0.0, 999999.99, 2)) self.loan_amount_edit.setPlaceholderText("Enter the Loan Amount") self.interest_rate_edit = QLineEdit() self.interest_rate_edit.setMaxLength(5) self.interest_rate_edit.setValidator( QDoubleValidator(0.0, 999999.99, 3)) regex_line_edit = QRegExp("^[1-9][0-9]*") validator = QRegExpValidator(regex_line_edit) self.num_of_years_edit = QLineEdit() self.num_of_years_edit.setMaxLength(2) self.num_of_years_edit.setValidator(validator) self.num_payment_per_yr_edit = QLineEdit() self.num_payment_per_yr_edit.setMaxLength(2) self.num_payment_per_yr_edit.setValidator(validator) input_gbox = QGridLayout() input_gbox.addWidget(self.loan_amount_label, 0, 0) input_gbox.addWidget(self.interest_rate_label, 1, 0) input_gbox.addWidget(self.number_of_years_label, 2, 0) input_gbox.addWidget(self.number_of_payment_per_year_label, 3, 0) input_gbox.addWidget(self.loan_amount_edit, 0, 1) input_gbox.addWidget(self.interest_rate_edit, 1, 1) input_gbox.addWidget(self.num_of_years_edit, 2, 1) input_gbox.addWidget(self.num_payment_per_yr_edit, 3, 1) self.input_fields_group_box.setLayout(input_gbox) return self.input_fields_group_box
def onClickedTypeOne(self, btn): if btn.objectName() == '1' and self.groupOne: self.groupOne = False self.sysType.append((QRadioButton(TEXT.REPLACEMENT, objectName='0'), QRadioButton(TEXT.PERMANENT, objectName='1'))) self.btnGroupTwo = QButtonGroup(self) self.btnGroupTwo.addButton(self.sysType[1][0]) self.btnGroupTwo.addButton(self.sysType[1][1]) self.sysType[1][1].setChecked(True) self.FormLayout.addRow(self.sysType[1][0], self.sysType[1][1]) self.sysType.append((QRadioButton(TEXT.BY_ELEMENTS, objectName='0'), QRadioButton(TEXT.WHOLE, objectName='1'))) self.btnGroupThree = QButtonGroup(self) self.btnGroupThree.addButton(self.sysType[2][0]) self.btnGroupThree.addButton(self.sysType[2][1]) self.sysType[2][0].setChecked(True) self.groupThree = True self.btnGroupThree.buttonClicked.connect(self.onClickedTypeThree) self.FormLayout.addRow(self.sysType[2][0], self.sysType[2][1]) self.isSame = QCheckBox(TEXT.LB_THE_SAME_VALUE) self.FormLayout.addWidget(self.isSame) self.row = QLineEdit() self.row.setPlaceholderText(TEXT.LEP_1_OR_MORE) regexp = QtCore.QRegExp('^([1-9]\\d{0,1})$') validator = QRegExpValidator(regexp) # QIntValidator(1, 15) self.row.setValidator(validator) self.row.textChanged.connect(self.check_state) self.row.textChanged.emit(self.row.text()) self.FormLayout.addRow(QLabel(TEXT.LB_THE_BACKUP_ELM_COUNT), self.row) elif btn.objectName() == '0' and not self.groupOne: self.groupOne = True self.sysType = self.sysType[:1] for i in range(5, self.FormLayout.count(), 2): self.FormLayout.removeRow(3)
def ui(self): # QRegExp是Qt的正则表达式,此处禁用键盘,即把任意非空内容都过滤掉 reg = QRegExp("^$") # 把键盘禁用了, 仅可以按钮的输入 validator = QRegExpValidator(reg, self) # 这个line_edit即计算器显示区,是一个文本编辑区 self.line_edit = QLineEdit('0', self) self.line_edit.setAlignment(Qt.AlignRight) self.line_edit.setValidator(validator) # 将该区域设置为只读 self.line_edit.setReadOnly(True) # 使用girdlayout进行界面布局 grid = QGridLayout() self.setLayout(grid) # 计算器界面上各个按钮显示的名字 btn_names = [ 'C', 'x^y', 'x^2', '/', '7', '8', '9', '*', '4', '5', '6', '-', '1', '2', '3', '+', '0', '', '.', '=' ] # 先在界面上将定义好的显示区添加,设置尺寸 grid.addWidget(self.line_edit, 0, 0, 1, 4) # i代表行数,j代表列数,将布局中的每个按键坐标位置和按键名称匹配 positions = [(i, j) for i in range(1, 6) for j in range(4)] for pos, name in zip(positions, btn_names): if name == '': continue btn = QPushButton(name) # 在布局的时候,直接把每个按钮连接到点击事件上 btn.clicked.connect(self.show_msg) if name == '0': tmp_pos = (pos[0], pos[1] + 1) grid.addWidget(btn, *pos, 1, 2) else: grid.addWidget(btn, *pos) self.setFocusPolicy(Qt.StrongFocus) self.setWindowTitle('Calculator') # 设置计算器界面在桌面显示位置 self.move(300, 150) self.show()
def __init__(self, gWindow): super().__init__(gWindow) self.app = QApplication.instance() self.posting = 0 buttonBox = QDialogButtonBox( QDialogButtonBox.Ok | QDialogButtonBox.Cancel, self) self.title = QLineEdit() self.title.setMaximumWidth(600) self.title.setAlignment(Qt.AlignCenter) self.title.textEdited.connect(self.onTitleEdited) regexp = QRegExp(r"[\w_-\s.,:;\"'?]+") self.title.setValidator(QRegExpValidator(regexp)) self.title.setMaxLength(128) titleLayout = QHBoxLayout() titleLayout.setSpacing(64) titleLayout.addItem( QSpacerItem(100, 10, QSizePolicy.Minimum, QSizePolicy.Minimum)) titleLayout.addWidget(QLabel('Title')) titleLayout.addWidget(self.title) titleLayout.addItem( QSpacerItem(10, 10, QSizePolicy.Expanding, QSizePolicy.Minimum)) self.markdownInput = MarkdownInputWidget() self.vLayout.setContentsMargins(20, 20, 20, 20) self.vLayout.addLayout(titleLayout) self.vLayout.addWidget(self.markdownInput) self.vLayout.addWidget(buttonBox, 0, Qt.AlignCenter) buttonBox.accepted.connect(partialEnsure(self.process)) buttonBox.rejected.connect(partialEnsure(self.postCancelled)) self.title.setFocus(Qt.OtherFocusReason)
def __init__(self, parent=None): # noinspection PyArgumentList super(FindServerUI, self).__init__(parent) self.setAttribute(Qt.WA_DeleteOnClose) uic.loadUi("ui/ModalAutoFind.ui", self) # Getting the configuration from config.ini file self.config = config.get_config() # self.from_ip = self.config["SETTINGS"]["find_from_range"] self.range_from.setText(self.from_ip) self.to_ip = self.config["SETTINGS"]["find_to_range"] self.range_to.setText(self.to_ip) # Obligatory line edit list self.linedit_list = [self.range_from, self.range_to] # for linedit in self.linedit_list: linedit.textChanged.connect(partial(self.text_changed, linedit)) # Setting IP validation for the search range ip_validator = QRegExpValidator(config.ip_regex, self) for linedit in self.linedit_list: linedit.setValidator(ip_validator) # Getting the running event loop self.main_loop = get_running_loop() # Setting event for interrupting the task running in thread self.find_event = Event() # Setting buttons clicked actions self.find_button.clicked.connect(self.call_auto_find) self.stop_button.clicked.connect(self.call_stop_find) self.append_button.clicked.connect(self.call_append) self.cancel_button.clicked.connect(self.close) # Setting right-click context menu to check/uncheck all found servers self.search_result.setContextMenuPolicy(Qt.CustomContextMenu) self.search_result.customContextMenuRequested.connect( self.search_result_context_menu)
def __init__(self, message): super().__init__("", message) # Set title label title_label = CustomLabel("Input required") title_label.setStyleSheet(style.NODE_LABEL_STYLE) title_label.setAlignment(Qt.AlignCenter) # Set message label mess_label = CustomLabel("\n" + self.content + "\n") mess_label.setAlignment(Qt.AlignCenter) # Set input reading self.input = None input_line = CustomTextBox() input_line.setValidator( QRegExpValidator( QRegExp(ArithmeticValidator.TENSOR.regExp().pattern() + "|" + ArithmeticValidator.TENSOR_LIST.regExp().pattern()))) # Add buttons to close the dialog confirm_button = CustomButton("Ok") confirm_button.clicked.connect(self.save_input()) cancel_button = CustomButton("Cancel") cancel_button.clicked.connect(self.cancel()) buttons = QWidget() buttons_layout = QHBoxLayout() buttons_layout.addWidget(confirm_button) buttons_layout.addWidget(cancel_button) buttons.setLayout(buttons_layout) # Compose widgets self.layout.addWidget(title_label) self.layout.addWidget(mess_label) self.layout.addWidget(input_line) self.layout.addWidget(buttons) self.render_layout()
def __init__(self): super().__init__() self.video = None self.setupUi(self) self.btn_search.setFocus() regex = QRegExp("\d+") validator = QRegExpValidator(regex) self.edt_seasion.setValidator(validator) self.edt_episode.setValidator(validator) self.btn_search.clicked.connect(self.search_meta) self.spider_search_Manager = None self.spider_dital_Manager = None self.init_spiders('dmm.co.jp', DmmSpider, ':/icons/spider_icons/dmm.ico') self.init_spiders('data18.com', Data18Spider, ':/icons/spider_icons/data18.bmp') self.init_spiders('aventertainments.com', AventertainmentsSpider, ':/icons/spider_icons/aventer.ico') self.init_spiders('kin8tengoku.com', Kin8tengokuSpider, ':/icons/spider_icons/kin8tengoku.ico') self.init_spiders('caribbeancom.com', CaribbeancomSpider, ':/icons/spider_icons/caribbean.ico') self.init_spiders('dvdkanojyo.com', DvdkanojyoSpider, ':/icons/spider_icons/dvdkanojyo.ico') self.init_spiders('themoviedb.org', ThemoviedbSpider, ':/icons/spider_icons/themoviedb.ico') self.btn_dital.clicked.connect(self.search_meta_item_select) self.hs_zoom.setMaximum(200) self.hs_zoom.setProperty("value", 100) self.hs_zoom.valueChanged.connect(self.pic_zoom) self.btn_add.clicked.connect(self.finish_edit) self.btn_cancel.clicked.connect(self.reject) self.meta_return = None self.pices_return = None self.spider_idx = -1 self.btn_select_all.clicked.connect(lambda: self.lst_pices.choose_pic(1)) self.btn_unselect_all.clicked.connect(lambda: self.lst_pices.choose_pic(2)) self.edt_keyword.textChanged.connect(self.auto_change_spdier)
def __init__(self, parent: Optional[Any] = None, name:str = "XorDialog", modal:int = 0, multiLines: bool = False, maxLen:int = -1) -> None: QDialog.__init__(self, parent) self.setupUi(self) # type: ignore # MyPy and PyQt problem self.setModal(modal) self.setObjectName(name) rx = QRegExp( "[A-Fa-f0-9]*" ) validator = QRegExpValidator( rx, self.maskLineEdit ) self.maskLineEdit.setValidator( validator ) if multiLines : self.dataLineEdit.setEnabled(False) self.resultLineEdit.setEnabled(False) self.dataLabel.setEnabled(False) self.resultLabel.setEnabled(False) else: self.maskLineEdit.textChanged.connect(self.slotTextChanged) if maxLen >= 0: self.maskLineEdit.setMaxLength( maxLen )
def initUI(self): self.resize(350, 100) self.setWindowTitle('自定义对话框') self.lb = QLabel("请输入密码", self) self.edit = QLineEdit(self) self.edit.installEventFilter(self) self.bt1 = QPushButton("确定", self) self.bt2 = QPushButton("取消", self) # 水平布局 hbox = QHBoxLayout() hbox.addStretch(1) hbox.addWidget(self.bt1) hbox.addStretch(1) hbox.addWidget(self.bt2) hbox.addStretch(1) # 垂直布局 vbox = QVBoxLayout() vbox.addWidget(self.lb) vbox.addWidget(self.edit) vbox.addStretch(1) vbox.addLayout(hbox) # 使用布局 self.setLayout(vbox) # 设置密码框属性 1.密码框禁止右键 2.密码框为空时,设置密码框规则提示 3.设置输入框显示字符模式 self.edit.setContextMenuPolicy(Qt.NoContextMenu) self.edit.setPlaceholderText("密码6-15位,只能有数字和字母,必须以字母开头") self.edit.setEchoMode(QLineEdit.Password) # 密码校验 regx = QRegExp("^[a-zA-Z][0-9A-Za-z]{14}$") validator = QRegExpValidator(regx, self.edit) self.edit.setValidator(validator) self.bt1.clicked.connect(self.Ok) self.bt2.clicked.connect(self.Cancel) object = QObject()
def __init__(self, **kwargs): parent = kwargs.get('parent', None) super(DataTcpIpDialog, self).__init__(parent) self.ipValue = kwargs.get("ip", '127.0.0.1') self.portValue = kwargs.get("port", 0) ipRange = "(?:[0-1]?[0-9]?[0-9]|2[0-4][0-9]|25[0-5])" # Part of the regular expression # regular expression ipRegex = QRegExp("^" + ipRange + "\\." + ipRange + "\\." + ipRange + "\\." + ipRange + "$") ipValidator = QRegExpValidator(ipRegex, self) mainLayout = QVBoxLayout(self) self.ipData = QLineEdit(self) self.ipData.setText(str(self.ipValue)) self.ipData.setValidator(ipValidator) self.portData = QLineEdit(self) self.portData.setText(str(self.portValue)) self.portData.setValidator(QIntValidator(0, 65535, self)) horizonalLayout = QHBoxLayout() horizonalLayout.addWidget(self.ipData) horizonalLayout.addWidget(self.portData) mainLayout.addLayout(horizonalLayout) # OK and Cancel buttons buttons = QDialogButtonBox( QDialogButtonBox.Ok | QDialogButtonBox.Cancel, Qt.Horizontal, self) buttons.accepted.connect(self.accept) buttons.rejected.connect(self.reject) mainLayout.addWidget(buttons) resPath = getResource("icon.svg") self.icon = QIcon(resPath) self.setWindowIcon(self.icon)
def __init__(self): # Обязательно нужно вызвать метод супер класса QMainWindow.__init__(self) self.setMinimumSize(QSize(480, 80)) # Устанавливаем размеры self.setWindowTitle("Line Edit IP Address") # Устанавливаем заголовок окна central_widget = QWidget(self) # Создаём центральный виджет self.setCentralWidget(central_widget) # Устанавливаем центральный виджет grid_layout = QGridLayout(self) # Создаём QGridLayout central_widget.setLayout(grid_layout) # Устанавливаем данное размещение в центральный виджет grid_layout.addWidget(QLabel("Введите IP-адрес", self), 0, 0) ipRange = "(?:[0-1]?[0-9]?[0-9]|2[0-4][0-9]|25[0-5])" # Часть регулярного выржение # Само регулярное выражение ipRegex = QRegExp("^" + ipRange + "\\." + ipRange + "\\." + ipRange + "\\." + ipRange + "$") ipValidator = QRegExpValidator(ipRegex, self) # Валидатор для QLineEdit lineEdit = QLineEdit() lineEdit.setValidator(ipValidator) # Устанавливаем валидатор grid_layout.addWidget(lineEdit, 0, 1)
def __init__(self, parent=None): super(ConnectionDialog, self).__init__(parent) self.setupUi(self) self.parent = parent Com.onStatusChanged.connect(self.setConnectionStatusSlot) # connect interface signals # self.button_connectToServer.clicked.connect(self.connectClientToServer) # self.button_disconnectFromServer.clicked.connect(Com.disconnectClient) # self.button_removeServerAddress.clicked.connect(self.connectClientToServer) # self.button_addServerAddress.clicked.connect(self.connectClientToServer) # self.button_disconnectFromServer.setEnabled(False) ipValidator = QRegExp( '^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.)' '{3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$') self.ip_box.setValidator(QRegExpValidator(ipValidator, self)) self.ip_box.addItems(['192.168.1.101', '192.168.2.2']) # for item in params.hosts: self.ip_box.addItem(item) print("connection dialog ready")
def __init__(self, Form): self.setupUi(Form) self.pushButton_2.clicked.connect(MainDialog.on_pushButton_2_clicked) self.pushButton_3.clicked.connect(MainDialog.on_pushButton_3_clicked) #dialog.setAttribute(QtCore.Qt.WA_DeleteOnClose) ipRange = "(?:[0-1]?[0-9]?[0-9]|2[0-4][0-9]|25[0-5])" # Part of the regular expression # Regulare expression ipRegex = QRegExp("^" + ipRange + "\\." + ipRange + "\\." + ipRange + "\\." + ipRange + "$") ipValidator = QRegExpValidator(ipRegex, self.lineEdit) self.lineEdit.setValidator(ipValidator) settings = QSettings() if self.lineEdit.objectName() == "lineEdit_KSC": self.lineEdit.setText(QSettings.value(settings,SETTINGS_KSC)) if self.lineEdit.objectName() == "lineEdit_Bacula": self.lineEdit.setText(QSettings.value(settings,SETTINGS_BACULA)) if self.lineEdit.objectName() == "lineEdit_SIEM": self.lineEdit.setText(QSettings.value(settings,SETTINGS_SIEM)) if self.lineEdit.objectName() == "lineEdit_Zabbix": self.lineEdit.setText(QSettings.value(settings,SETTINGS_ZABBIX)) if self.lineEdit.objectName() == "lineEdit_DrWeb": self.lineEdit.setText(QSettings.value(settings,SETTINGS_DRWEB)) settings.sync()
def __init__(self, main): # pylint: disable=bad-super-call super(QMainWindow, self).__init__() self._main = main self._full_mode_chosen = FullModeChosen() self._full_mode_chosen.signal.connect(self._main.full_mode_chosen_slot) self._single_mode_chosen = SingleModeChosen() self._single_mode_chosen.signal.connect( self._main.single_mode_chosen_slot) self._buttons_clustering = QButtonGroup() self._buttons_nlp = QButtonGroup() self._line_dimension = QLineEdit() self._line_dimension.setPlaceholderText( "Допустимое расстояние между требованиями") reg_ex = QRegExp("[0-9]+.?[0-9]{,2}") input_validator = QRegExpValidator(reg_ex, self._line_dimension) self._line_dimension.setValidator(input_validator) self._init_ui()
def __init__(self, show_strength: bool = True, parent: Any = None) -> None: super(PinMatrixWidget, self).__init__(parent) self.password = QLineEdit() self.password.setValidator(QRegExpValidator(QRegExp("[1-9]+"), None)) self.password.setEchoMode(QLineEdit.Password) if QT_VERSION_STR >= "5": self.password.textChanged.connect(self._password_changed) elif QT_VERSION_STR >= "4": QObject.connect(self.password, SIGNAL("textChanged(QString)"), self._password_changed) else: raise RuntimeError("Unsupported Qt version") self.strength = QLabel() self.strength.setMinimumWidth(75) self.strength.setAlignment(Qt.AlignCenter) self._set_strength(0) grid = QGridLayout() grid.setSpacing(0) for y in range(3)[::-1]: for x in range(3): button = PinButton(self.password, x + y * 3 + 1) button.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) button.setFocusPolicy(Qt.NoFocus) grid.addWidget(button, 3 - y, x) hbox = QHBoxLayout() hbox.addWidget(self.password) if show_strength: hbox.addWidget(self.strength) vbox = QVBoxLayout() vbox.addLayout(grid) vbox.addLayout(hbox) self.setLayout(vbox)
def initUI(self): self.resize(350, 110) self.setWindowTitle('password_input') self.lb = QLabel('请输入密码', self) self.edit = QLineEdit(self) self.edit.installEventFilter(self) self.bt1 = QPushButton('确定', self) self.bt2 = QPushButton('取消', self) self.edit.setContextMenuPolicy(Qt.NoContextMenu) self.edit.setPlaceholderText('"密码6-15位,只能有数字和字母,必须以字母开头"') self.edit.setEchoMode(QLineEdit.Password) regx = QRegExp("^[a-zA-Z][0-9A-Za-z]{14}$") validator = QRegExpValidator(regx, self.edit) self.bt1.clicked.connect(self.Ok) self.bt2.clicked.connect(self.Cancel) object = QObject()
def __init__(self,parent=None): super(MainWindow,self).__init__(parent) self.setupUi(self) self.setWindowTitle('蓝牙测试工具V2.2') logging.basicConfig(level=logging.DEBUG, format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s', datefmt='%a, %d %b %Y %H:%M:%S', filename='test.log', filemode='w') self.init_config() self.btn_com.clicked.connect(self.btn_com_click) self.cb_rssi.stateChanged.connect(self.cb_rssi_state) self.cb_devname.stateChanged.connect(self.cb_devname_state) self.btn_conn_state.setStyleSheet('background-color:green') self.tv_last_snamac.setStyleSheet('color:green') self.btn_disconnect.clicked.connect(self.btn_disconnect_click) self.btn_next.clicked.connect(self.btn_next_click) self.tv_log.setFont(QtGui.QFont("Roman times",14)) self.conn_info.setFont(QtGui.QFont("Roman times", 14)) self.et_snmac.setFocus() self.et_snmac.setFont(QtGui.QFont("Roman times", 20)) self.et_snmac.setFont(QtGui.QFont("Roman times", 20)) self.tv_systime.setFont(QtGui.QFont("Roman times", 16)) self.btn_next.setFont(QtGui.QFont("宋体", 20)) self.et_snmac.textChanged.connect(self.snmac_change) regx = QRegExp("^Q{1}D{1}[0-9A-Z]{13}/{1}[0-9A-F]{12}$") validator = QRegExpValidator(regx, self.et_snmac) self.et_snmac.setValidator(validator) self.tv_last_snamac.setFont(QtGui.QFont("Roman times",20)) self.init_com() self.reset_all_result() self.con_state_timer=QtCore.QTimer() self.con_state_timer.timeout.connect(self.update_con_state) self.con_state_counter=0 self.con_state=False self.con_state_timer.start(200) self.init_ui() self.init_res()
def __init__(self, parent=None, default_value=0): super().__init__(parent) self.validator = QRegExpValidator(QRegExp('^([ ]*[0-9A-Fa-f][ ]*){1,8}$'), self) self.setValue(default_value)
def __init__(self, parent=None, time=900): super(TimeSpinBox, self).__init__(parent) self.validator = QRegExpValidator(QRegExp(r'(\d+\s*[{}]\s*)+'.format(''.join([key for key in self.SUFFIXES.keys()]), Qt.CaseInsensitive))) self.setMaximum(60*60*24*7 - 1) self.setValue(time)
class CooperationPage(ConfigurationPageBase, Ui_CooperationPage): """ Class implementing the Cooperation configuration page. """ def __init__(self): """ Constructor """ super(CooperationPage, self).__init__() self.setupUi(self) self.setObjectName("CooperationPage") self.__bannedUserValidator = QRegExpValidator( QRegExp("[a-zA-Z0-9.-]+@" "(?:(?:2(?:[0-4][0-9]|5[0-5])|[01]?[0-9]{1,2})\.){3}" "(?:2(?:[0-4][0-9]|5[0-5])|[01]?[0-9]{1,2})"), self.bannedUserEdit) self.bannedUserEdit.setValidator(self.__bannedUserValidator) # set initial values self.autostartCheckBox.setChecked( Preferences.getCooperation("AutoStartServer")) self.otherPortsCheckBox.setChecked( Preferences.getCooperation("TryOtherPorts")) self.serverPortSpin.setValue( Preferences.getCooperation("ServerPort")) self.portToTrySpin.setValue( Preferences.getCooperation("MaxPortsToTry")) self.autoAcceptCheckBox.setChecked( Preferences.getCooperation("AutoAcceptConnections")) self.bannedUsersList.addItems(sorted( Preferences.getCooperation("BannedUsers"))) def save(self): """ Public slot to save the Cooperation configuration. """ Preferences.setCooperation( "AutoStartServer", self.autostartCheckBox.isChecked()) Preferences.setCooperation( "TryOtherPorts", self.otherPortsCheckBox.isChecked()) Preferences.setCooperation( "AutoAcceptConnections", self.autoAcceptCheckBox.isChecked()) Preferences.setCooperation( "ServerPort", self.serverPortSpin.value()) Preferences.setCooperation( "MaxPortsToTry", self.portToTrySpin.value()) bannedUsers = [] for row in range(self.bannedUsersList.count()): bannedUsers.append(self.bannedUsersList.item(row).text()) Preferences.setCooperation("BannedUsers", bannedUsers) @pyqtSlot() def on_bannedUsersList_itemSelectionChanged(self): """ Private slot to react on changes of selected banned users. """ self.deleteBannedUsersButton.setEnabled( len(self.bannedUsersList.selectedItems()) > 0) @pyqtSlot(str) def on_bannedUserEdit_textChanged(self, txt): """ Private slot to handle the user entering a banned user. @param txt text entered by the user (string) """ self.addBannedUserButton.setEnabled( self.__bannedUserValidator.validate(txt, len(txt))[0] == QValidator.Acceptable) @pyqtSlot() def on_deleteBannedUsersButton_clicked(self): """ Private slot to remove the selected users from the list of banned users. """ for itm in self.bannedUsersList.selectedItems(): row = self.bannedUsersList.row(itm) itm = self.bannedUsersList.takeItem(row) del itm @pyqtSlot() def on_addBannedUserButton_clicked(self): """ Private slot to add a user to the list of banned users. """ self.bannedUsersList.addItem(self.bannedUserEdit.text()) self.bannedUserEdit.clear()