def provideAuthentication(self, reply, auth): username = QInputDialog.getText(None, "Authentication", "Enter your username:"******"Authentication", "Enter your password:", QLineEdit.Password) if password[1]: auth.setPassword(password[0])
def msg(self): #后面四个数字的作用依次是 初始值 最小值 最大值 小数点后位数 doubleNum,ok1 = QInputDialog.getDouble(self, "标题","计数:", 37.56, -10000, 10000, 2) #后面四个数字的作用依次是 初始值 最小值 最大值 步幅 intNum,ok2 = QInputDialog.getInt(self, "标题","计数:", 37, -10000, 10000, 2) #第三个参数可选 有一般显示 (QLineEdit.Normal)、密碼显示( QLineEdit. Password)与不回应文字输入( QLineEdit. NoEcho) stringNum,ok3 = QInputDialog.getText(self, "标题","姓名:",QLineEdit.Normal, "王尼玛") #1为默认选中选项目,True/False 列表框是否可编辑。 items = ["Spring", "Summer", "Fall", "Winter"] item, ok4 = QInputDialog.getItem(self, "标题","Season:", items, 1, True) text, ok5 = QInputDialog.getMultiLineText(self, "标题", "Address:", "John Doe\nFreedom Street")
def doBulk(self): qidxes = self.ui.bugList.selectionModel().selectedIndexes() cols = set(qidx.column() for qidx in qidxes) if len(cols) != 1: return col, = cols colname = self.mdl.headerData(col, Qt.Horizontal, Qt.DisplayRole) if colname not in ('status', 'assignee'): return objs = [qidx.data(ResultModel.RoleObject) for qidx in qidxes] project = objs[0].project if colname == 'status': vals = [status.name for status in project.statuses or []] val, ok = QInputDialog.getItem(self, self.tr('Bulk edit'), self.tr('Select new status for selected items'), vals, 0, False) elif colname == 'assignee': vals = [user.name for user in project.members or []] val, ok = QInputDialog.getItem(self, self.tr('Bulk edit'), self.tr('Select new assignee for selected items'), vals, 0, False) if not ok: return for obj in objs: change = Change() change.field = colname change.new = val update = Update() update.changes = [change] self.weboob.do('update_issue', obj, update, backends=(obj.backend,))
def addButtonClicked(self): shop = self.shopModel.record(self.list.currentIndex().row()) query = QSqlQuery("SELECT detail.id as id, CONCAT(detail.article, \": \", detail.name) as name \ FROM detail WHERE NOT(detail.id IN (SELECT detail_id FROM shop_detail \ WHERE shop_id={}))".format(shop.value("id"))) details = {} while query.next(): details[query.value("name")] = query.value("id") if not details: return QMessageBox.warning(None, "Ошибка добавления", "Не удалось добавить новый товар на склад: все возможные товары уже добавлены.") choice, ok = QInputDialog.getItem(None, "Товар", "Укажите товар:", list(details.keys()), 0, False) if not ok: return qnt, ok = QInputDialog.getInt(None, "Количество", "Укажите количество товара:", 1, 1) if not ok: return detail_id = details[choice] shop_id = shop.value("id") query = QSqlQuery("INSERT INTO shop_detail (shop_id, detail_id, quantity) \ VALUES ({}, {}, {})".format(shop_id, detail_id, qnt)) if not query.isActive(): print(query.lastError().text()) self.setShopIndex(self.list.currentIndex().row()) self.table.selectionModel().clearSelection()
def connect(self): if self.connected: self.revert() self.client.disconnect() return try: login, login_ok = QInputDialog.getText(self, 'Логин', 'Введите логин:') if login_ok: passwd, password_ok = QInputDialog.getText(self, 'Пароль', 'Введите пароль:', 2) if password_ok: server_item = self.serverList.currentItem() try: address = server_item.text().split(":") except: # server_item = self.serverList.findItems('', 0)[0] self.serverList.setCurrentRow(0) server_item = self.serverList.currentItem() address = server_item.text().split(":") if self.client.connect_to_server(address, login, passwd): self.connectButton.setText("Отключиться") self.connected = True else: self.critical("Неверный логин или пароль!", log=False) # mb = QMessageBox.critical(self, "Ошибка", "Неверный логин или пароль!") except TimeoutError: self.critical("Сервер перестал отвечать")
def new_item_edit_options(self, new): """Edit the selected item option with custom dialog.""" if new: selected = ItemOptionWidget("", None) else: selected = self.ui.variant.currentItem() # TODO: need a better way to lay this out. it's going to get big and messy fast # this is for the qinputdialog stuff. can't set signals on them generic = False if new: # needs to be here or new opts get detected as string (?) dialog = ItemEditOptions(self.dialog, selected.option[0], selected.option[1]) def get_option(): data = dialog.ui.options.toPlainText() return dialog.ui.name.text(), json.loads(data) #elif selected.option[0] in ["inventoryIcon", "image", "largeImage"]: # dialog = ImageBrowser(self.dialog, self.assets) # def get_option(): # return selected.option[0], dialog.get_key() elif type(self.item["parameters"][selected.option[0]]) is str: generic = True text, ok = QInputDialog.getText(self.dialog, "Edit Text", selected.option[0], text=self.item["parameters"][selected.option[0]]) if ok: self.item["parameters"][selected.option[0]] = text elif type(self.item["parameters"][selected.option[0]]) is int: generic = True num, ok = QInputDialog.getInt(self.dialog, "Edit Integer", selected.option[0], self.item["parameters"][selected.option[0]]) if ok: self.item["parameters"][selected.option[0]] = num elif type(self.item["parameters"][selected.option[0]]) is float: generic = True num, ok = QInputDialog.getDouble(self.dialog, "Edit Double", selected.option[0], self.item["parameters"][selected.option[0]], decimals=2) if ok: self.item["parameters"][selected.option[0]] = num elif type(self.item["parameters"][selected.option[0]]) is bool: generic = True self.item["parameters"][selected.option[0]] = not self.item["parameters"][selected.option[0]] else: dialog = ItemEditOptions(self.dialog, selected.option[0], selected.option[1]) def get_option(): data = dialog.ui.options.toPlainText() return dialog.ui.name.text(), json.loads(data) def save(): new_option = get_option() self.item["parameters"][new_option[0]] = new_option[1] if not generic: dialog.dialog.accepted.connect(save) dialog.dialog.exec() self.populate_options() self.update_item_info(self.item["name"], self.item["parameters"])
def loguj(self): login, ok = QInputDialog.getText(self, "Logowanie", "Podaj login:"******"Logowanie", "Podaj haslo:") if ok: if not login or not haslo: QMessageBox.warning(self, "Błąd", "Pusty login lub hasło!", QMessageBox.Ok) return QMessageBox.information(self, "Dane logowania", "Podano: " + login + " " + haslo, QMessageBox.Ok)
def AddPoint(self,x,y): self.Main.iface.mapCanvas().unsetMapTool(self.AddPointMapTool) Point = QgsPointXY(x,y) pos = self.player.position() if self.player.state() == QMediaPlayer.PlayingState: self.player.pause() a = self.DBLayer.name() last_desc = '///' LayerName =str(a) last_desc2 = LayerName + ' Point N ' directory = str(self.DB.split('.')[0])+'_Image/' if not os.path.exists(directory): os.makedirs(directory) fc = int(self.DBLayer.featureCount()) self.ExtractSingleFrameOnTime(pos,directory+LayerName+'_'+str(fc)+'_.jpg') fields = self.DBLayer.fields() attributes = [] lat,lon = Point.y(), Point.x() for field in fields: a = str(field.name()) b = str(field.typeName()) if a == 'id': fcnr = fc attributes.append(fcnr) elif a == 'Lon(WGS84)': attributes.append(str(lon)) elif a == 'Lat(WGS84)': attributes.append(str(lat)) elif a == 'Image link': attributes.append(str(directory+LayerName+'_'+str(fc)+'_.jpg')) else: if b == 'String': (a,ok) = QInputDialog.getText( self.Main.iface.mainWindow(), "Attributes", a + ' = String', QLineEdit.Normal) attributes.append(a) elif b == 'Real': (a,ok) = QInputDialog.getDouble( self.Main.iface.mainWindow(), "Attributes", a + ' = Real', decimals = 10) attributes.append(a) elif b == 'Integer64': (a,ok) = QInputDialog.getInt( self.Main.iface.mainWindow(), "Attributes", a + ' = Integer') attributes.append(a) feature = QgsFeature() feature.setGeometry(QgsGeometry.fromPoint(Point)) feature.setAttributes(attributes) self.DBLayer.startEditing() self.DBLayer.addFeature(feature) self.DBLayer.commitChanges() self.DBLayer.triggerRepaint()
def pull_split_queue(self): mb = QMessageBox() ind = QInputDialog() mb.information(self, "Breeze Software", "Please make sure that you have your Kornit Software open and running.", mb.Ok) queueNumber, ok = ind.getText(self, "Queue Number", "Please enter queue number.") if ok and queueNumber: queueNumber = queueNumber.lstrip("0") firstOrder, ok = ind.getText(self, "Starting Order", "Optional - please enter the beginning order number.") if not firstOrder: firstOrder = 1 machineNumber, ok = ind.getInt(self, "Machine Number", "Please enter machine number", 1, 1, 9, 1) clearHF = mb.question(self, "Hot Folder", "Do you want to clear all the items in the hot folder?", mb.Yes | mb.No, mb.Yes) if clearHF == mb.Yes: dirPath = "C:/HotFolder" fileList = os.listdir(dirPath) for filename in fileList: item = os.path.join(dirPath,filename) if os.path.isfile(item): os.remove(item) QMessageBox.information(self, 'Pulling Down', 'Your queue should show up in QuickP shortly.') front = len(str(machineNumber)) + len(str(queueNumber))+2 back = len(str(firstOrder)) + front dir_lst = os.listdir("//qserver/Breeze Artwork Storage/SplitQueues") counts = Counter(dir_lst) for file in dir_lst: if file[:len(str(machineNumber)+"_"+queueNumber)] == str(machineNumber)+"_"+queueNumber and file[front:-(len(file) - back)] >= str(firstOrder): type = file.split("_") queue = type[1] order = type[2] skuName = type[3] db = type[4] sizeGarment = type[5] skuType = type[6] printType = type[7] qty = type[8] pos1 = type[9] ext = type[10] fileName = skuType+"_"+printType+"_"+queue+"."+order+"."+skuName+"."+db+"."+sizeGarment+"."+qty+"_"+qty+"_"+pos1+"_"+ext shutil.copy(os.path.join("//qserver/Breeze Artwork Storage/SplitQueues", file), os.path.join("c:\HotFolder", fileName)) #shutil.copy(os.path.join("//qserver/Breeze Artwork Storage/Test", file), os.path.join("//qserver/BreezeSplitQueues", file)) elif ok and not queueNumber: mb.critical(self, "No Queue Number", "Must enter queue number to continue.") if ok == True: self.pull_split_queue()
def __init__(self, parent, indexes, mark=None): """ @param parent: a QWidget, for the dialog. @param indexes: a list of QModelIndex in the outlineModel @param default: the default split mark """ QInputDialog.__init__(self, parent) description = self.tr(""" <p>Split selected item(s) at the given mark.</p> <p>If one of the selected item is a folder, it will be applied recursively to <i>all</i> of it's children items.</p> <p>The split mark can contain following escape sequences: <ul> <li><b><code>\\n</code></b>: line break</li> <li><b><code>\\t</code></b>: tab</li> </ul> </p> <p><b>Mark:</b></p> """) if not mark: mark = "\\n---\\n" mark = mark.replace("\n", "\\n") mark = mark.replace("\t", "\\t") self.setLabelText(description) self.setTextValue(mark) if len(indexes) == 0: return if len(indexes) == 1: idx = indexes[0] self.setWindowTitle( self.tr("Split '{}'").format(self.getItem(idx).title()) ) else: self.setWindowTitle(self.tr("Split items")) r = self.exec() mark = self.textValue() if r and mark: mark = mark.replace("\\n", "\n") mark = mark.replace("\\t", "\t") for idx in indexes: item = self.getItem(idx) item.split(mark)
def __init__(self, posx, posy, label, title, value, parent=None): QInputDialog.__init__(self) xoff = parent.pos().x() yoff = parent.pos().y() self.setGeometry(posx+xoff, posy+yoff, 300, 200) self.setLabelText(label) self.setWindowTitle(title) self.setTextValue(value) dlgFont = self.font() dlgFont.setPointSize(14) self.setFont(dlgFont)
def addSearch(self): if "%s" in self.expEntry.text(): name = QInputDialog.getText(self, tr('Query'), tr('Enter a name here:')) if name[1] and name[0] != "": name = name[0] keyword = QInputDialog.getText(self, tr('Query'), tr('Enter a keyword here:'))[0] self.searchManager.add(name, self.expEntry.text(), keyword) self.expEntry.clear() self.reload_() else: QMessageBox.warning(self, tr('Error'), tr('Search expression must contain a <b>%s</b> to indicate the search terms.'))
def blankStock(self): printTypes = ("Brother", "Breeze", "Embroidery", "Kornit") barcode, ok = QInputDialog.getText(self, "Enter barcode", "Please scan or enter barcode:") if ok: bc = barcode printType, ok = QInputDialog.getItem(self, "Select Print Type", "Print Type", printTypes, 0, True) if ok and printType: pt = printType quantity, ok = QInputDialog.getInt(self, "Quantity", "Please enter quantity:", 1, 0, 25, 1) if ok: qty = quantity ImportExportDB.insBlankStock(self, bc, pt, qty)
def LogIn(self): self.user = Auth(self.login.displayText(), self.password.displayText()) if self.user.getError() is "UserNotFound": text, ok = QInputDialog.getText(self, 'ERROR', 'Enter your name:') if ok: self.login.setText(str(text)) elif Auth(self.login.displayText(), self.password.displayText()).getError() is "IncorrectPassword": pass text, ok = QInputDialog.getText(self, 'ERROR', 'Enter your password:') if ok: self.password.setText(str(text)) else: return self.user and self.close()
def mouseDoubleClickEvent(self, event): if event.button() != Qt.LeftButton: super(TabBarPlus, self).mouseDoubleClickEvent(event) idx = self.currentIndex() ok = True self.input_dialog = QInputDialog() print(type(self.input_dialog.textEchoMode())) newName, ok = QInputDialog.getText(self, 'Mudar nome', 'Novo nome:') if ok: self.setTabText(idx, newName)
def addWebsite(self): # get the site name that the user wants website, ok = QInputDialog.getText(self, 'Enter Website', 'Enter the NEW website:') # show the site self.textEdit.setText(website) # get the password unencryptedPassword, ok = QInputDialog.getText(self, 'Enter Password', 'Enter the site password:') # encrypt the new password encryptedPassword = passwordEncrypt(unencryptedPassword, encryptionKey) self.textEdit.append("PASSWORD ACCEPTED") # create a size 2 list tempList = [website, encryptedPassword] # append the tempList to the password list passwords.append(tempList)
def DeletePass(self): # get the website userWebsite, ok = QInputDialog.getText(self, 'Enter Website', 'Enter the website to DELETE:') # update the user with info self.textEdit.setText("Thank you we have the website") self.textEdit.append(userWebsite) # get the password for the website from the user userPassword, ok = QInputDialog.getText(self, 'Enter Password', 'Enter the website Password:') # flip through the password list again (probably should have saved this meh, we got ram) for x, y in enumerate(passwords): # could have used (for i in passwords) again trying out enumerate if y[0] == userWebsite: if y[1] == passwordEncrypt(userPassword, encryptionKey): # Delete the website and password from our list passwords.remove([userWebsite, passwordEncrypt(userPassword, encryptionKey)]) self.textEdit.setText("We found and deleted the site and password")
def hgQueueDeletePatch(self, name): """ Public method to delete a selected unapplied patch. @param name file/directory name (string) """ # find the root of the repo repodir = self.vcs.splitPath(name)[0] while not os.path.isdir(os.path.join(repodir, self.vcs.adminDir)): repodir = os.path.dirname(repodir) if os.path.splitdrive(repodir)[1] == os.sep: return args = self.vcs.initCommand("qdelete") patchnames = sorted(self.__getPatchesList(repodir, Queues.UNAPPLIED_LIST)) if patchnames: patch, ok = QInputDialog.getItem( None, self.tr("Select Patch"), self.tr("Select the patch to be deleted:"), patchnames, 0, False) if ok and patch: args.append(patch) dia = HgDialog(self.tr("Delete Patch"), self.vcs) res = dia.startProcess(args, repodir) if res: dia.exec_() else: E5MessageBox.information( None, self.tr("Select Patch"), self.tr("""No patches to select from."""))
def onBackupDBTriggered(self): self.checkMysqldumpTool() backupFlag = True fileName,okPressed = QInputDialog.getText(self,"数据库备份","请输入文件名:",QLineEdit.Normal, "dbback.sql") if okPressed and fileName.strip(): print('DBBackupFile:' + fileName) logging.info('DBBackupFile:' + fileName) logging.info("\r\n") command = 'mysqldump -u' + self.sysXMLDict['mysqluser'] + ' -h ' + self.sysXMLDict['mysqlhost'] + ' -p' + self.sysXMLDict['mysqlpassword'] \ + ' ' + self.sysXMLDict['mysqldatabase'] + ' ' + self.sysXMLDict['mysqltable'] + '>' + fileName print(command) logging.info("Backup DB command: " + command) process = subprocess.Popen(command,shell=True,stdout=subprocess.PIPE,stderr=subprocess.STDOUT) for line in process.stdout.readlines(): if str(line).count('error'): backupFlag = False break process.wait() if backupFlag: QMessageBox.information(self,SUCCESSTITLE,MYSQL_BACKUP_SUCCESS) else: QMessageBox.critical(self,ERRORTITLE,MYSQL_BACKUP_FAILED) else: QMessageBox.critical(self,ERRORTITLE,MYSQL_INFO_BACKUP)
def on_addButton_clicked(self): """ Private slot to add a new idntity. """ name, ok = QInputDialog.getText( self, self.tr("Add Identity"), self.tr("Identity Name:"), QLineEdit.Normal) if ok: if name: if name in self.__identities: E5MessageBox.critical( self, self.tr("Add Identity"), self.tr( """An identity named <b>{0}</b> already exists.""" """ You must provide a different name.""").format( name)) self.on_addButton_clicked() else: identity = IrcIdentity(name) identity.setIdent(Utilities.getUserName()) identity.setRealName(Utilities.getRealName()) self.__identities[name] = identity self.identitiesCombo.addItem(name) self.identitiesCombo.setCurrentIndex( self.identitiesCombo.count() - 1) else: E5MessageBox.critical( self, self.tr("Add Identity"), self.tr("""The identity has to have a name.""")) self.on_addButton_clicked()
def onResetMACTriggered(self): resetFlag = False mac,okPressed = QInputDialog.getText(self,"MAC状态重置","请输入MAC号:",QLineEdit.Normal, " ") if okPressed and mac.strip(): print('mac:' + mac) logging.info('mac:' + mac) logging.info("\r\n") mysql = MySQLCommand(host=self.sysXMLDict['mysqlhost'],port=int(self.sysXMLDict['mysqlport']),user=self.sysXMLDict['mysqluser'],\ passwd=self.sysXMLDict['mysqlpassword'],db=self.sysXMLDict['mysqldatabase'],table=self.sysXMLDict['mysqltable']) mysqlConFlag = mysql.connectMysql() if not mysqlConFlag: self.mysqlConnectErrSignal.emit(MYSQL_CONNECT_ERROR) return self.lock.acquire() resetFlag = mysql.resetMysqlMACStatusAndSN(mac=mac,stbType=self.sysXMLDict['mysqlstbtype'],poNumber=self.poNumber) if resetFlag: QMessageBox.information(self,SUCCESSTITLE,RESET_MAC_SUCCESS) else: QMessageBox.critical(self,ERRORTITLE,RESET_MAC_FAILED) self.lock.release() mysql.closeMysql() else: QMessageBox.critical(self,ERRORTITLE,RESET_MAC_INFO)
def _onRename(self): """Handler for File->File System->Rename""" document = core.workspace().currentDocument() if document.qutepart.document().isModified() or \ document.isExternallyModified() or \ document.isExternallyRemoved() or \ document.isNeverSaved(): QMessageBox.warning(core.mainWindow(), 'Rename file', 'Save the file before renaming') return newPath, ok = QInputDialog.getText(core.mainWindow(), 'Rename file', 'New file name', text=document.filePath()) if not ok: return if newPath == document.filePath(): return if newPath == '/dev/null': try: os.remove(document.filePath()) except (OSError, IOError) as ex: QMessageBox.critical(core.mainWindow(), 'Not this time', 'The OS thinks it needs the file') else: core.workspace().closeDocument(document) else: try: os.rename(document.filePath(), newPath) except (OSError, IOError) as ex: QMessageBox.critical(core.mainWindow(), 'Failed to rename file', str(ex)) else: document.setFilePath(newPath) document.saveFile()
def on_newButton_clicked(self): """ Private slot to create a new toolbar. """ name, ok = QInputDialog.getText( self, self.tr("New Toolbar"), self.tr("Toolbar Name:"), QLineEdit.Normal) if ok and name: if self.toolbarComboBox.findText(name) != -1: # toolbar with this name already exists E5MessageBox.critical( self, self.tr("New Toolbar"), self.tr( """A toolbar with the name <b>{0}</b> already""" """ exists.""") .format(name)) return tbItem = E5ToolBarItem(None, [], False) tbItem.title = name tbItem.isChanged = True self.__toolbarItems[id(tbItem)] = tbItem self.__toolBarItemToWidgetActionID[id(tbItem)] = [] self.toolbarComboBox.addItem(name, int(id(tbItem))) self.toolbarComboBox.model().sort(0) self.toolbarComboBox.setCurrentIndex( self.toolbarComboBox.findText(name))
def on_renameButton_clicked(self): """ Private slot to rename the selected identity. """ currentIdentity = self.identitiesCombo.currentText() name, ok = QInputDialog.getText( self, self.tr("Rename Identity"), self.tr("Identity Name:"), QLineEdit.Normal, currentIdentity) if ok and name != currentIdentity: if name: if name in self.__identities: E5MessageBox.critical( self, self.tr("Rename Identity"), self.tr( """An identity named <b>{0}</b> already exists.""" """ You must provide a different name.""").format( name)) self.on_renameButton_clicked() else: del self.__identities[currentIdentity] self.__currentIdentity.setName(name) self.__identities[name] = self.__currentIdentity self.identitiesCombo.setItemText( self.identitiesCombo.currentIndex(), name) else: E5MessageBox.critical( self, self.tr("Copy Identity"), self.tr("""The identity has to have a name.""")) self.on_renameButton_clicked()
def on_renameButton_clicked(self): """ Private slot to rename a custom toolbar. """ oldName = self.toolbarComboBox.currentText() newName, ok = QInputDialog.getText( self, self.tr("Rename Toolbar"), self.tr("New Toolbar Name:"), QLineEdit.Normal, oldName) if ok and newName: if oldName == newName: return if self.toolbarComboBox.findText(newName) != -1: # toolbar with this name already exists E5MessageBox.critical( self, self.tr("Rename Toolbar"), self.tr( """A toolbar with the name <b>{0}</b> already""" """ exists.""") .format(newName)) return index = self.toolbarComboBox.currentIndex() self.toolbarComboBox.setItemText(index, newName) tbItem = \ self.__toolbarItems[self.toolbarComboBox.itemData(index)] tbItem.title = newName tbItem.isChanged = True
def _rename_file(self): item = self.currentItem() if item.parent() is None: pathForFile = item.path else: pathForFile = os.path.join(item.path, item.text(0)) result = QInputDialog.getText(self, _translate("TreeProjectsWidget", "Rename File"), _translate("TreeProjectsWidget", "Enter New File Name:"), text=item.text(0)) fileName = result[0] if result[1] and fileName.strip() != '': fileName = os.path.join( file_manager.get_folder(pathForFile), fileName) if pathForFile == fileName: return try: fileName = file_manager.rename_file(pathForFile, fileName) name = file_manager.get_basename(fileName) mainContainer = main_container.MainContainer() if mainContainer.is_open(pathForFile): mainContainer.change_open_tab_name(pathForFile, fileName) subitem = ProjectItem(item.parent(), name, file_manager.get_folder(fileName)) subitem.setToolTip(0, name) subitem.setIcon(0, self._get_file_icon(name)) index = item.parent().indexOfChild(item) subitem.parent().takeChild(index) except file_manager.NinjaFileExistsException as ex: QMessageBox.information(self, _translate("TreeProjectsWidget", "File Already Exists"), (_translate("TreeProjectsWidget", "Invalid Path: the file '%s' already exists.") % ex.filename))
def _copy_file(self): #get the selected QTreeWidgetItem item = self.currentItem() if item.parent() is None: pathForFile = item.path else: pathForFile = os.path.join(item.path, item.text(0)) pathProjects = [p.path for p in self.get_open_projects()] addToProject = ui_tools.AddToProject(pathProjects, self) addToProject.setWindowTitle(_translate("TreeProjectsWidget", "Copy File to")) addToProject.exec_() if not addToProject.pathSelected: return name = QInputDialog.getText(self, _translate("TreeProjectsWidget", "Copy File"), _translate("TreeProjectsWidget", "File Name:"), text=item.text(0))[0] if not name: QMessageBox.information(self, _translate("TreeProjectsWidget", "Invalid Name"), _translate("TreeProjectsWidget", "The file name is empty, please enter a name")) return path = file_manager.create_path(addToProject.pathSelected, name) try: content = file_manager.read_file_content(pathForFile) path = file_manager.store_file_content(path, content, newFile=True) self.add_existing_file(path) except file_manager.NinjaFileExistsException as ex: QMessageBox.information(self, _translate("TreeProjectsWidget", "File Already Exists"), (_translate("TreeProjectsWidget", "Invalid Path: the file '%s' already exists.") % ex.filename))
def on_namedReferenceButton_clicked(self): """ Private slot to handle the named reference toolbutton. """ # determine cursor position as length into text length = self.regexpTextEdit.textCursor().position() # only present group names that occur before the # current cursor position regex = self.regexpTextEdit.toPlainText()[:length] names = self.namedGroups(regex) if not names: E5MessageBox.information( self, self.tr("Named reference"), self.tr("""No named groups have been defined yet.""")) return groupName, ok = QInputDialog.getItem( self, self.tr("Named reference"), self.tr("Select group name:"), names, 0, True) if ok and groupName: self.__insertString("(?P={0})".format(groupName))
def _add_new_file(self): item = self.currentItem() if item.parent() is None: pathForFile = item.path else: pathForFile = os.path.join(item.path, item.text(0)) result = QInputDialog.getText(self, _translate("TreeProjectsWidget", "New File"), _translate("TreeProjectsWidget", "Enter the File Name:")) fileName = result[0] if result[1] and fileName.strip() != '': try: fileName = os.path.join(pathForFile, fileName) fileName = file_manager.store_file_content( fileName, '', newFile=True) name = file_manager.get_basename(fileName) subitem = ProjectItem(item, name, pathForFile) subitem.setToolTip(0, name) subitem.setIcon(0, self._get_file_icon(name)) mainContainer = main_container.MainContainer() mainContainer.open_file(fileName) except file_manager.NinjaFileExistsException as ex: QMessageBox.information(self, _translate("TreeProjectsWidget", "File Already Exists"), (_translate("TreeProjectsWidget", "Invalid Path: the file '%s' already exists.") % ex.filename))
def openUrl(self): url, ok = QInputDialog.getText(self, "Enter a URL", "URL:", QLineEdit.Normal, "http://") if ok and url: url = QUrl(url) self.centralWidget.webView.setUrl(url)
def keyPressEvent(self, e): textCursor = self.textCursor() key = e.key() if ( e.modifiers() == Qt.ControlModifier and key == 16777217 ): # that key code stands for tab self.parent.parent.switchTabs() isSearch = e.modifiers() == Qt.ControlModifier and e.key() == Qt.Key_F isDeleteLine = ( e.modifiers() == Qt.ControlModifier and e.key() == 16777219 ) # This is for MacOS (CMD+Delete) if isSearch: try: currentWidget = self.parent currentFile = currentWidget.fileName currentEditor = currentWidget.editor textCursor = currentEditor.textCursor() textCursorPos = textCursor.position() if currentWidget is not None: text, okPressed = QInputDialog.getText(self, "Find", "Find what: ") if okPressed: if text == "": text = " " self.not_found = NoMatch(text) self.searchtext = text try: with open(currentFile, "r") as file: contents = file.read() self.indexes = list(find_all(contents, text)) if len(self.indexes) == 0: self.not_found = NoMatch(text) except FileNotFoundError as E: print(E, " on line 245 in the file Editor.py") except (AttributeError, UnboundLocalError) as E: print(E, " on line 228 in the file Editor.py") if isDeleteLine and platform.system() == "Darwin": # Check if the os is MacOS textCursor.select(QTextCursor.LineUnderCursor) textCursor.removeSelectedText() if key == Qt.Key_QuoteDbl: self.insertPlainText('"') self.moveCursorPosBack() if ( e.modifiers() == Qt.ControlModifier and e.key() == 61 ): # Press Ctrl+Equal key to make font bigger self.font.setPointSize(self.size + 1) self.font.setFamily(editor["editorFont"]) self.setFont(self.font) self.size += 1 if e.modifiers() == Qt.ControlModifier and e.key() == 16777217: return if ( e.modifiers() == Qt.ControlModifier and e.key() == 45 ): # Press Ctrl+Minus key to make font smaller self.font.setPointSize(self.size - 1) self.font.setFamily(editor["editorFont"]) self.setFont(self.font) self.size -= 1 if key == Qt.Key_F3: try: index = self.indexes[0 + self.l] currentWidget = self.parent currentFile = currentWidget.fileName currentEditor = currentWidget.editor textCursor.setPosition(index) textCursor.movePosition( textCursor.Right, textCursor.KeepAnchor, len(self.searchtext) ) currentEditor.setTextCursor(textCursor) self.l += 1 except IndexError: self.l = 0 if key == 16777220: currentText: str = self.textCursor().block().text() space: str = " " if self.textUnderCursor().endswith(":"): spaces: int = 0 for index, i in enumerate(currentText): if i != " ": if index % 4 == 0: super().keyPressEvent(e) self.insertPlainText(space * (index + 4)) return if spaces == 0: super().keyPressEvent(e) self.insertPlainText(space * 4) return else: for index, i in enumerate(currentText): if i != " ": if index % 4 == 0 and index != 0: super().keyPressEvent(e) self.insertPlainText(space * index) return break else: if len(currentText) % 4 == 0 and self.onlySpaces(currentText): super().keyPressEvent(e) self.insertPlainText(space * len(currentText)) return super().keyPressEvent(e)
def scalegraph(self): scale, ok = QInputDialog.getDouble(self, self.tr("scale the graph"), self.tr("set the scale value:"), 1, 0.01, 100, 2) if ok: self.view.scaleGraphImage(scale)
def send_any_command(self): text, ok = QInputDialog.getText(self, "Enter command to send on copter", "Command:", QLineEdit.Normal, "") if ok and text: self.send_to_selected("execute", command_kwargs={"command": text})
def contextMenuEvent(self, event): # create menu pos = self.mapToScene(event.pos()) menu = QMenu(self) # remove from memory after usage menu.setAttribute(Qt.WA_DeleteOnClose) # remove from memory spawn_point_menu = menu.addMenu('Spawn Point') spawn_point_create = spawn_point_menu.addAction('Create on Cursor') spawn_point_delete = spawn_point_menu.addAction('Delete on Cursor') spawn_point_delete_all = spawn_point_menu.addAction('Delete All') way_point_menu = menu.addMenu('Way Point') way_point_create = way_point_menu.addAction('Create on Cursor') way_point_delete = way_point_menu.addAction('Clear') load_map = menu.addAction('Load Map') # execute action = menu.exec_(self.mapToGlobal(event.pos())) # parse response if action == spawn_point_create: spawn_time = text_time_to_seconds('6:40') dialog = QInputDialog(self) dialog.setWindowTitle('Create Spawn Point') dialog.setLabelText('Respawn Time (hh:mm:ss):') dialog.setTextValue('6:40') if dialog.exec_(): spawn_time = text_time_to_seconds(dialog.textValue()) dialog.deleteLater() spawn = SpawnPoint(location=MapPoint( x=pos.x(), y=pos.y(), z=self._data.geometry.z_groups[self._z_index]), length=spawn_time) self._scene.addItem(spawn) self._data.spawns.append(spawn) spawn.start() if action == spawn_point_delete: pixmap = self._scene.itemAt(pos.x(), pos.y(), QTransform()) if pixmap: group = pixmap.parentItem() if group: self._data.spawns.remove(group) self._scene.removeItem(group) if action == spawn_point_delete_all: for spawn in self._data.spawns: self._scene.removeItem(spawn) self._data.spawns = [] if action == way_point_create: if self._data.way_point: self._scene.removeItem(self._data.way_point.pixmap) self._scene.removeItem(self._data.way_point.line) self._data.way_point = None self._data.way_point = WayPoint(location=MapPoint( x=pos.x(), y=pos.y(), z=self._data.geometry.z_groups[self._z_index])) self._scene.addItem(self._data.way_point.pixmap) self._scene.addItem(self._data.way_point.line) if action == way_point_delete: if self._data.way_point: self._scene.removeItem(self._data.way_point.pixmap) self._scene.removeItem(self._data.way_point.line) self._data.way_point = None if action == load_map: dialog = QInputDialog(self) dialog.setWindowTitle('Load Map') dialog.setLabelText('Select map to load:') dialog.setComboBoxItems( sorted([map.title() for map in MapData.get_zone_dict().keys()])) if dialog.exec_(): self.load_map(dialog.textValue().lower()) dialog.deleteLater() self.update_()
def on_actionFind_triggered(self): SubPage = self.mdi_Editor.currentSubWindow() text, ok = QInputDialog.getText(self, 'Find', 'Search Target:') if ok: SubPage.Editor.findFirst(text, 0, 0, 0, 0)
def detect_object(self): available_detect_methods = ( 'TM_CCOEFF', 'TM_CCOEFF_NORMED', 'TM_CCORR', 'TM_CCORR_NORMED', 'TM_SQDIFF', 'TM_SQDIFF_NORMED', ) _available_detect_methods = { 'TM_CCOEFF': cv2.TM_CCOEFF, 'TM_CCOEFF_NORMED': cv2.TM_CCOEFF_NORMED, 'TM_CCORR': cv2.TM_CCORR, 'TM_CCORR_NORMED': cv2.TM_CCORR_NORMED, 'TM_SQDIFF': cv2.TM_SQDIFF, 'TM_SQDIFF_NORMED': cv2.TM_SQDIFF_NORMED, } result = QFileDialog.getOpenFileName(self, 'Open file', '', "Image files (*.jpg *.png)") path_to_pattern_image = result[0] if path_to_pattern_image == '': return methods = available_detect_methods input_method_raw, ok = QInputDialog.getItem( self, "Select detect method dialog", "Detect method", methods, 0, False) if not ok or not input_method_raw: return method = _available_detect_methods.get(input_method_raw) if method is None: self.show_error('Unavailable method') return template = cv2.imread(path_to_pattern_image, cv2.IMREAD_UNCHANGED) if template is None: self.show_error('Error reading template file') return gray_template = cv2.cvtColor(template, cv2.COLOR_BGR2GRAY) image_gray = cv2.cvtColor(self._image, cv2.COLOR_BGR2GRAY) shape = gray_template.shape[::-1] width, height = (shape[0], shape[1]) res = cv2.matchTemplate(image_gray, gray_template, method) min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(res) if method in [cv2.TM_SQDIFF, cv2.TM_SQDIFF_NORMED]: top_left = min_loc else: top_left = max_loc bottom_right = (top_left[0] + width, top_left[1] + height) cv2.rectangle(self._image, top_left, bottom_right, 255, 2) self.draw_image()
def __init__(self, app): super().__init__() self.app = app menubar = QMenuBar() main_menu = menubar.addMenu("Sign") pass_menu = menubar.addMenu("Password") self.remove_password_item = pass_menu.addAction("Remove password") self.remove_password_item.triggered.connect(self.remove_pass) self.set_password_item = pass_menu.addAction("Set password") self.set_password_item.triggered.connect(self.set_new_pass) cancel = False if Utils().check_pass_set(): self.set_password_item.setDisabled(True) good = False while not (good): text, ok = QInputDialog.getText(self, 'Password', 'Enter password:'******'RSA Signature') main_layout.addWidget(menubar) wind_layout = QHBoxLayout() wind_layout.addLayout(table_horiz_layout1) wind_layout.addLayout(table_horiz_layout2) main_layout.addLayout(wind_layout) self.setLayout(main_layout) self.show()
def do_key(self, k, x, y, mod): """ Parameters ---------- k : int pressed key x : float coordinate x y : float coordinate y mod : shift pressed Returns ------- """ # Does not deal with events passed down to Selection # Check what the current test mode is and do the appropriate action at each key. Problem: FBefore test mode 4 i did not use crd and self.test_mode but just checked if attributes set by the test functions are present print(k, x, y, mod, mv=0) if k == 13 and mod == 0: # Enter if self.check_results_mode == 4: self._check_optimzer_results_pairwise_4() elif self.check_results_mode == 6: self._check_optimzer_results_pairwise_6( ) # Show_next+True by default elif hasattr(self, '_to2_i_m'): self._to2_i_m = (self._to2_i_m + 1) % len( self.cmd.get_object_list()) self._optimzer_show_next_molecule_pair_2() elif hasattr(self, '_to3_i_m'): self._to3_i_m = int((self._to3_i_m + 1) % (len(self.cmd.get_object_list()) / 3)) self._optimzer_show_next_molecule_pair_3() elif k == 13 and mod == 1: # shift Enter # Start or end test mode 5 if self.check_results_mode == 4: self._check_optimzer_results_pairwise_4(exit_test_mode=True) elif self.check_results_mode == 5: self._check_optimzer_results_pairwise_5(exit_test_mode=True) elif self.check_results_mode == 6: self._check_optimzer_results_pairwise_6(exit_test_mode=True) elif len(self.logic_handler.selected_restraints) != 0: self._check_optimzer_results_pairwise_6() elif k == 8: # Backspace if self.check_results_mode == 6: self._check_optimzer_results_pairwise_6(show_next=False) if hasattr(self, '_to2_i_m'): self._to2_i_m = (self._to2_i_m - 1) % len( self.cmd.get_object_list()) self._optimzer_show_next_molecule_pair_2() elif hasattr(self, 'to_3_i_m'): self._to3_i_m = int((self._to3_i_m - 1) % (len(self.cmd.get_object_list()) / 3)) self._optimzer_show_next_molecule_pair_3() elif k == 32: # Space self.cmd.set('grid_mode', (int(self.cmd.get('grid_mode')) + 1) % 2) elif k == 81 or k == 113: # q or Q self.cmd.enable('all') elif k in range(48, 58): # Number - #TODO: seems not to work # Show the corresponidng moleucle in test mode num = k - 48 print(str(num), mv=4) print(k, x, y, mod, mv=4) if self.check_results_mode == 4: if num > 0 and num <= len(self.pymol_molecule_objects): self._check_optimzer_results_pairwise_4( mol1=self.pymol_molecule_objects[(num - 1)], mol2=self.check_result_dict['mol1']) # KEYBOARD SHORTCUTS FOR USEFULL FUNCTIONS. Warning: Do not use alt or Ctrl for shortcuts. Many keys are already occupied # h: Hide instructions if k == 104: self.show_message = False # The only instruction will be how to show instructions self.cmd.refresh_wizard() # s: show instructions if k == 115: self.show_message = True self.cmd.refresh_wizard() # Shf R: Delete all restraints if k == 82 and mod == 1: self.logic_handler.selected_restraints = [] self.logic_handler.set_action_states() self.get_panel() self.redraw() self.cmd.refresh_wizard() # Shf Q: Choose all atoms, start brute force optimizer, start test mode 4 if k == 81 and mod == 1: self._action_button_pressed('AllSelection') self.trigger_event(program_states.EventType.CONFIRM) self._action_button_pressed("RingFilter") self.trigger_event(program_states.EventType.CONFIRM) self._action_button_pressed('GreedyGraphOptimizer') # Make sure Optimizatyion was sucessfull if (len(self.logic_handler.selected_restraints) > 0): self._check_optimzer_results_pairwise_6() # Shf T: Test Optimizers if k == 84 and mod == 1: print('Testing Optimizers...', mv=3) from restraintmaker.algorithm import Optimizer from PyQt5.QtWidgets import QFileDialog, QInputDialog Optimizer.compare_pair_optimizers(criterion=Optimizer._calculate_value_convex_hull, \ atoms=self.logic_handler.selected_atoms, \ opt_types=[Optimizer.GreedyGraphOptimizer, Optimizer.GreedyGraphOptimizer, Optimizer.GreedyGraphOptimizer, Optimizer.BruteForceRingOptimzer, Optimizer.BruteForceRingOptimzer], \ opt_args=[(4, 1.0, 'prim', 'convex_hull'), (4, 1.0, 'cog', 'convex_hull'), (4, 1.0, 'shortest', 'convex_hull'), (4, 1.0, 'pca', 'convex_hull'), (4, 1.0, 'convex_hull', 'convex_hull')], \ out_path=QFileDialog.getExistingDirectory( caption='Where should all restraints be saved?'), new_dir_name= QInputDialog.getText(cmd.gui.get_qtwindow(), 'Directory name', 'What should the new directory be calledd?')[0]) print('... tested optimizers', mv=3) # Shft C: Readjust color if k == 67 and mod == 1: pu.colorize(self.logic_handler.all_atoms) # Shft S: Snapshot if k == 83 and mod == 1: self.cmd.refresh() file = qt_dialogs.create_file_save_dialog()( "Where should the snapshot be saved?" ) # '~/Desktop/'+str(self.quicksnapshot_nr)+'.png' self.quicksnapshot_nr += 1 self.cmd.png(file) self.cmd.refresh() self.cmd.refresh_wizard() print('Saved picture at ' + file, mv=3)
def playGame(self): global o keepPlaying = True app = QApplication(sys.argv) w = QWidget() w.showMaximized() w.setWindowTitle("Otakunator") l = QLabel(w) pixmap = QPixmap("homescreen.jpg") l.setPixmap(pixmap) l.move(400, -300) l.resize(10000, 1500) l.show() l2 = QLabel(w) pixmap = QPixmap("cloud3.png") l2.setPixmap(pixmap) l2.move(400, 50) l2.resize(700, 400) l2.setScaledContents(True) l2.setSizePolicy(QtWidgets.QSizePolicy.Ignored, QtWidgets.QSizePolicy.Ignored) l2.hide() simg = QtGui.QImage("background.png").scaled(w.maximumSize()) pallette = QtGui.QPalette() pallette.setBrush(QtGui.QPalette.Window, QtGui.QBrush(simg)) w.setPalette(pallette) label = QLabel(w) label.move(110, 530) label.resize(900, 80) engine = pyttsx3.init() engine.setProperty('voice', engine.getProperty('voices')[0].id) engine.setProperty('rate', 200) engine.say( "Hello I am Otaah kunator. Think about a character fro Narutoverse and I will guess it. So, are you ready to challenge me" ) engine.runAndWait() btn = QPushButton(w) btn.setText("Next") btn.move(900, 840) btn.show() btn.clicked.connect(dialog) o = 0 while o == 0: QtCore.QCoreApplication.processEvents() o = 0 l.move(300, 100) btn.move(510, 600) l2.show() btn2 = QPushButton(w) btn3 = QPushButton(w) btn.setText("Yes") btn2.setText("No") btn3.setText("Maybe") btn.move(500, 500) btn2.move(500, 650) btn3.move(500, 800) btn.resize(510, 100) btn2.resize(510, 100) btn3.resize(510, 100) btn.setStyleSheet( 'QPushButton {background-color: #005296; color: white; font-size: 18pt; font-weight: bold} ' ) btn2.setStyleSheet( 'QPushButton {background-color: #0BB5FF; color: white; font-size: 18pt; font-weight: bold}' ) btn3.setStyleSheet( 'QPushButton {background-color: #AFC1DA; color: white; font-size: 18pt; font-weight: bold}' ) btn.show() btn2.show() btn3.show() simg = QtGui.QImage("background.png").scaled(w.size()) pallette = QtGui.QPalette() pallette.setBrush(QtGui.QPalette.Window, QtGui.QBrush(simg)) w.setPalette(pallette) l.resize(300, 500) url = QtCore.QUrl.fromLocalFile("./narutos-theme-song.wav") content = M.QMediaContent(url) playlist = M.QMediaPlaylist() playlist.addMedia(content) url = QtCore.QUrl.fromLocalFile("./naruto-sad-music-instant.wav") content = M.QMediaContent(url) playlist.addMedia(content) playlist.setPlaybackMode(M.QMediaPlaylist.Loop) player = M.QMediaPlayer() player.setPlaylist(playlist) player.play() while keepPlaying: print("Welcome to 20 Questions!") q = self.game.getNextQuestion() print(q) pixmap = QPixmap("Akinator3.png") l.setPixmap(pixmap) l.setScaledContents(True) l.setSizePolicy(QtWidgets.QSizePolicy.Ignored, QtWidgets.QSizePolicy.Ignored) l.move(880, 100) l.resize(650, 900) l.show() label.move(500, -100) label.setScaledContents(True) label.setSizePolicy(QtWidgets.QSizePolicy.Ignored, QtWidgets.QSizePolicy.Ignored) label.resize(550, 600) label.setText(str(q)) label.setFont(QtGui.QFont("Times", 25, QtGui.QFont.Decorative)) label.setWordWrap(True) label.show() #engine = pyttsx3.init() #engine.say(str(q)) #engine.runAndWait() #engine.stop() btn.clicked.connect(dialog) btn2.clicked.connect(dialog1) btn3.clicked.connect(dialog2) while o == 0: QtCore.QCoreApplication.processEvents() url2 = QtCore.QUrl.fromLocalFile("./activation.wav") content2 = M.QMediaContent(url2) player2 = M.QMediaPlayer() player2.setMedia(content2) player2.play() answer = a self.game.answerQuestion(self.game.questionsUsed[0], answer) i = 0 pixmap = QPixmap("Akinator3.png") l.setPixmap(pixmap) while len(self.game.remainingFood) > 1 and i < 20: i += 1 o = 0 nextQ = self.game.getNextQuestion() label.setText(nextQ) if not nextQ: break data = [(name, self.game.likelihood[name]) for name in self.game.remainingFood] #print(data) print(nextQ) btn.clicked.connect(dialog) btn2.clicked.connect(dialog1) btn3.clicked.connect(dialog2) while o == 0: QtCore.QCoreApplication.processEvents() url2 = QtCore.QUrl.fromLocalFile("./activation.wav") content2 = M.QMediaContent(url2) player2 = M.QMediaPlayer() player2.setMedia(content2) player2.play() answer = a if answer == 0: l2.show() pixmap = QPixmap("Akinator2.png") l.setPixmap(pixmap) if answer == 1: l2.show() pixmap = QPixmap("Akinator3.png") l.setPixmap(pixmap) while answer == -1: print(nextQ) label.setText(nextQ) print( "Please answer with 'yes', 'no', 'sometimes', 'maybe', or 'unknown'." ) answer = self.game.convertAnswer(input()) self.game.answerQuestion(self.game.questionsUsed[i], answer) #selected = self.game.remainingFood[0] data = [(name, self.game.likelihood[name]) for name in self.game.remainingFood] selected = max(data, key=lambda item: item[1])[0] #print(data) pixmap = QPixmap(selected + ".png") l.setPixmap(pixmap) l.setScaledContents(True) l.setSizePolicy(QtWidgets.QSizePolicy.Ignored, QtWidgets.QSizePolicy.Ignored) label.setText("Are you thinking of " + selected + "?") btn.clicked.connect(dialog) btn2.clicked.connect(dialog1) btn3.clicked.connect(dialog2) o = 0 while o == 0: QtCore.QCoreApplication.processEvents() url2 = QtCore.QUrl.fromLocalFile("./activation.wav") content2 = M.QMediaContent(url2) player2 = M.QMediaPlayer() player2.setMedia(content2) player2.play() correct = a if correct == 0: print("Enter the name of the character you are thinking of:") text, okPressed = QInputDialog.getText(w, "Get text", "Your name:", QLineEdit.Normal, "") if okPressed and text != '': print(text) correctAnswer = text if correctAnswer not in list(self.game.answers) and len( self.game.questionsUsed) < len(self.game.questions): print("Please help me learn about", correctAnswer, "by answering a few more questions.") i2 = len(self.game.questionsUsed) nextQ = self.game.askAnotherQuestion() while nextQ != None: pixmap = QPixmap("Akinator3.png") l.setPixmap(pixmap) label.setText(nextQ) btn.clicked.connect(dialog) btn2.clicked.connect(dialog1) btn3.clicked.connect(dialog2) o = 0 while o == 0: QtCore.QCoreApplication.processEvents() answer = a print(nextQ) while answer == -1: print(nextQ) print( "Please answer with 'yes', 'no', 'sometimes', 'maybe', or 'unknown'." ) answer = self.game.convertAnswer(input()) self.game.answerQuestion(self.game.questionsUsed[i2], answer) nextQ = self.game.askAnotherQuestion() i2 += 1 self.game.updateWeights(correctAnswer) else: self.game.updateWeights(selected) self.game.resetGame() d = QMessageBox.question(w, "Otakunator", "Continue?", QMessageBox.Yes | QMessageBox.No, QMessageBox.No) answer = -1 if d == QMessageBox.Yes: answer = 1 else: answer = 0 if answer != 1: keepPlaying = False label.setText("")
def getInteger(self): i, okPressed = QInputDialog.getInt(self, "Get column", "Column", 6, 0, 100, 1) if okPressed: return i
def add_roi(self): new_roi_name, ok = QInputDialog.getText( self, "ROI Name", "Insert the name of the new ROI") if new_roi_name and ok: self.roi_added.emit(new_roi_name)
def schedule_process(self, number): #对话框有两个按钮(ok/cancel)一个输入框,ok是按钮值(True/False),text是输入框值 text, ok = QInputDialog.getText( self, "Schedule Input", "\n\n\t输入'enter' : 使进程ready\t\n\n\t 输入'esc' : 使进程block\t\n\n\t 输入其它字符 : 无效\t\n\n\t cmd here:\t\n\n\n" ) if ok: if number == 1: if text == 'enter': global_pcb.pcb.enter(global_pcb.pid1) self.change_status(number, 'ready') self.status_bar.appendPlainText(self.get_time() + '\t[PID1]\tPID1 is ready') #将status状态颜色变为淡蓝 self.stylesheet = self.stylesheet + '#status1{background-color:#99CCFF;}' self.setStyleSheet(self.stylesheet) elif text == 'esc': global_pcb.pcb.block(global_pcb.pid1) self.change_status(number, 'block') self.status_bar.appendPlainText( self.get_time() + '\t[PID1]\tPID1 is blocked') #将status状态颜色变为红色 self.stylesheet = self.stylesheet + '#status1{background-color:#CC3333;}' self.setStyleSheet(self.stylesheet) elif number == 2: if text == 'enter': global_pcb.pcb.enter(global_pcb.pid2) self.change_status(number, 'ready') self.status_bar.appendPlainText(self.get_time() + '\t[PID2]\tPID2 is ready') #将status状态颜色变为淡蓝 self.stylesheet = self.stylesheet + '#status2{background-color:#99CCFF;}' self.setStyleSheet(self.stylesheet) elif text == 'esc': global_pcb.pcb.block(global_pcb.pid2) self.change_status(number, 'block') self.status_bar.appendPlainText( self.get_time() + '\t[PID2]\tPID2 is blocked') #将status状态颜色变为红色 self.stylesheet = self.stylesheet + '#status2{background-color:#CC3333;}' self.setStyleSheet(self.stylesheet) elif number == 3: if text == 'enter': global_pcb.pcb.enter(global_pcb.pid3) self.change_status(number, 'ready') self.status_bar.appendPlainText(self.get_time() + '\t[PID3]\tPID3 is ready') #将status状态颜色变为淡蓝 self.stylesheet = self.stylesheet + '#status3{background-color:#99CCFF;}' self.setStyleSheet(self.stylesheet) elif text == 'esc': global_pcb.pcb.block(global_pcb.pid3) self.change_status(number, 'block') self.status_bar.appendPlainText( self.get_time() + '\t[PID3]\tPID3 is blocked') #将status状态颜色变为红色 self.stylesheet = self.stylesheet + '#status3{background-color:#CC3333;}' self.setStyleSheet(self.stylesheet) elif number == 4: if text == 'enter': global_pcb.pcb.enter(global_pcb.pid4) self.change_status(number, 'ready') self.status_bar.appendPlainText(self.get_time() + '\t[PID4]\tPID4 is ready') #将status状态颜色变为淡蓝 self.stylesheet = self.stylesheet + '#status4{background-color:#99CCFF;}' self.setStyleSheet(self.stylesheet) elif text == 'esc': global_pcb.pcb.block(global_pcb.pid4) self.change_status(number, 'block') self.status_bar.appendPlainText( self.get_time() + '\t[PID4]\tPID4 is blocked') #将status状态颜色变为红色 self.stylesheet = self.stylesheet + '#status4{background-color:#CC3333;}' self.setStyleSheet(self.stylesheet) elif number == 5: if text == 'enter': global_pcb.pcb.enter(global_pcb.pid5) self.change_status(number, 'ready') self.status_bar.appendPlainText(self.get_time() + '\t[PID5]\tPID5 is ready') #将status状态颜色变为淡蓝 self.stylesheet = self.stylesheet + '#status5{background-color:#99CCFF;}' self.setStyleSheet(self.stylesheet) elif text == 'esc': global_pcb.pcb.block(global_pcb.pid5) self.change_status(number, 'block') self.status_bar.appendPlainText( self.get_time() + '\t[PID5]\tPID5 is blocked') #将status状态颜色变为红色 self.stylesheet = self.stylesheet + '#status5{background-color:#CC3333;}' self.setStyleSheet(self.stylesheet)
def generate_certificate(self): text, ok = QInputDialog.getText(self, 'Key pair Alias', 'Enter alias:') if ok: FileSigner().generate_new_key(text) self.refresh_data_in_privkey_table()
def dialog_file_to_verify(self): options = QFileDialog.Options() options |= QFileDialog.DontUseNativeDialog file_path, _ = QFileDialog.getOpenFileName( self, "Choose file to check signature for...", "", "All Files (*)", options=options) if file_path: msg_box = QMessageBox() msg_box.setWindowTitle("Verification result") msg_box.setStandardButtons(QMessageBox.Ok) result = FileSigner().verify_signature(file_path) if result != 2 and result: msg_box.setIcon(QMessageBox.Information) try: msg_box.setText("File has been signed by " + result) except: if result[1] == "11": msg_box.setText("File has been signed by " + str(result[0][0]) + " using a certificate issued by " + str(result[0][1])) if result[1] == "01": msg_box.setIcon(QMessageBox.Warning) msg_box.setText( "Warning! File has been signed by " + str(result[0][0]) + " using a certificate issued by " + str(result[0][1]) + ", but the root CA is NOT TRUSTED by your system ") if result[1] == "00": msg_box.setIcon(QMessageBox.Critical) msg_box.setText( "Warning! File has been signed by " + str(result[0][0]) + " using a certificate issued by " + str(result[0][1]) + ", but the root CA is NOT TRUSTED by your system. Certificate is expired" ) if result[1] == "00": msg_box.setIcon(QMessageBox.Critical) msg_box.setText("Warning! File has been signed by " + str(result[0][0]) + " using a certificate issued by " + str(result[0][1]) + ". Certificate is expired") msg_box.exec() if not (result): msg_box.setIcon(QMessageBox.Critical) msg_box.setText( "WARNING!!! DO NOT TRUST!!! Signature check failed. File has been modified!" ) msg_box.exec() if result == 2: msg_box = QMessageBox.question( self, 'Verification result', "This public key does not exist in your trusted set." "Importing it is a very dangerous thing if you do not know the key, or you are not sure whom this key " "belongs to, as someone may have tampered with the file on it's way. Do you want to import it?" + open("temp/pkey.key").read(), QMessageBox.Yes | QMessageBox.No, QMessageBox.No) if msg_box == QMessageBox.Yes: alias, ok = QInputDialog.getText(self, 'Public Key Alias', 'Enter alias:') if ok: FileSigner().import_public_key("temp/pkey.key", alias) self.refresh_data_in_pubkey_table() result = FileSigner().verify_signature(file_path) if result == False: msg_box = QMessageBox() msg_box.setWindowTitle("Verification result") msg_box.setStandardButtons(QMessageBox.Ok) msg_box.setIcon(QMessageBox.Critical) msg_box.setText( "WARNING!!! DO NOT TRUST!!! Signature check failed. File has been modified! The key remains imported. If you wish, you can delete it manually" ) msg_box.exec() else: msg_box = QMessageBox() msg_box.setWindowTitle("Verification result") msg_box.setStandardButtons(QMessageBox.Ok) msg_box.setIcon(QMessageBox.Information) msg_box.setText("File has been signed by " + result[0] + "(The newly added key)") msg_box.exec() else: print('No clicked.')
def _vcsCheckout(self, export=False): """ Protected slot used to create a local project from the repository. @param export flag indicating whether an export or a checkout should be performed """ if not self.project.checkDirty(): return vcsSystemsDict = e5App().getObject("PluginManager")\ .getPluginDisplayStrings("version_control") if not vcsSystemsDict: # no version control system found return vcsSystemsDisplay = [] keys = sorted(vcsSystemsDict.keys()) for key in keys: vcsSystemsDisplay.append(vcsSystemsDict[key]) vcsSelected, ok = QInputDialog.getItem( None, self.tr("New Project"), self.tr("Select version control system for the project"), vcsSystemsDisplay, 0, False) if not ok: return for vcsSystem, vcsSystemDisplay in list(vcsSystemsDict.items()): if vcsSystemDisplay == vcsSelected: break if not self.project.closeProject(): return self.project.pdata["VCS"] = [vcsSystem] self.project.vcs = self.project.initVCS(vcsSystem) if self.project.vcs is not None: vcsdlg = self.project.vcs.vcsNewProjectOptionsDialog() if vcsdlg.exec_() == QDialog.Accepted: projectdir, vcsDataDict = vcsdlg.getData() self.project.pdata["VCS"] = [vcsSystem] self.project.vcs = self.project.initVCS(vcsSystem) # edit VCS command options if self.project.vcs.vcsSupportCommandOptions(): vcores = E5MessageBox.yesNo( self.parent(), self.tr("New Project"), self.tr( """Would you like to edit the VCS command""" """ options?""")) else: vcores = False if vcores: from .CommandOptionsDialog import VcsCommandOptionsDialog codlg = VcsCommandOptionsDialog(self.project.vcs) if codlg.exec_() == QDialog.Accepted: self.project.vcs.vcsSetOptions(codlg.getOptions()) # create the project directory if it doesn't exist already if not os.path.isdir(projectdir): try: os.makedirs(projectdir) except EnvironmentError: E5MessageBox.critical( self.parent(), self.tr("Create project directory"), self.tr( "<p>The project directory <b>{0}</b> could not" " be created.</p>").format(projectdir)) self.project.pdata["VCS"] = ['None'] self.project.vcs = self.project.initVCS() return # create the project from the VCS self.project.vcs.vcsSetDataFromDict(vcsDataDict) if export: ok = self.project.vcs.vcsExport(vcsDataDict, projectdir) else: ok = self.project.vcs.vcsCheckout(vcsDataDict, projectdir, False) if ok: projectdir = os.path.normpath(projectdir) filters = ["*.e4p"] d = QDir(projectdir) plist = d.entryInfoList(filters) if len(plist): if len(plist) == 1: self.project.openProject( plist[0].absoluteFilePath()) self.project.newProject.emit() else: pfilenamelist = d.entryList(filters) pfilename, ok = QInputDialog.getItem( None, self.tr("New project from repository"), self.tr("Select a project file to open."), pfilenamelist, 0, False) if ok: self.project.openProject( QFileInfo(d, pfilename).absoluteFilePath()) self.project.newProject.emit() if export: self.project.pdata["VCS"] = ['None'] self.project.vcs = self.project.initVCS() self.project.setDirty(True) self.project.saveProject() else: res = E5MessageBox.yesNo( self.parent(), self.tr("New project from repository"), self.tr( "The project retrieved from the repository" " does not contain an eric project file" " (*.e4p). Create it?"), yesDefault=True) if res: self.project.ppath = projectdir self.project.opened = True from Project.PropertiesDialog import \ PropertiesDialog dlg = PropertiesDialog(self.project, False) if dlg.exec_() == QDialog.Accepted: dlg.storeData() self.project.initFileTypes() self.project.setDirty(True) try: ms = os.path.join( self.project.ppath, self.project.pdata["MAINSCRIPT"][0]) if os.path.exists(ms): self.project.appendFile(ms) except IndexError: ms = "" self.project.newProjectAddFiles(ms) self.project.createProjectManagementDir() self.project.saveProject() self.project.openProject(self.project.pfile) if not export: res = E5MessageBox.yesNo( self.parent(), self.tr( "New project from repository"), self.tr( "Shall the project file be added" " to the repository?"), yesDefault=True) if res: self.project.vcs.vcsAdd( self.project.pfile) else: E5MessageBox.critical( self.parent(), self.tr("New project from repository"), self.tr( """The project could not be retrieved from""" """ the repository.""")) self.project.pdata["VCS"] = ['None'] self.project.vcs = self.project.initVCS() else: self.project.pdata["VCS"] = ['None'] self.project.vcs = self.project.initVCS()
def prompt_for_password(is_encryption): '''Prompt user for password''' # Pop up a password-customised input dialog dialog = QInputDialog(main_win) text = ('Please provide a password to %s the OTP key/secret with:' % ('encrypt' if is_encryption else 'decrypt')) dialog.setWindowTitle(SCRIPT_NAME) dialog.setLabelText(text) dialog.setInputMode(QInputDialog.TextInput) dialog.setTextEchoMode(QLineEdit.Password) # Default to empty password if the dialog is rejected. Password validation # is done with the calling code if dialog.exec_() == QDialog.Accepted: return dialog.textValue() else: return ''
def showdialog(self): text, ok = QInputDialog.getText(self, 'input dialog', 'enter your name') if ok: self.le.setText(str(text))
def _vcsImport(self): """ Protected slot used to import the local project into the repository. <b>NOTE</b>: This does not necessarily make the local project a vcs controlled project. You may have to checkout the project from the repository in order to accomplish that. """ def revertChanges(): """ Local function to revert the changes made to the project object. """ self.project.pdata["VCS"] = pdata_vcs[:] self.project.pdata["VCSOPTIONS"] = copy.deepcopy(pdata_vcsoptions) self.project.pdata["VCSOTHERDATA"] = copy.deepcopy(pdata_vcsother) self.project.vcs = vcs self.project.vcsProjectHelper = vcsHelper self.project.vcsBasicHelper = vcs is None self.initMenu(self.project.vcsMenu) self.project.setDirty(True) self.project.saveProject() pdata_vcs = self.project.pdata["VCS"][:] pdata_vcsoptions = copy.deepcopy(self.project.pdata["VCSOPTIONS"]) pdata_vcsother = copy.deepcopy(self.project.pdata["VCSOTHERDATA"]) vcs = self.project.vcs vcsHelper = self.project.vcsProjectHelper vcsSystemsDict = e5App().getObject("PluginManager")\ .getPluginDisplayStrings("version_control") if not vcsSystemsDict: # no version control system found return vcsSystemsDisplay = [] keys = sorted(list(vcsSystemsDict.keys())) for key in keys: vcsSystemsDisplay.append(vcsSystemsDict[key]) vcsSelected, ok = QInputDialog.getItem( None, self.tr("Import Project"), self.tr("Select version control system for the project"), vcsSystemsDisplay, 0, False) if not ok: return for vcsSystem, vcsSystemDisplay in list(vcsSystemsDict.items()): if vcsSystemDisplay == vcsSelected: break self.project.pdata["VCS"] = [vcsSystem] self.project.vcs = self.project.initVCS(vcsSystem) if self.project.vcs is not None: vcsdlg = self.project.vcs.vcsOptionsDialog(self.project, self.project.name, 1) if vcsdlg.exec_() == QDialog.Accepted: vcsDataDict = vcsdlg.getData() # edit VCS command options if self.project.vcs.vcsSupportCommandOptions(): vcores = E5MessageBox.yesNo( self.parent(), self.tr("Import Project"), self.tr( """Would you like to edit the VCS command""" """ options?""")) else: vcores = False if vcores: from .CommandOptionsDialog import VcsCommandOptionsDialog codlg = VcsCommandOptionsDialog(self.project.vcs) if codlg.exec_() == QDialog.Accepted: self.project.vcs.vcsSetOptions(codlg.getOptions()) self.project.setDirty(True) self.project.vcs.vcsSetDataFromDict(vcsDataDict) self.project.saveProject() isVcsControlled = self.project.vcs.vcsImport( vcsDataDict, self.project.ppath)[0] if isVcsControlled: # reopen the project self.project.openProject(self.project.pfile) else: # revert the changes to the local project # because the project dir is not a VCS directory revertChanges() else: # revert the changes because user cancelled revertChanges()
def getInt(self): inteiro, ok = QInputDialog.getInt(self, "Entrada de inteiro", "Digite um número") if ok: self.lineedit2.setText(str(inteiro))
def getText(self): texto, ok = QInputDialog.getText(self, "Entrada de texto", "Digite algo") if ok: self.lineedit3.setText(str(texto))
def save_spiketrains(self): tot_timestamps = [] num_timestamps = [] merge_timestamps = [] # for all merged waveforms print "Saving spiketrains" with SaveFile(self.sortfile) as qq: if ("samplingRate" not in qq.keys()) and ("samplingrate" not in qq.keys()): if self.sampling_rate == -1.0: text, ok = QInputDialog.getText(self, 'Sampling rate', 'Sampling rate [Hz] :') if ok: self.sampling_rate = float(text) else: return # not able to continue with a sampling rate else: self.sampling_rate = qq.get("samplingRate", qq.get("samplingrate", 0.0)) template_idx = [ int(filter(lambda x: x.isdigit(), v)) for v in self.picked_lines ] merge_idx = [ int(filter(lambda x: x.isdigit(), v)) for v in self.merged_lines ] nstates = self.waveforms.shape[-1] pidx = int(nstates / 3) if qq["mlseq"].shape[0] == self.waveforms.shape[0]: uidx, tidx = np.where(qq["mlseq"][:] == pidx) else: tidx, uidx = np.where(qq["mlseq"][:] == pidx) for (ii, tt) in enumerate(template_idx): iidx, = np.where(uidx == tt) tot_timestamps.append(tidx[iidx] * 1000 / self.sampling_rate) saveind_idx = list( set(template_idx) - set(merge_idx)) # only waveforms to save individually if merge_idx: for i in merge_idx: idx = merge_idx.index(i) merge_timestamps = self.addto_array( merge_timestamps, tot_timestamps[idx]) merge_timestamps = list(set(merge_timestamps)) merge_timestamps.sort() if self.ishdf5 == True: self.waveforms = np.transpose(self.waveforms[:, :, :]) merge_waveforms = np.mean(self.waveforms[merge_idx, :, :], axis=0) cname = "cell%02d" % (self.counter + 1, ) cdir = os.path.join(os.path.dirname(self.sortfile), cname) if not os.path.isdir(cdir): os.mkdir(cdir) fname = cdir + os.path.sep + "spiketrain.mat" mio.savemat(fname, { "timestamps": merge_timestamps, "spikeForm": merge_waveforms }) self.counter += 1 if saveind_idx: for i in saveind_idx: idx = template_idx.index(i) timestamps = tot_timestamps[idx][0].tolist() if self.ishdf5 == True: self.waveforms = np.transpose(self.waveforms) cname = "cell%02d" % (self.counter + 1, ) cdir = os.path.join(os.path.dirname(self.sortfile), cname) if not os.path.isdir(cdir): os.mkdir(cdir) fname = cdir + os.path.sep + "spiketrain.mat" mio.savemat( fname, { "timestamps": timestamps, "spikeForm": self.waveforms[i, :, :] }) self.counter += 1 msg = QMessageBox() msg.setIcon(QMessageBox.Information) msg.setText("Spiketrains saved") msg.setWindowTitle("Info") retval = msg.exec_()
def getItem(self): items = ("C", "C++", "Java", "Python") item, ok = QInputDialog.getItem(self, "combobox", "linguagens", items, 0, False) if ok and item: self.lineedit1.setText(item)
def on_btnSshReadRpcConfig_clicked(self): """Read the configuration of a remote RPC node from the node's stash.conf file.""" if self.current_network_cfg: host = self.current_network_cfg.ssh_conn_cfg.host port = self.current_network_cfg.ssh_conn_cfg.port username = self.current_network_cfg.ssh_conn_cfg.username if not host: self.errorMsg('Host address is required') self.ssh_tunnel_widget.edtSshHost.setFocus() if not port: self.errorMsg('Host TCP port number is required') self.ssh_tunnel_widget.edtSshHost.setFocus() ok = True if not username: username, ok = QInputDialog.getText(self, 'Username Dialog', 'Enter username for SSH connection:') if not ok or not username: return from stashd_intf import StashdSSH ssh = StashdSSH(host, int(port), username) try: ssh.connect() stashd_conf = ssh.find_stashd_config() self.disable_cfg_update = True if isinstance(stashd_conf, tuple) and len(stashd_conf) >= 3: if not stashd_conf[0]: self.infoMsg('Remore Stash daemon seems to be shut down') elif not stashd_conf[1]: self.infoMsg('Could not find remote stashd.conf file') else: file = stashd_conf[2] rpcuser = file.get('rpcuser', '') rpcpassword = file.get('rpcpassword', '') rpcport = file.get('rpcport', '9998') modified = False if rpcuser: modified = modified or (self.current_network_cfg.username != rpcuser) self.current_network_cfg.username = rpcuser if rpcpassword: modified = modified or (self.current_network_cfg.password != rpcpassword) self.current_network_cfg.password = rpcpassword if rpcport: modified = modified or (self.current_network_cfg.port != rpcport) self.current_network_cfg.port = rpcport rpcbind = file.get('rpcbind', '') if not rpcbind: # listen on all interfaces if not set rpcbind = '127.0.0.1' modified = modified or (self.current_network_cfg.host != rpcbind) self.current_network_cfg.host = rpcbind if modified: self.is_modified = modified if file.get('server', '1') == '0': self.warnMsg("Remote stash.conf parameter 'server' is set to '0', so RPC interface will " "not work.") if not rpcuser: self.warnMsg("Remote stash.conf parameter 'rpcuser' is not set, so RPC interface will " "not work.") if not rpcpassword: self.warnMsg("Remote stash.conf parameter 'rpcpassword' is not set, so RPC interface will " "not work.") self.update_connection_details_ui() elif isinstance(stashd_conf, str): self.warnMsg("Couldn't read remote stashd configuration file due the following error: " + stashd_conf) ssh.disconnect() except Exception as e: self.errorMsg(str(e)) return finally: self.disable_cfg_update = False
def accept(self): # "OK" button # check if all fields are filled up nothingSelected = True for i in self.polygonItems: for j in range(1, len(self.polygonItems[i])): if self.polygonItems[i][j][2]: nothingSelected = False for i in self.rasterItems: for j in range(1, len(self.rasterItems[i])): if self.rasterItems[i][j][2]: nothingSelected = False if self.TargetLayer.currentText() == "": QMessageBox.information(self, self.tr("Extract Tool"), self.tr("Please select target point layer")) return if nothingSelected: QMessageBox.information(self, self.tr("Extract Tool"), self.tr("Please select at least one field")) return if self.OutLayer.text() == "": QMessageBox.information(self, self.tr("Extract Tool"), self.tr("Please specify output file name")) return # check if target field names are unique if not self.testFieldNames(self.fields): self.updateFieldsTable() QMessageBox.warning(self, self.tr("Extract Tool"), self.tr("At least two field names are the same!\nPlease type unique names.")) return # check if there a CRS mismatch targetLayerSrid = list(self.targetItems.values())[0][0].crs().postgisSrid() msg = self.tr('''<html>All layers must have the same coordinate reference system. The <b>%s</b> layer seems to have different CRS id (<b>%d</b>) than the point layer (<b>%d</b>). If they are two different CRSes, you need to reproject one of the layers first, otherwise results will be wrong.<br/> However, if you are sure both CRSes are the same, and they are just improperly recognized, you can safely continue. Do you want to continue?</html>''') for i in self.polygonItems: for j in range(1, len(self.polygonItems[i])): if self.polygonItems[i][j][2]: layerSrid = self.polygonItems[i][0].crs().postgisSrid() if layerSrid != targetLayerSrid: if QMessageBox.question(self, self.tr("Extract Tool: layer CRS mismatch!"), msg % (i, layerSrid, targetLayerSrid), QMessageBox.Yes | QMessageBox.No) != QMessageBox.Yes: return for i in self.rasterItems: for j in range(1, len(self.rasterItems[i])): if self.rasterItems[i][j][2]: layerSrid = self.rasterItems[i][0].crs().postgisSrid() if layerSrid != targetLayerSrid: if QMessageBox.question(self, self.tr("Extract Tool: layer CRS mismatch!"), msg % (i, layerSrid, targetLayerSrid), QMessageBox.Yes | QMessageBox.No) != QMessageBox.Yes: return if True: # all tests passed, go on self.repaint() outPath = self.OutLayer.text() outPath = outPath.replace("\\","/") if not outPath.upper().endswith('.SHP') and not outPath.upper().endswith('.CSV') and not outPath.upper().endswith('.GPKG'): outPath += '.gpkg' outName = QFileInfo(outPath).fileName() tableName = None oldFile = QFile(outPath) if oldFile.exists(): if not outPath.upper().endswith('.GPKG'): if QMessageBox.question(self, self.tr("Extract Tool"), self.tr("File %s already exists. Do you want to overwrite?") % outName) == QMessageBox.No: self.OutLayer.clear() self.repaint() return else: msg = self.tr("""Please provide <b>table name</b> for your layer.<br/> <b>WARNING: </b>Database %s already exists. If you select a table existing in it, the table will be overwritten.""") % outName tableName, result = QInputDialog.getText(self, "Extract Tool", msg, text = outName[:-5]) if not result: self.OutLayer.clear() self.repaint() return self.repaint() # execute main function if not self.extract(outPath, tableName): return self.OutLayer.clear() if self.AddToMap.checkState() == Qt.Checked: uri = outPath layerName = outName if tableName: uri += "|layername=%s" % tableName layerName += ": %s" % tableName self.vlayer = QgsVectorLayer(uri, layerName, "ogr") if self.vlayer.isValid(): # Add layer to the map, but first remove it if already present for l in QgsProject.instance().mapLayers().values(): if hasattr(l, 'source') and l.source() == self.vlayer.source(): QgsProject.instance().removeMapLayer(l) QgsProject.instance().addMapLayer(self.vlayer) else: QMessageBox.warning(self, self.tr("Extract Tool"), self.tr("The new layer seems to be created, but is invalid.\nIt won't be loaded."))
def _get_input(self): text, ok = QInputDialog.getText(self, 'Input Dialog', 'Enter your name:') if ok: self.ui.statusbar.showMessage("Your name is " + text)
def showDialog(self): text, ok = QInputDialog.getText(self, 'Input Dialog', 'Введите ФИО пациента:') if ok and text !='': self.le.setText(str(text))
def showDialog(self): text, ok = QInputDialog.getText(self, "Input Dialog", "Enter your name") if ok: self.le.setText(str(text))
def pushButtonAdd_clickedEvent( self ): ########################변경내용: text -> title로 인자이름 변경 밑 추가############################################################## row = self.ui.listWidgetRuleNo.currentRow( ) # 왼쪽 규칙 리스트에서 현재 클릭된 아이템의 행(currentRow)위치를 row로 받아옴 title, ok = QInputDialog.getText( self, "규칙 이름 추가", "추가할 규칙의 이름을 입력하세요.") # 메세지 입력할 수 있는 다이얼로그 띄움 tmp = title.strip(' ') title = tmp ##############################타이틀에 해당하는 검색 키워드 저장하는 구문 추가해야됨 ############################################################## listWidgetRuleOk = self.ui.listWidgetRuleOK listWidgetRuleNo = self.ui.listWidgetRuleNo countListWidgetRuleOk = listWidgetRuleOk.count() countListWidgetRuleNo = listWidgetRuleNo.count() ruleDuplicateFlag = 0 # 중복 체크 변수 선언 okListItems = [] # 오른쪽 리스트 아이템 받아올 배열 생성 noListItems = [] # 왼쪽 리스트 아이템 받아올 배열 생성 """현재 선택된 규칙 리스트의 아이템에 기능제한 체크박스 체크한 TRUE FALSE값 저장시킴""" """변수를 주고 넘겨서 나중에 규칙 리스트 더블클릭하여 수정하고플 시 , 값 읽어오게 해야됨""" if countListWidgetRuleNo is None: # 왼쪽 리스트에 아이템이 하나도 없을 때 -아이템이 오른쪽 리스트로 전부 다 이동했을 때- 이때는 오른쪽 리스트만 배열에 저장한다 for index in range(countListWidgetRuleOk ): # 오른쪽 리스트를 count()하여 item의 갯수를 알아내어 반복 okListItems.append(listWidgetRuleOk.item(index).text( )) # 오른쪽 리스트의 아이템을 텍스트형태로 받아와서 noListItems배열에 저장 if ok and title != '': for i in range(len(okListItems)): if title == okListItems[i]: ruleDuplicateFlag = 1 # 중복체크변수 1로 세팅 self.showNoDuplicate() # 중복 경고메세지박스 출력 함수 호출 if ruleDuplicateFlag == 0: listWidgetRuleNo.insertItem( row, title ) # 왼쪽 규칙 리스트에서 현재 클릭된 아이템의 행 바로 위에 입력한 title을 추가함 (아이템을 클릭하지 않았다면 기본 값은 맨 위) # cm.configset2(title) #############################변경사항 text -> title 로 인자이름 변경 ######################################################## cmt.add_tmp(title) # print("되냐") self.second = secondWindow() self.second.show() print("해당 규칙은 중복되지 않습니다.") print("추가완료") elif ok: # 사용자가 text(규칙)에 값을 안 넣었을 때 오류 메세지박스 띄움 plzInputRule = QtWidgets.QMessageBox(self) plzInputRule.setWindowTitle("규칙 입력 오류") plzInputRule.setIcon(QtWidgets.QMessageBox.Warning) plzInputRule.setText("규칙을 제대로 입력하세요.") plzInputRule.exec_() elif countListWidgetRuleOk is None: # 오른쪽 리스트에 아이템이 하나도 없을 때 -아이템이 왼쪽 리스트로 전부 다 이동했을 때- 이때는 왼쪽 리스트만 배열에 저장한다 for index in range(countListWidgetRuleNo ): # 왼쪽 리스트를 count()하여 item의 갯수를 알아내어 반복 noListItems.append(listWidgetRuleNo.item(index).text( )) # 왼쪽 리스트의 아이템을 텍스트형태로 받아와서 noListItems배열에 저장 if ok and title != '': for i in range(len(noListItems)): if title == noListItems[i]: ruleDuplicateFlag = 1 # 중복체크변수 1로 세팅 self.showNoDuplicate() # 중복 경고메세지박스 출력 함수 호출 if ruleDuplicateFlag == 0: listWidgetRuleNo.insertItem( row, title ) # 왼쪽 규칙 리스트에서 현재 클릭된 아이템의 행 바로 위에 입력한 title을 추가함 (아이템을 클릭하지 않았다면 기본 값은 맨 위) # cm.configset2(title) #############################변경사항 text -> title 로 인자이름 변경 ######################################################## cmt.add_tmp(title) print("되냐") self.second = secondWindow() self.second.show() print("해당 규칙은 중복되지 않습니다.") print("추가완료") elif ok: # 사용자가 title(규칙제목)에 값을 안 넣었을 때 오류 메세지박스 띄움 plzInputRule = QtWidgets.QMessageBox(self) plzInputRule.setWindowTitle("규칙 입력 오류") plzInputRule.setIcon(QtWidgets.QMessageBox.Warning) plzInputRule.setText("규칙을 제대로 입력하세요.") plzInputRule.exec_() else: # 왼쪽, 오른쪽 규칙 리스트에 다 아이템이 있을 때 for index in range(countListWidgetRuleOk ): # 오른쪽 리스트를 count()하여 item의 갯수를 알아내어 반복 okListItems.append(listWidgetRuleOk.item(index).text( )) # 오른쪽 리스트의 아이템을 텍스트형태로 받아와서 noListItems배열에 저장 for index in range(countListWidgetRuleNo ): # 왼쪽 리스트를 count()하여 item의 갯수를 알아내어 반복 noListItems.append(listWidgetRuleNo.item(index).text( )) # 왼쪽 리스트의 아이템을 텍스트형태로 받아와서 noListItems배열에 저장 if ok and title != '': for i in range(len(noListItems)): if title == noListItems[i]: ruleDuplicateFlag = 1 # 중복체크변수 1로 세팅 self.showNoDuplicate() # 중복 경고메세지박스 출력 함수 호출 break else: for j in range(len(okListItems)): if title == okListItems[j]: ruleDuplicateFlag = 1 # 중복체크변수 1로 세팅 self.showNoDuplicate() # 중복 경고메세지박스 출력 함수 호출 if ruleDuplicateFlag == 0: listWidgetRuleNo.insertItem( row, title ) # 왼쪽 규칙 리스트에서 현재 클릭된 아이템의 행 바로 위에 입력한 text를 추가함 (아이템을 클릭하지 않았다면 기본 값은 맨 위) # cm.configset2(title) #############################변경사항 text -> title 로 인자이름 변경 ######################################################## cmt.add_tmp(title) print("되냐") self.second = secondWindow() self.second.show() print("해당 규칙은 중복되지 않습니다.") print("추가완료") elif ok: # 사용자가 text(규칙)에 값을 안 넣었을 때 오류 메세지박스 띄움 plzInputRule = QtWidgets.QMessageBox(self) plzInputRule.setWindowTitle("규칙 입력 오류") plzInputRule.setIcon(QtWidgets.QMessageBox.Warning) plzInputRule.setText("규칙을 제대로 입력하세요.") plzInputRule.exec_()
class TabBarPlus(QTabBar): """Tab bar that has a plus button floating to the right of the tabs.""" plusClicked = pyqtSignal() def __init__(self, parent): super(TabBarPlus, self).__init__() self.setParent(parent) self.setStyleSheet(""" color: white; border-radius: 4px; background:rgb(37,43,52,220); """) # Plus Button self.plusButton = QPushButton("+") self.plusButton.setParent(self) self.plusButton.setMaximumSize(20, 20) # Small Fixed size self.plusButton.setMinimumSize(20, 20) # Small Fixed size self.plusButton.clicked.connect(self.plusClicked.emit) self.movePlusButton() # Move to the correct location # end Constructor def sizeHint(self): """Return the size of the TabBar with increased width for the plus button.""" sizeHint = QTabBar.sizeHint(self) width = sizeHint.width() height = sizeHint.height() return QSize(width+25, height) # end tabSizeHint def resizeEvent(self, event): """Resize the widget and make sure the plus button is in the correct location.""" super().resizeEvent(event) self.movePlusButton() # end resizeEvent def tabLayoutChange(self): """This virtual handler is called whenever the tab layout changes. If anything changes make sure the plus button is in the correct location. """ super().tabLayoutChange() self.movePlusButton() # end tabLayoutChange def mouseDoubleClickEvent(self, event): if event.button() != Qt.LeftButton: super(TabBarPlus, self).mouseDoubleClickEvent(event) idx = self.currentIndex() ok = True self.input_dialog = QInputDialog() print(type(self.input_dialog.textEchoMode())) newName, ok = QInputDialog.getText(self, 'Mudar nome', 'Novo nome:') if ok: self.parent().tables[idx].name = newName self.parent().series[idx].setName(newName) self.setTabText(idx, newName) def open_kb(self): print("open kb") # KEYBOARD.close() # KEYBOARD.open() # KEYBOARD.set_receiver(self.input_dialog) def movePlusButton(self): """Move the plus button to the correct location.""" # Find the width of all of the tabs size = 0 for i in range(self.count()): size += self.tabRect(i).width() # Set the plus button location in a visible area h = self.geometry().top() w = self.width() if size > w: # Show just to the left of the scroll buttons self.plusButton.move(w-54, h) else: self.plusButton.move(size, h)
def tryToRenameTopBlob(self, connector): """ Shows a input dialog to ask for a new blob name and notifies the NetworkManager to change the blobs name. """ # show input dialog name, ok = QInputDialog.getText(self.__view, "Change name of top blob", "Top blob name:") name = name.strip() # if the name is invalid ask again duplicateFound = True while ok: if len(name) == 0: QMessageBox.warning( self.__view, "Top blob name is empty", "The name for the top blob can't be empty or all whitespace characters." ) name, ok = QInputDialog.getText(self.__view, "Change name of top blob", "Top blob name:") name = name.strip() continue elif duplicateFound: for blob in connector.getNodeItem().getTopConnectors(): if name == blob.getBlobName() and blob != connector: QMessageBox.warning( self.__view, "Top blob name already exists", "The name you chose already exists on this Layer, please choose another name." ) name, ok = QInputDialog.getText( self.__view, "Change name of top blob", "Top blob name:") name = name.strip() duplicateFound = True break # stop for loop, continue while loop else: duplicateFound = False else: break # if string is valid # the user provided a valid name if ok: # check if any bottom connector has multiple connections as a bottom connector can only have one name bottomConnectorWithMultipleConnectionsFound = False connections = connector.getConnections() for connection in connections: bottomConnector = connection.getBottomConnector() if bottomConnector.getConnectionCount() > 1: bottomConnectorWithMultipleConnectionsFound = True # ask the user whether they want to continue (break invalid connections) ore cancel shouldRename = True if bottomConnectorWithMultipleConnectionsFound: reply = QMessageBox.question( self.__view, "Removing connections", "A bottom blob, connected to the top blob, has multiple connections. " "By renaming the top blob, the other connections will get removed. " "Continue?", QMessageBox.Yes, QMessageBox.No) if reply != QMessageBox.Yes: shouldRename = False # if the user did not cancel -> notify the Networkmanager if shouldRename: self.__networkManager.renameTopBlob( connector.getNodeItem().getLayerID(), connector.getIndex(), name)