def __init__(self, opPixelClassification, parent): super( QDialog, self ).__init__(parent=parent) self._op = opPixelClassification classifier_listwidget = QListWidget(parent=self) classifier_listwidget.setSelectionMode( QListWidget.SingleSelection ) classifier_factories = self._get_available_classifier_factories() for name, classifier_factory in list(classifier_factories.items()): item = QListWidgetItem( name ) item.setData( Qt.UserRole, classifier_factory ) classifier_listwidget.addItem(item) buttonbox = QDialogButtonBox( Qt.Horizontal, parent=self ) buttonbox.setStandardButtons( QDialogButtonBox.Ok | QDialogButtonBox.Cancel ) buttonbox.accepted.connect( self.accept ) buttonbox.rejected.connect( self.reject ) layout = QVBoxLayout() layout.addWidget( classifier_listwidget ) layout.addWidget( buttonbox ) self.setLayout(layout) self.setWindowTitle( "Select Classifier Type" ) # Save members self._classifier_listwidget = classifier_listwidget
def familyChanged(self,currentText): if not currentText == "Aircraft Family" and not currentText == "": self.familyMenu.setCurrentText("Aircraft Family") index = self.familyMenu.findText(currentText) if currentText.endswith(self.checkMark): newText = currentText[0:-2] self.familyMenu.setItemText(index,newText) subTypes = self.acSchema[0][newText] fullNames = [] for subType in subTypes: fullNames.append(self.acSchema[1][subType]) self.current_subTypeVector[subType] = False for index in range(self.subTypeList.count()-1,-1,-1): if self.subTypeList.item(index).text() in fullNames: self.subTypeList.takeItem(index) else: self.familyMenu.setItemText(index,currentText+"\t"+self.checkMark) subTypes = self.acSchema[0][currentText] for subType in subTypes: item = QListWidgetItem(self.acSchema[1][subType]) item.setForeground(QtGui.QColor('green')) self.subTypeList.addItem(item) self.current_subTypeVector[subType] = True ############SORT SUBTYPE LIST!!!!!!!!!!!################# self.sendAircraft()
def set_start_settings(self): query = "SELECT Id, Name FROM accessories_name WHERE For_Beika = 1" sql_info = my_sql.sql_select(query) if "mysql.connector.errors" in str(type(sql_info)): QMessageBox.critical(self, "Ошибка sql получения разрешеной фурнитуры", sql_info.msg, QMessageBox.Ok) return False if len(sql_info) > 1: QMessageBox.critical(self, "Ошибка фурнитуры", "Выбрано 2 фурнитуры! Это не правильно!", QMessageBox.Ok) self.close() self.destroy() return False elif len(sql_info) == 1: self.le_accessories_name.setWhatsThis(str(sql_info[0][0])) self.le_accessories_name.setText(str(sql_info[0][1])) elif len(sql_info) == 0: self.le_accessories_name.setWhatsThis("None") self.le_accessories_name.setText("None") query = "SELECT Id, Name FROM material_name WHERE For_Beika = 1 ORDER BY Name" sql_info = my_sql.sql_select(query) if "mysql.connector.errors" in str(type(sql_info)): QMessageBox.critical(self, "Ошибка sql получения разрешеной ткани", sql_info.msg, QMessageBox.Ok) return False self.lw_material_name.clear() for material in sql_info: item = QListWidgetItem(material[1]) item.setData(-1, material[0]) self.lw_material_name.addItem(item)
def createListWidget(self): listWidget = QListWidget() w, h = self.ITEM_SIZE scroll_size = 16 listWidget.setFixedWidth(w + scroll_size) listWidget.setAttribute(Qt.WA_MacShowFocusRect, False) for x in xrange(self._min_size, self._max_size): h = max(x + self.MARGIN * 2.0, h) pixmap = QPixmap(w, h) pixmap.fill(Qt.transparent) painter = QPainter(pixmap) center = h / 2.0 painter.fillRect(QRectF(self.MARGIN, center - x / 2.0, w - self.MARGIN * 2.0, x), Qt.black) painter.end() label = QLabel() label.setPixmap(pixmap) item = QListWidgetItem(listWidget) item.setSizeHint(QSize(w, h)) item.setData(Qt.UserRole, x) listWidget.addItem(item) listWidget.setItemWidget(item, label) if self._size == x: listWidget.setCurrentItem(item) return listWidget
def __init__(self, parent=None): QDialog.__init__(self) self.setupUi(self) for it in G.categoryList: item = QListWidgetItem(it, self.listWidgetCategories) if it in G.categorySet: item.setCheckState(2) else: item.setCheckState(0) catLen = len(G.categoryList) sg = self.geometry() pg = parent.geometry() self.lt = pg.left() + 900 self.tp = pg.top() + 100 self.w = sg.width() self.h = catLen*35 bOfst = (catLen *-25) +410 self.listWidgetCategories.setGeometry(10, 10, 216, catLen * 25) self.pushButtonSelectAll.setGeometry(15, 445 - bOfst, 61, 23) self.pushButtonClearAll.setGeometry(155, 445 - bOfst, 61, 23) self.pushButtonOK.setGeometry(35, 495 - bOfst, 61, 23) self.pushButtonCancel.setGeometry(125, 495 - bOfst, 61, 23) # print(lt, tp, w, h) self.setGeometry(self.lt, self.tp, self.w, self.h) self.listWidgetCategories.setCurrentRow(1) self.pushButtonOK.clicked.connect(self.accept) self.pushButtonCancel.clicked.connect(self.reject) self.pushButtonSelectAll.clicked.connect(self.selectAll) self.pushButtonClearAll.clicked.connect(self.clearAll)
def changeGame(self, game): self.game = game self.engine = ResumeEngine(game) self.savedlist.clear() self.matches = [] candidates = self.engine.getCandidates() if not candidates: self.savedlist.hide() self.resumebutton.hide() self.cancelbutton.hide() self.emptyLabel.show() else: self.emptyLabel.hide() for idMatch, candidate in candidates.items(): self.matches.append(idMatch) savedtime = datetime.datetime.strptime( candidate['started'], "%Y-%m-%d %H:%M:%S.%f") strtime = savedtime.strftime("%Y-%m-%d %H:%M:%S") hours, remainder = divmod(int(candidate['elapsed']), 3600) minutes, seconds = divmod(remainder, 60) strelapsed = "{0:02}:{1:02}:{2:02}".format( hours, minutes, seconds) msg = i18n("ResumeBox", 'Saved on {}. Time played: {}').format(strtime, strelapsed) item = QListWidgetItem(msg, self.savedlist) playerlist = "" for player in candidate['players']: playerlist += "\n " + player item.setToolTip(i18n( "ResumeBox", "Players: {}").format(playerlist)) self.savedlist.addItem(item) self.savedlist.show() self.resumebutton.show() self.cancelbutton.show()
def search(self, text): model = self.ui.search_result_list.model() model.removeRows(0, model.rowCount()) raw_results = index().search(self.ui.search_text.text()) dirs = dict([ (r.get('path'), -1) for r in raw_results if r.get('directory') ]) results = {} for index_, result in enumerate(raw_results): path_ = result.get('path') dir_ = os.path.dirname(path_) if dir_ not in dirs: results[path_] = [result, float(index_) / len(raw_results)] else: dirs[dir_] += 1 for dir_, count in dirs.items(): if dir_ in results: results[dir_][1] += count results = sorted(results.values(), key=lambda x: -x[1]) for result, count in results: postfix = ' (%i)' % (count + 1) if result.get('directory') else '' item = QListWidgetItem( result['path'] + postfix, self.ui.search_result_list ) item.result = result
def _finishAddQuestions(self, t): item = QListWidgetItem() item.setText(t.title) item.setStatusTip(str(t.id)) self.lstTopics.addItem(item) session.commit() print('finished')
def create_list(self, current_path): self.myQListWidget.clear() self.file_field.set_text(name=None, path=None) # file browsing logic # ---------------------- self.parent_path = current_path.rsplit('/', 1)[0] if self.parent_path is "": self.parent_path = "/" if current_path is "/": self.current_path = current_path self.setWindowTitle(current_path) else: self.current_path = current_path + "/" self.setWindowTitle(current_path.rsplit('/', 1)[-1]) # ----------------------- files = sorted(os.scandir(current_path), key=lambda e: e.is_file()) for item in files: if item.is_dir(): list_item = ListItem(name=item.name, drawer=True, current_path=self.current_path, parent=self) else: list_item = ListItem(name=item.name, drawer=False, current_path=self.current_path, parent=self) myQListWidgetItem = QListWidgetItem(self.myQListWidget) myQListWidgetItem.setSizeHint(list_item.sizeHint()) self.myQListWidget.addItem(myQListWidgetItem) self.myQListWidget.setItemWidget(myQListWidgetItem, list_item)
def updateList(self): self.portList.clear() self.backup_indixes = list(self.gui.song.outputsPorts) for name in self.backup_indixes: this_item = QListWidgetItem(name) this_item.setFlags(this_item.flags()) self.portList.addItem(this_item)
def __init__(self, parent, pluginId, useSkins): QListWidgetItem.__init__(self, parent, self.kRackItemType) self.host = parent.host if False: # kdevelop likes this :) parent = RackListWidget() host = CarlaHostMeta() self.host = host self.fWidget = AbstractPluginSlot() # ---------------------------------------------------------------------------------------------------- # Internal stuff self.fParent = parent self.fPluginId = pluginId self.fUseSkins = useSkins self.fWidget = None self.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEnabled) # self.setFlags(Qt.ItemIsSelectable|Qt.ItemIsEnabled|Qt.ItemIsDragEnabled|Qt.ItemIsDropEnabled) # ---------------------------------------------------------------------------------------------------- # Set-up GUI self.recreateWidget()
def createTabColorScheme(self): self.tabColorScheme = QWidget() self.tabColorScheme.setObjectName("tabColorScheme") self.verticalLayout_2 = QVBoxLayout(self.tabColorScheme) self.verticalLayout_2.setObjectName("verticalLayout_2") self.listWidgetColorScheme = QListWidget(self.tabColorScheme) self.listWidgetColorScheme.setObjectName("listWidgetColorScheme") self.verticalLayout_2.addWidget(self.listWidgetColorScheme) self.previewWidgetColor = PreviewWidgetColor(self.tabColorScheme) self.verticalLayout_2.addWidget(self.previewWidgetColor) self.addTab(self.tabColorScheme, self.tr("Color Scheme")) color_list = os.listdir(self.colorSchemePath) color_list.sort() for color in color_list: item = QListWidgetItem(self.listWidgetColorScheme) item.setText(color.split(".")[0]) item.colorSchemeName = color self.listWidgetColorScheme.itemClicked.connect(self.previewColorScheme)
def build_list(self, files): self.listWidget.clear() for fname in files: item = QListWidgetItem(fname) item.setData(Qt.UserRole, fname) self.listWidget.addItem(item) self.listWidget.setCurrentRow(0)
def ui_beika(self): self.timer.start(900000) query = "SELECT Id, Name FROM accessories_name WHERE For_Beika = 1" sql_info = my_sql.sql_select(query) if "mysql.connector.errors" in str(type(sql_info)): return False if len(sql_info) == 1: self.beika_accessories_id = sql_info[0][0] else: return False query = """SELECT Id, Name FROM material_name WHERE For_Beika = 1 ORDER BY Name""" sql_info = my_sql.sql_select(query) if "mysql.connector.errors" in str(type(sql_info)): return False for material in sql_info: item = QListWidgetItem(material[1]) item.setData(-1, (material[0])) item.setTextAlignment(Qt.AlignHCenter) self.lw_material.addItem(item) self.lw_material.setSpacing(5) self.sw_main.setCurrentIndex(9)
def accept(self): while self.running: try: mes = self.socket.recv(4096) mes = pickle.loads(mes) print(mes) if type(mes) == list: if type(mes[0]) == str: if mes[0] == 'to stop': self.stopbtn.click() else: self.active.clear() for i in mes: if i == self.name: i = 'You' a = QListWidgetItem(str(i)) a.setTextAlignment(0x0004) self.active.addItem(a) else: print(mes) self.clientresult = mes self.disp.click() elif type(mes) == dict: self.typing = list(mes.values())[0] self.startmode.click() elif mes == 'Admin: start': self.startmode.click() else: self.list.addItem(QListWidgetItem('{}'.format(mes))) except: pass
def __init__(self, workspace, documents): super(_UISaveFiles, self).__init__(workspace) self.cancelled = False uic.loadUi(os.path.join(DATA_FILES_PATH, 'ui/SaveFiles.ui'), self) self.buttonBox.clicked.connect(self._onButtonClicked) self._documents = documents for index, document in enumerate(documents): name = document.fileName() if name is None: name = 'untitled' item = QListWidgetItem(name, self.listWidget) if document.filePath() is not None: item.setToolTip(document.filePath()) item.setCheckState(Qt.Checked) # Retitle buttons, add first letter shortcuts for them. bb = self.buttonBox self._shortcut = ( self._firstLetterShortcut(bb.Discard, 'close &Without saving'), self._firstLetterShortcut(bb.Cancel, '&Cancel close'), self._firstLetterShortcut(bb.Save, '&Save checked')) self.buttonBox.button(QDialogButtonBox.Cancel).setFocus()
def _appendQuestion(self, q): print('q: ', q) item = QListWidgetItem() item.setText(q.text) item.setStatusTip(str(q.id)) self.lstQuestions.addItem(item) session.add(q)
def __init__(self, parent = None, message = None, itemType = "log"): QListWidgetItem.__init__(self) self.itemType = itemType if (itemType == "log"): self.setText("--- " + str(message)) elif (itemType == "in"): self.setText("<<< " + str(message)) elif (itemType == "out"): self.setText(">>> " + str(message)) else: self.setText(str(message)) font = QFont() font.setFamily("Monospace") if (itemType == "in") or (itemType == "out"): font.setBold(True) font.setWeight(75) else: font.setBold(False) font.setWeight(50) self.setFont(font) brush = QBrush(QColor(0, 0, 0)) if (itemType == "in"): brush = QBrush(QColor(0, 0, 85)) elif (itemType == "out"): brush = QBrush(QColor(0, 85, 0)) brush.setStyle(Qt.NoBrush) self.setForeground(brush)
def plugin_item_changed(self, index): """ This function is called when the user selects another plugin in the plugin tree on the left side. Every change of plugin updates the displayed plugin information on the right side. :param index: :return: """ plugin_info = self.pluginTree.model().data(index, Qt.UserRole) self.clear() self.scrollArea.setDisabled(True) if plugin_info is None: return self.scrollArea.setDisabled(False) self.nameEdit.setText(plugin_info.name) self.authorEdit.setText(plugin_info.author) self.descriptionText.setText(plugin_info.description) self.pathEdit.setText(plugin_info.path) self.createButton.setEnabled(plugin_info.loadable) lines = None with open(plugin_info.path + '.py') as f: lines = f.readlines() found_imports = [] for line in lines: if line.startswith('import'): m = re.search('(import)\s+([\w.]*)(\s+as){0,1}', str.strip(line)) if m is not None: if len(m.groups()) > 2: found_imports.append(m.group(2)) if line.startswith('from'): m = re.search('(from)\s+([\w.]*)(\s+import)', str.strip(line)) if m is not None: if len(m.groups()) > 2: found_imports.append(m.group(2)) found_imports.sort() for imp in found_imports: item = QListWidgetItem(imp) spam_loader = importlib.find_loader(imp) found = spam_loader is not None if not found: self.modulesList.addItem(item) item.setBackground(QColor(255, 0, 0, 50)) if not plugin_info.loadable: self.modulesList.setEnabled(True) self.modulesLabel.setEnabled(True)
def on_solve_clicked(self): """ Solve in domain tab. """ domain = self.domains_dict[str(self.domains.currentItem().text())] if not (self.mesh is not None and domain.dim == 'FILE'): if not self.getMesh() and self.mesh is None: return dim = self.mesh.topology().dim() initsize = self.mesh.size(dim) trans = [self.selectedTransforms.item(i).obj for i in xrange(self.selectedTransforms.count())] bcs = self.getBCList() # create solver and adjust parameters wTop, wBottom = self.getWeights() solver = Solver(self.mesh, bcs, trans, deg=self.femDegree.value(), bcLast=self.useTransformed.isChecked(), method=str(self.femType.currentText()), wTop=wTop, wBottom=wBottom) solver.refineTo(int(self.meshSize.text()), self.meshLimit.currentText() == 'at most', self.refine.currentText() == 'long edge') if self.solveType.currentIndex() == 0: solver.solveFor(self.solveNumber.value(), None, False) else: solver.solveFor(self.solveNumber.value(), float(self.targetValue.text()), False) # get ready for pickling solver.removeMesh() longcalc = LongCalculation(solver, [], pickle_solutions, "Solving") code = longcalc.exec_() if not code: # worker failed longcalc.cleanUp() self.stats.appendPlainText("Solver failed!\n\n") return results = longcalc.res eigv, eigf = results[:2] for i in range(len(eigf)): u = solver.newFunction() u.vector()[:] = eigf[i] eigf[i] = u finalsize = solver.finalsize sol = SolutionTab(dim) sol.data = {'geometry': results[2]} self.fillTabData(sol.data, trans, bcs, str(initsize), str(finalsize), solver.extraRefine) sol.formatData() domain = self.domains.currentItem().text() self.solutionTabs.addTab(sol, domain) for i, [e, u] in enumerate(zip(eigv, eigf)): if abs(e) < 1E-9: e = 0.0 new = QListWidgetItem(str(i+1)+': '+str(e)) new.eigenvalue = e new.eigenfunction = u sol.eigList.addItem(new) self.tabs.tabBar().setCurrentIndex(4) self.solutionTabs.tabBar().setCurrentIndex(self.solutionTabs.count()-1) sol.setFocus(True) self.stats.appendPlainText("Solutions found.\n\n")
def initUI(self): main_layout = QVBoxLayout(self) sub_layout = QHBoxLayout() # Left Panel left_panel = QListWidget() left_panel.setViewMode(left_panel.ListMode) #left_panel.setIconSize(QSize(40,40)) left_panel.setTextElideMode(Qt.ElideRight) left_panel.setMaximumWidth(200) left_panel.itemClicked.connect(self.change) #web.setText('Web') self.application = QListWidgetItem() self.application.setText('Application') self.web = QListWidgetItem() self.web.setText('Web') self.visual = QListWidgetItem() self.visual.setText('Visual') self.advanced = QListWidgetItem() self.advanced.setText('Advanced') self.about = QListWidgetItem() self.about.setText('About') #main.setIcon(QIcon(os.path.join(app_constants.static_dir, 'plus2.png'))) left_panel.addItem(self.application) left_panel.addItem(self.web) left_panel.addItem(self.visual) left_panel.addItem(self.advanced) left_panel.addItem(self.about) left_panel.setMaximumWidth(100) # right panel self.right_panel = QStackedLayout() self.init_right_panel() # bottom bottom_layout = QHBoxLayout() ok_btn = QPushButton('Ok') ok_btn.clicked.connect(self.accept) cancel_btn = QPushButton('Cancel') cancel_btn.clicked.connect(self.close) info_lbl = QLabel() info_lbl.setText('<a href="https://github.com/Pewpews/happypanda">'+ 'Visit GitHub Repo</a> | Options marked with * requires application restart.') info_lbl.setTextFormat(Qt.RichText) info_lbl.setTextInteractionFlags(Qt.TextBrowserInteraction) info_lbl.setOpenExternalLinks(True) self.spacer = QWidget() self.spacer.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Preferred) bottom_layout.addWidget(info_lbl, 0, Qt.AlignLeft) bottom_layout.addWidget(self.spacer) bottom_layout.addWidget(ok_btn, 0, Qt.AlignRight) bottom_layout.addWidget(cancel_btn, 0, Qt.AlignRight) sub_layout.addWidget(left_panel) sub_layout.addLayout(self.right_panel) main_layout.addLayout(sub_layout) main_layout.addLayout(bottom_layout) self.restore_options()
def _add_new_trigger(self, tr_action, target, ta_action): item = QListWidgetItem() item.setSizeHint(QSize(200, 30)) widget = TriggerWidget(tr_action, target, ta_action, self.cue_dialog) self.triggersWidget.addItem(item) self.triggersWidget.setItemWidget(item, widget)
def loadList(self): self.__ob_list_main.clear() self.__ob_line_search.clear() for i in self.__socman.getDump(): item = QListWidgetItem() item.setText(i.getTitle()) item.setSizeHint(QSize(10, 30)) self.__ob_list_main.addItem(item)
def readSettings(self): self.inputTextList.clear() entries = settings.metricsWindowComboBoxItems() for entry in entries: item = QListWidgetItem(entry, self.inputTextList) item.setFlags(item.flags() | Qt.ItemIsEditable) if not len(entries): self.removeItemButton.setEnabled(False)
def build_list(self): """Builds listWidget""" self.listWidget.clear() for choice in sorted(self.choices, key=lambda choice: choice[1]): value, name = choice item = QListWidgetItem(name.replace('"', '')) item.setData(Qt.UserRole, value) self.listWidget.addItem(item)
def __init__(self, name, desc): if desc == "": display = name else: #display = "%s (%s)" % (desc, name) display = desc QListWidgetItem.__init__(self, display) self.name = name
def generate_hotkey_list(self): """Generate the hotkey list.""" for option in self.model.options('Hotkeys'): if not option.startswith(';'): item = QListWidgetItem() item.setText(option) item.setData(Qt.UserRole, self.model.get('Hotkeys', option)) self.ui.listWidget_hotkey.addItem(item)
def addCategory(self, title): item = QListWidgetItem(title) item.setBackground(QBrush(lightBlue())) item.setForeground(QBrush(Qt.darkBlue)) item.setFlags(Qt.ItemIsEnabled) f = item.font() f.setBold(True) item.setFont(f) self.list.addItem(item)
def _add_cue(self, cue, action): item = QListWidgetItem() item.setSizeHint(QSize(200, 30)) widget = CueItemWidget(cue, action, self.cue_dialog) self.cuesWidget.addItem(item) self.cuesWidget.setItemWidget(item, widget) self.cue_dialog.remove_cue(cue)
def add_list_widget_item(self): my_custom_widget = ItemListWidget() my_qlist_widget_item = QListWidgetItem() my_qlist_widget_item.setSizeHint(my_custom_widget.sizeHint()) self.listWidget.insertItem(0, my_qlist_widget_item) self.listWidget.setItemWidget(my_qlist_widget_item, my_custom_widget) return my_qlist_widget_item
def btn_add_class(self): if self.add_a: self.radioButton.setChecked(True) my_key = self.lineEdit_2.text() my_val = self.lineEdit_3.text() my_val = my_val.split(",") _translate = QtCore.QCoreApplication.translate if self.checkBox.isChecked(): if len(my_key) != 0: i = len(self.A_comboBox_list) self.item = QListWidgetItem(my_key, self.left_widget) # 左侧选项的添加 font = QtGui.QFont() font.setPointSize(15) self.item.setFont(font) self.item.setSizeHint(QSize(15, 25)) self.item.setTextAlignment(Qt.AlignCenter) # 居中显示 locals()['stack' + str(i)] = QListWidget() # 左侧选项列表 locals()['stack' + str(i)].setGeometry( QtCore.QRect(0, 0, 181, 360)) locals()['stack' + str(i)].setStyleSheet(self.list_style) for att_v in my_val: self.ritem = QListWidgetItem( att_v, locals()['stack' + str(i)]) # 左侧选项的添加 font = QtGui.QFont() font.setPointSize(15) self.ritem.setFont(font) self.ritem.setSizeHint(QSize(15, 25)) self.ritem.setTextAlignment(Qt.AlignCenter) # 居中显示 self.right_widget.addWidget(locals()['stack' + str(i)]) self.A_comboBox_list.append(locals()["stack" + str(i)]) locals()['stack' + str(i)].currentRowChanged.connect( self.row_change) self.A_dict[my_key] = my_val lines = [] with open("Attribute", encoding="utf-8-sig") as f: for line in f.readlines(): lines.append(line) lines.append('\n' + my_key + ":" + ",".join(my_val)) with open("Attribute", 'w', encoding="utf-8") as f: s = ''.join(lines) f.write(str(s)) self.comboBox_11.addItem("") self.comboBox_11.setItemText( len(self.A_dict.keys()) + len(self.O_dict.keys()) - 1, _translate("Form", my_key)) else: text = self.QTextEdit.toPlainText() if len(text) != 0: self.A_answer = eval(text.split('\n')[3]) self.O_answer = eval(text.split('\n')[1]) else: self.A_answer = {} self.O_answer = {} # print(A_an) self.A_answer[my_key] = my_val[0] self.QTextEdit.setPlainText( str("对象:\n") + str(self.O_answer) + "\n" + str("属性:\n") + str(self.A_answer) + "\n") if self.add_o: self.add_o = False self.radioButton.setChecked(True) my_key = self.lineEdit_2.text() my_val = self.lineEdit_3.text() my_val = my_val.split(",") _translate = QtCore.QCoreApplication.translate if self.checkBox.isChecked(): if len(my_key) != 0: i = len(self.O_comboBox_list) self.oitem = QListWidgetItem(my_key, self.oleft_widget) # 左侧选项的添加 font = QtGui.QFont() font.setPointSize(15) self.oitem.setFont(font) self.oitem.setSizeHint(QSize(15, 25)) self.oitem.setSizeHint(QSize(15, 20)) self.oitem.setTextAlignment(Qt.AlignCenter) # 居中显示 locals()['ostack' + str(i)] = QListWidget() # 左侧选项列表 locals()['ostack' + str(i)].setGeometry( QtCore.QRect(0, 0, 181, 360)) locals()['ostack' + str(i)].setStyleSheet(self.olist_style) for obj_v in my_val: self.oritem = QListWidgetItem( obj_v, locals()['ostack' + str(i)]) # 左侧选项的添加 font = QtGui.QFont() font.setPointSize(15) self.oritem.setFont(font) self.oritem.setSizeHint(QSize(15, 25)) self.oritem.setTextAlignment(Qt.AlignCenter) # 居中显示 self.oright_widget.addWidget(locals()['ostack' + str(i)]) self.O_comboBox_list.append(locals()["ostack" + str(i)]) locals()['ostack' + str(i)].currentRowChanged.connect( self.orow_change) self.O_dict[my_key] = my_val lines = [] with open("Object", encoding="utf-8-sig") as f: for line in f.readlines(): lines.append(line) lines.append('\n' + my_key + ":" + ",".join(my_val)) with open("Object", 'w', encoding="utf-8") as f: s = ''.join(lines) f.write(str(s)) self.comboBox_11.addItem("") self.comboBox_11.setItemText( len(self.A_dict.keys()) + len(self.O_dict.keys()) - 1, _translate("Form", my_key)) else: text = self.QTextEdit.toPlainText() if len(text) != 0: self.A_answer = eval(text.split('\n')[3]) self.O_answer = eval(text.split('\n')[1]) else: self.A_answer = {} self.O_answer = {} self.O_answer[my_key] = my_val[0] self.QTextEdit.setPlainText( str("对象:\n") + str(self.O_answer) + "\n" + str("属性:\n") + str(self.A_answer) + "\n") self.radio_flag = False self.checkBox.setChecked(False) self.lineEdit_2.setText("") self.lineEdit_3.setText("")
def initUI(self): newFont = QFont("Laksaman", 14) self.setFont(newFont) recipesByTag = {} recipeList = QListWidget(self) for recipe in database.RECIPES: for tag in recipe.tags: if tag not in recipesByTag: recipesByTag[tag] = [] recipesByTag[tag].append(recipe) for tag in sorted(recipesByTag.keys(), key=database.SORT_TAGS.index): recipeList.addItem(QListWidgetItem(tag)) for recipe in recipesByTag[tag]: item = RecipeItem(recipe) recipeList.addItem(item) recipeList.show() recipeList.itemActivated.connect(self.selectRecipe) self.calendar = RecipeCalendar(self.mealPlan.meals) recipeVBox = QVBoxLayout() recipeVBox.addWidget(self.calendar, 1) recipeVBox.addWidget(recipeList, 2) self.selectedRecipeList = QListWidget(self) self.selectedRecipeList.show() self.selectedRecipeList.itemActivated.connect(self.deselectRecipe) self.ingredientList = QListWidget(self) self.ingredientList.show() self.ingredientList.itemActivated.connect(self.toggleIngredient) listHBox = QHBoxLayout() listHBox.addLayout(recipeVBox) listHBox.addWidget(self.selectedRecipeList) listHBox.addWidget(self.ingredientList) quitButton = QPushButton("Quit") quitButton.clicked.connect(self.close) buttonHBox = QHBoxLayout() buttonHBox.addStretch(1) buttonHBox.addWidget(quitButton) self.text = QTextEdit() self.text.setReadOnly(True) textLayout = QVBoxLayout() textLayout.addWidget(self.text) tabs = QTabWidget() tabBuild = QWidget() tabView = QWidget() tabBuild.setLayout(listHBox) tabView.setLayout(textLayout) tabs.addTab(tabBuild, "Build") tabs.addTab(tabView, "View") layout = QVBoxLayout() layout.addWidget(tabs) layout.addLayout(buttonHBox) self.setLayout(layout) self.setWindowTitle('Webb Family Recipes') self.showMaximized()
class CarrotHypothesis(): def __init__(self, tf, height, radius, name, color, im_server, listwidget, remove_callback): self.tf = tf.copy() self.height = height self.radius = radius self.color = color self.name = name # Users provide feedback to refine the mesh # position + configuration through RViz # InteractiveMarkers self.im_marker = ros_im.InteractiveMarker() self.im_marker.header.frame_id = "base" self.im_marker.name = name self.im_marker.description = "Hypothesized Carrot" self.im_marker.scale = 0.15 self.im_marker.pose = ros_utils.ROSPoseMsgFromPose( spartanUtils.dict_from_homogenous_transform(tf)) # Visualize current carrot mesh self.mesh_control = None self._regenerateMesh() # Add some control widgets self._add6DofControls() self.im_server = im_server self.im_server.insert(self.im_marker, self._processImMarkerFeedbackCb) self.im_server.applyChanges() # Make control interface + add to list widget self.control_widget = CarrotHypothesisWidget(name=name, radius=radius, height=height, owner_hypothesis=self) self.control_widget_listwidgetitem = QListWidgetItem(listwidget) self.control_widget_listwidgetitem.setSizeHint( self.control_widget.sizeHint()) self.listwidget = listwidget self.listwidget.addItem(self.control_widget_listwidgetitem) self.listwidget.setItemWidget(self.control_widget_listwidgetitem, self.control_widget) self.remove_callback = remove_callback def populateCarrotConfigurationMessage(self, msg): msg.radius = self.radius msg.height = self.height msg.pose = self.im_marker.pose return msg def _handleRemove(self): self.im_server.erase(self.name) self.im_server.applyChanges() self.listwidget.takeItem( self.listwidget.row(self.control_widget_listwidgetitem)) self.remove_callback(self) def _handleEditClicked(self): in_edit_mode = self.control_widget.getEditState() if in_edit_mode: # Add the 6DOF controls self._add6DofControls() else: for control in self.axis_controls: self.im_marker.controls.remove(control) self.axis_controls = [] self._forceIntMarkerUpdate() def _forceIntMarkerUpdate(self): # Force update of the mesh update = ros_im.UpdateContext() update.update_type = ros_im.UpdateContext.FULL_UPDATE update.int_marker = self.im_marker self.im_server.pending_updates[self.name] = update self.im_server.applyChanges() def _handleParameterChangeCb(self): self.height = self.control_widget.getHeight() self.radius = self.control_widget.getRadius() self._regenerateMesh() self._forceIntMarkerUpdate() def _processImMarkerFeedbackCb(self, feedback): if feedback.marker_name == self.im_marker.name: if feedback.event_type == InteractiveMarkerFeedback.POSE_UPDATE: self.im_marker.pose = feedback.pose def _add6DofControls(self): self.axis_controls = [] # Insert 6DOF control control = InteractiveMarkerControl() control.orientation.w = 1 control.orientation.x = 1 control.orientation.y = 0 control.orientation.z = 0 control.name = "rotate_x" control.interaction_mode = InteractiveMarkerControl.ROTATE_AXIS self.im_marker.controls.append(control) self.axis_controls.append(control) control = InteractiveMarkerControl() control.orientation.w = 1 control.orientation.x = 1 control.orientation.y = 0 control.orientation.z = 0 control.name = "move_x" control.interaction_mode = InteractiveMarkerControl.MOVE_AXIS self.im_marker.controls.append(control) self.axis_controls.append(control) control = InteractiveMarkerControl() control.orientation.w = 1 control.orientation.x = 0 control.orientation.y = 1 control.orientation.z = 0 control.name = "rotate_z" control.interaction_mode = InteractiveMarkerControl.ROTATE_AXIS self.im_marker.controls.append(control) self.axis_controls.append(control) control = InteractiveMarkerControl() control.orientation.w = 1 control.orientation.x = 0 control.orientation.y = 1 control.orientation.z = 0 control.name = "move_z" control.interaction_mode = InteractiveMarkerControl.MOVE_AXIS self.im_marker.controls.append(control) self.axis_controls.append(control) control = InteractiveMarkerControl() control.orientation.w = 1 control.orientation.x = 0 control.orientation.y = 0 control.orientation.z = 1 control.name = "rotate_y" control.interaction_mode = InteractiveMarkerControl.ROTATE_AXIS self.im_marker.controls.append(control) self.axis_controls.append(control) control = InteractiveMarkerControl() control.orientation.w = 1 control.orientation.x = 0 control.orientation.y = 0 control.orientation.z = 1 control.name = "move_y" control.interaction_mode = InteractiveMarkerControl.MOVE_AXIS self.im_marker.controls.append(control) self.axis_controls.append(control) def _regenerateMesh(self): self.mesh = mesh_creation.create_cut_cylinder(radius=self.radius, height=self.height, cutting_planes=[ ([0., 0., 0.], [1., 0., 0.]) ], sections=10) mesh_marker = Marker() mesh_marker.type = Marker.TRIANGLE_LIST mesh_marker.color.r = self.color[0] mesh_marker.color.g = self.color[1] mesh_marker.color.b = self.color[2] if len(self.color) > 3: mesh_marker.color.a = self.color[3] else: mesh_marker.color.a = 1. tris = self.mesh.faces.ravel() verts = self.mesh.vertices[tris, :] mesh_marker.points = ros_utils.arrayToPointMsgs(verts.T) mesh_marker.colors = [ std_msgs.msg.ColorRGBA(self.color[0], self.color[1], self.color[2], self.color[3]) ] * tris.shape[0] if self.mesh_control is not None: self.im_marker.controls.remove(self.mesh_control) self.mesh_control = InteractiveMarkerControl() self.mesh_control.always_visible = True self.mesh_control.markers.append(mesh_marker) self.im_marker.controls.append(self.mesh_control)
def init_data(self): self.navigation.setIconSize(QSize(18, 18)) font = QFont() font.setPixelSize(13) local_item = QListWidgetItem(self.navigation) local_item.setData(Qt.UserRole, self.music_list_service.get_local_music()) local_item.setIcon(QIcon("./resource/image/歌单0.png")) local_item.setText("本地音乐") local_item.setFont(font) self.navigation.addItem(local_item) # item1 = QListWidgetItem() # item1.setText("创建的歌单") # item1.setFlags(Qt.NoItemFlags) # self.navigation.addItem(item1) music_list_icon = QIcon("./resource/image/歌单1.png") item = QListWidgetItem() item.setIcon(music_list_icon) item.setFont(font) item.setText('菜单1') item.setData(Qt.UserRole, 1) self.navigation.addItem(item) item = QListWidgetItem() item.setIcon(music_list_icon) item.setFont(font) item.setText('菜单2') item.setData(Qt.UserRole, 2) self.navigation.addItem(item) # mls = list(filter(lambda ml: ml.id != MusicList.DEFAULT_ID, self.music_list_service.list_(MusicList()))) # music_list_icon = QIcon("./resource/image/歌单1.png") # for music_list in mls: # item = QListWidgetItem() # item.setIcon(music_list_icon) # item.setFont(font) # item.setText(music_list.name) # item.setData(Qt.UserRole, music_list) # self.navigation.addItem(item) # 启动时默认选中第一个歌单 self.navigation.setCurrentRow(0) cur_id = self.navigation.currentItem().data(Qt.UserRole).id self.update_music_list(cur_id) self.stacked_view.setCurrentWidget(self.music_list_detail) self.musics_table.setColumnCount(5)
def __loadScripts(self): """ Private method to load all the available scripts. """ for script in self.__manager.allScripts(): itm = QListWidgetItem( UI.PixmapCache.getIcon("greaseMonkeyScript.png"), script.name(), self.scriptsList) itm.setData(GreaseMonkeyConfigurationDialog.ScriptVersionRole, script.version()) itm.setData(GreaseMonkeyConfigurationDialog.ScriptDescriptionRole, script.description()) itm.setFlags(itm.flags() | Qt.ItemIsUserCheckable) if script.isEnabled(): itm.setCheckState(Qt.Checked) else: itm.setCheckState(Qt.Unchecked) itm.setData(GreaseMonkeyConfigurationDialog.ScriptRole, script) self.scriptsList.addItem(itm) self.scriptsList.sortItems() itemMoved = True while itemMoved: itemMoved = False for row in range(self.scriptsList.count()): topItem = self.scriptsList.item(row) bottomItem = self.scriptsList.item(row + 1) if topItem is None or bottomItem is None: continue if topItem.checkState() == Qt.Unchecked and \ bottomItem.checkState == Qt.Checked: itm = self.scriptsList.takeItem(row + 1) self.scriptsList.insertItem(row, itm) itemMoved = True
def __init__(self, user_id, *args, **kwargs): super(UserCenter, self).__init__(*args, **kwargs) self.user_id = user_id self.set_new_avatar = False layout = QVBoxLayout() # 总布局 layout.setContentsMargins(QMargins(100, 10, 100, 10)) middle_layout = QHBoxLayout() # 中间布局 # 左侧显示头像和菜单 left_layout = QVBoxLayout() # 左侧布局 self.avatar = CAvatar(size=QSize(180, 180)) self.avatar.clicked.connect(self.modify_user_avatar) left_layout.addWidget(self.avatar, alignment=Qt.AlignCenter) machine_code = settings.app_dawn.value('machine') code_label = QLineEdit(machine_code, parent=self) code_label.setMaximumWidth(250) code_label.setCursor(QCursor(Qt.ArrowCursor)) code_label.setAlignment(Qt.AlignCenter) code_label.setFocusPolicy(Qt.NoFocus) left_layout.addWidget(code_label) # 菜单 self.left_list = QListWidget(clicked=self.menu_clicked, parent=self) self.left_list.setMaximumWidth(250) item1 = QListWidgetItem('基本资料', self.left_list) item2 = QListWidgetItem('修改密码', self.left_list) item1.setTextAlignment(Qt.AlignCenter) item2.setTextAlignment(Qt.AlignCenter) self.left_list.addItem(item1) self.left_list.addItem(item2) left_layout.addWidget(self.left_list) middle_layout.addLayout(left_layout) # 右侧显示具体窗口 self.right_win = LoadedPage(self) self.right_win.remove_borders() middle_layout.addWidget(self.right_win) layout.addLayout(middle_layout) self.setLayout(layout) code_label.setObjectName('machineCode') self.left_list.setObjectName('leftList') self.setStyleSheet(""" #machineCode{ border: none; background:rgb(240,240,240); } #leftList{ outline:none; border:none; background-color: rgb(240,240,240); } #leftList::item{ height:25px; } #leftList::item:selected{ color:rgb(100,180,230); background-color:rgb(240,240,240); } #leftList::item:hover{ color:rgb(150,180,230); background-color:rgb(240,240,240); } """) self.left_list.setCurrentRow(0) self.menu_clicked()
def listwidget_init(self): self.beam_list = beam_dict.list_beams() for i in range(len(self.beam_list)): QListWidgetItem(self.beam_list[i], self.commission_text) self.commission_text.itemSelectionChanged.connect(self.beam_selected)
def makeItem(self, data): taskItem = taskItemImpl() taskItem.setInfo(data) ListItem = QListWidgetItem() ListItem.setSizeHint(taskItem.size()) return taskItem, ListItem
def add_pom(self): new_item = '{} | {} | {}'.format(self.sb_number_of_poms.value(), self.cb_project.currentText(), self.cb_task.currentText()) QListWidgetItem(new_item, self.listWidget)
def on_listPkt_currentItemChanged(self, item: QtWidgets.QListWidgetItem, item_pre: QtWidgets.QListWidgetItem): if item: p = (self.packetList[item.text()]) self.edtInfo.setText("Packet Size:%d\n%s" % (len(p), p.show(dump=True)))
def run(self): contDict_file = os.path.exists(par.full_dir + '/system/controlDict') if os.path.exists(contDict_file) == True: if msh_t == 'blockMesh': mesh_name_txt_val_th_a = mesh_name_txt_val_th_new + '_blockMesh' elif msh_t == 'snappyHexMesh': mesh_name_txt_val_th_a = mesh_name_txt_val_th_new + '_snappyHexMesh' #1 solv_bash_file = open( prj_path_val_th + '/' + mesh_name_txt_val_th_a + '/' + 'solv_script', 'w') solv_bash_file.write('#!/bin/sh' + '\n' + '. /opt/openfoam6/etc/bashrc' + '\n' + 'setFields' + '\n' + 'exit') solv_bash_file.close() solv_out_file = open( prj_path_val_th + '/' + mesh_name_txt_val_th_a + '/' + 'solv_script.log', "w") solv_run_subprocess_a = subprocess.Popen([ "bash " + prj_path_val_th + '/' + mesh_name_txt_val_th_a + "/" + "solv_script" ], cwd=pp_dir_th, shell=True, stdout=solv_out_file, stderr=solv_out_file) solv_out_file.close() self.solv_sig_start.emit(prj_path_val_th, mesh_name_txt_val_th_a, par, int_lng, msh_t) #2 solv_bash_file = open( prj_path_val_th + '/' + mesh_name_txt_val_th_a + '/' + 'solv_script', 'w') solv_bash_file.write('#!/bin/sh' + '\n' + '. /opt/openfoam6/etc/bashrc' + '\n' + 'decomposePar' + '\n' + 'exit') solv_bash_file.close() solv_out_file = open( prj_path_val_th + '/' + mesh_name_txt_val_th_a + '/' + 'solv_script.log', "w") solv_run_subprocess_b = subprocess.Popen([ "bash " + prj_path_val_th + '/' + mesh_name_txt_val_th_a + "/" + "solv_script" ], cwd=pp_dir_th, shell=True, stdout=solv_out_file, stderr=solv_out_file) solv_out_file.close() #3 solv_bash_file = open( prj_path_val_th + '/' + mesh_name_txt_val_th_a + '/' + 'solv_script', 'w') solv_bash_file.write('#!/bin/sh' + '\n' + '. /opt/openfoam6/etc/bashrc' + '\n' + par.application + '\n' + 'exit') solv_bash_file.close() solv_out_file = open( prj_path_val_th + '/' + mesh_name_txt_val_th_a + '/' + 'solv_script.log', "w") solv_run_subprocess = subprocess.Popen([ "bash " + prj_path_val_th + '/' + mesh_name_txt_val_th_a + "/" + "solv_script" ], cwd=pp_dir_th, shell=True, stdout=solv_out_file, stderr=solv_out_file) solv_out_file.close() while solv_run_subprocess.poll() is None: pass return_code_1 = solv_run_subprocess.returncode if return_code_1 == 0: solv_bash_file = open( prj_path_val_th + '/' + mesh_name_txt_val_th_a + '/' + 'solv_script', 'w') solv_bash_file.write('#!/bin/sh' + '\n' + '. /opt/openfoam6/etc/bashrc' + '\n' + 'reconstructPar' + '\n' + 'exit') solv_bash_file.close() solv_out_file = open( prj_path_val_th + '/' + mesh_name_txt_val_th_a + '/' + 'solv_script.log', "w") solv_run_subprocess = subprocess.Popen([ "bash " + prj_path_val_th + '/' + mesh_name_txt_val_th_a + "/" + "solv_script" ], cwd=pp_dir_th, shell=True, stdout=solv_out_file, stderr=solv_out_file) solv_out_file.close() while solv_run_subprocess.poll() is None: pass return_code = solv_run_subprocess.returncode self.solv_sig_fin.emit(return_code, prj_path_val_th, mesh_name_txt_val_th_a, par, int_lng, msh_t) else: self.solv_sig_fin.emit(return_code_1, prj_path_val_th, mesh_name_txt_val_th_a, par, int_lng, msh_t) else: if int_lng == 'Russian': msg_lbl = QLabel( '<span style="color:blue">' + "Сначала выполните сохранение файла controlDict" + '</span>') elif int_lng == 'English': msg_lbl = QLabel('<span style="color:blue">' + "First save the controlDict file" + '</span>') par.listWidget.clear() par.item = QListWidgetItem() par.listWidget.addItem(par.item) par.listWidget.setItemWidget(par.item, msg_lbl)
def input_recipe(self, item: QListWidgetItem) -> None: """Input the double clicked recipe in the search field.""" self.recipe_of_choice.setText(item.text())
def insertCity(self, i): item = QListWidgetItem() item.setText(i.text()) item.setData(Qt.UserRole, i.data(Qt.UserRole)) self.ui.citiesList.addItem(item)
def createIcons(self): configButton = QListWidgetItem(self.contentsWidget) configButton.setIcon(QIcon(':/images/config.png')) configButton.setText("Configuration") configButton.setTextAlignment(Qt.AlignHCenter) configButton.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEnabled) updateButton = QListWidgetItem(self.contentsWidget) updateButton.setIcon(QIcon(':/images/update.png')) updateButton.setText("Update") updateButton.setTextAlignment(Qt.AlignHCenter) updateButton.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEnabled) queryButton = QListWidgetItem(self.contentsWidget) queryButton.setIcon(QIcon(':/images/query.png')) queryButton.setText("Query") queryButton.setTextAlignment(Qt.AlignHCenter) queryButton.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEnabled) self.contentsWidget.currentItemChanged.connect(self.changePage)
def __init__(self, parent=None): super(UpdatePage, self).__init__(parent) updateGroup = QGroupBox("Package selection") systemCheckBox = QCheckBox("Update system") appsCheckBox = QCheckBox("Update applications") docsCheckBox = QCheckBox("Update documentation") packageGroup = QGroupBox("Existing packages") packageList = QListWidget() qtItem = QListWidgetItem(packageList) qtItem.setText("Qt") qsaItem = QListWidgetItem(packageList) qsaItem.setText("QSA") teamBuilderItem = QListWidgetItem(packageList) teamBuilderItem.setText("Teambuilder") startUpdateButton = QPushButton("Start update") updateLayout = QVBoxLayout() updateLayout.addWidget(systemCheckBox) updateLayout.addWidget(appsCheckBox) updateLayout.addWidget(docsCheckBox) updateGroup.setLayout(updateLayout) packageLayout = QVBoxLayout() packageLayout.addWidget(packageList) packageGroup.setLayout(packageLayout) mainLayout = QVBoxLayout() mainLayout.addWidget(updateGroup) mainLayout.addWidget(packageGroup) mainLayout.addSpacing(12) mainLayout.addWidget(startUpdateButton) mainLayout.addStretch(1) self.setLayout(mainLayout)
def _on_current_item_changed(self, item: QListWidgetItem, last_item: QListWidgetItem) -> None: account_id = item.data(Qt.UserRole) # This should update the internal tracking, and also the active wallet account. if self._update_active_account(account_id): account = self._main_window._wallet.get_account(account_id) self._update_window_account(account)
def buildCityItem(self, city): item = QListWidgetItem() item.setText('<b>%s</b> (%s)' % (city.name, city.backend)) item.setData(Qt.UserRole, city) return item
def listprint(self, head, msg): print(self.sctl.handleError()) brush = QBrush(QColor(255, 213, 214)) brush.setStyle(Qt.SolidPattern) item1 = QListWidgetItem() item1.setBackground(brush) item1.setText( QCoreApplication.translate("Ui_MainWindow", '{}:'.format(head))) brush = QBrush(QColor(205, 232, 255)) brush.setStyle(Qt.SolidPattern) item2 = QListWidgetItem() item2.setBackground(brush) item2.setText( QCoreApplication.translate("Ui_MainWindow", ' {}'.format(msg))) self.listWidget_danmaku.addItem(item1) self.listWidget_danmaku.addItem(item2) self.listWidget_danmaku.addItem('') item2.setHidden(False) item1.setHidden(False) for i in range(2): self.listWidget_danmaku.scrollToBottom() time.sleep(0.1)
def updateUi(self, name): E = exporter.getExporterByName(name) self.currentExporter = E if not E: self.stack.setEnabled(False) return self.stack.setEnabled(True) # Updates name and description self.lblExporterName.setText(E.name) self.lblExporterDescription.setText(E.description) # Updates formats self.lstExportTo.clear() for f in E.exportTo: item = QListWidgetItem(QIcon.fromTheme(f.icon), f.name) self.lstExportTo.addItem(item) self.grpExportTo.layout().setStretch(0, 4) self.grpExportTo.layout().setStretch(1, 6) self.lstExportTo.setCurrentRow(0) # Updates path & version self.grpPath.setVisible( E.name != "Manuskript") # We hide if exporter is manuskript # Installed if E.isValid() == 2: self.lblStatus.setText(self.tr("Installed")) self.lblStatus.setStyleSheet("color: darkGreen;") self.lblHelpText.setVisible(False) self.lblVersion.setVisible(True) self.lblVersionName.setVisible(True) elif E.isValid() == 1: self.lblStatus.setText(self.tr("Custom")) self.lblStatus.setStyleSheet("color: darkOrange;") self.lblHelpText.setVisible(False) self.lblVersion.setVisible(True) self.lblVersionName.setVisible(True) else: self.lblStatus.setText(self.tr("Not found")) self.lblStatus.setStyleSheet("color: red;") self.lblHelpText.setVisible(True) self.lblHelpText.setText( self.tr("{} not found. Install it, or set path manually."). format(name)) self.lblVersion.setVisible(False) self.lblVersionName.setVisible(False) # Version self.lblVersion.setText(E.version()) # Path if E.path(): self.txtPath.setText(E.path()) else: self.txtPath.setText(E.customPath)
def on_btnSave_clicked(self): # создаем таблицу D if 'D' not in self.par.con.tables(): query = QtSql.QSqlQuery() query.exec("CREATE TABLE D(param, value)") dimensions_perem = [self.d_1.text(), self.d_2.text(), self.d_3.text(), self.d_4.text(), self.d_5.text(), self.d_6.text(), self.d_7.text()] dimensions_str = ' '.join(dimensions_perem) internalField_perem = [self.internalField.currentText(), self.x.text(), self.y.text(), self.z.text()] internalField_str = ', '.join(internalField_perem) query = QtSql.QSqlQuery() query.exec("INSERT INTO D(param, value) VALUES ('%s','%s')" % ('dimensions', dimensions_str)) query.exec("INSERT INTO D(param, value) VALUES ('%s','%s')" % ('internalField', internalField_str)) # записываем файл D if os.path.exists(self.full_dir + '/0/D'): os.remove(self.full_dir + '/0/D') shutil.copyfile("./matches/Shablon/0/D", self.full_dir + '/0/D') D = open(self.full_dir + '/0/D', 'a') ###dimensions### dimensions_bl = '\n' + 'dimensions ' + '[' + dimensions_str + ']' + ';' + '\n' ###internalField### internalField_bl = '\n' + 'internalField ' + self.internalField.currentText() + ' ' + '(' + self.x.text() + ' ' + self.y.text() + ' ' + self.z.text() + ')' + ';' + '\n' ###boundaryField### boundaryField_bl_start = '\n' + 'boundaryField' + '\n' + '{' + '\n' D.write(dimensions_bl + internalField_bl + boundaryField_bl_start) i = 0 for el_p in self.patches_lst: if self.type_list_main[i].currentText() == "symmetryPlane" or self.type_list_main[i].currentText() == "empty": type_txt = self.main_grid_list[i].itemAtPosition(0, 1).widget().currentText() query.exec("INSERT INTO D(param, value) VALUES ('%s','%s')" % (el_p, type_txt)) type_bl = ' ' + el_p + '\n' + ' ' + '{' + '\n' + ' ' + 'type' + ' ' + type_txt + ';' + '\n' + ' ' + '}' + '\n' D.write(type_bl) elif self.type_list_main[i].currentText() == "tractionDisplacement": type_txt = self.main_grid_list[i].itemAtPosition(0, 1).widget().currentText() traction_txt = self.main_grid_list[i].itemAtPosition(1, 1).widget().currentText() x_1_txt = self.main_grid_list[i].itemAtPosition(1, 2).widget().text() y_1_txt = self.main_grid_list[i].itemAtPosition(1, 3).widget().text() z_1_txt = self.main_grid_list[i].itemAtPosition(1, 4).widget().text() pressure_txt = self.main_grid_list[i].itemAtPosition(2, 1).widget().currentText() koord_txt = self.main_grid_list[i].itemAtPosition(2, 2).widget().text() value_txt = self.main_grid_list[i].itemAtPosition(3, 1).widget().currentText() x_2_txt = self.main_grid_list[i].itemAtPosition(3, 2).widget().text() y_2_txt = self.main_grid_list[i].itemAtPosition(3, 3).widget().text() z_2_txt = self.main_grid_list[i].itemAtPosition(3, 4).widget().text() complex_list = [type_txt, traction_txt, x_1_txt, y_1_txt, z_1_txt, pressure_txt, koord_txt, value_txt, x_2_txt, y_2_txt, z_2_txt] complex_str = ', '.join(complex_list) query.exec("INSERT INTO D(param, value) VALUES ('%s','%s')" % (el_p, complex_str)) complex_bl = ' ' + el_p + '\n' + ' ' + '{' + '\n' + \ ' ' + 'type' + ' ' + type_txt + ';' + '\n' + \ ' ' + 'traction' + ' ' + traction_txt + ' ' + '(' + x_1_txt + ' ' + y_1_txt + ' ' + z_1_txt + ')' + ';' + '\n' + \ ' ' + 'pressure' + ' ' + pressure_txt + ' ' + koord_txt + ';' + '\n' + \ ' ' + 'value' + ' ' + value_txt + ' ' + '(' + x_2_txt + ' ' + y_2_txt + ' ' + z_2_txt + ')' + ';' + '\n' + \ ' ' + '}' + '\n' D.write(complex_bl) i = i + 1 boundaryField_bl_start = '}' + '\n\n' D.write(boundaryField_bl_start) close_str = '// ************************************************************************* //' D.write(close_str) D.close() if 'D' in self.par.con.tables(): dimensions_perem = [self.d_1.text(), self.d_2.text(), self.d_3.text(), self.d_4.text(), self.d_5.text(), self.d_6.text(), self.d_7.text()] dimensions_str = ' '.join(dimensions_perem) internalField_perem = [self.internalField.currentText(), self.x.text(), self.y.text(), self.z.text()] internalField_str = ', '.join(internalField_perem) query = QtSql.QSqlQuery() query.exec("REPLACE INTO D(param, value) VALUES ('%s','%s')" % ('dimensions', dimensions_str)) query.exec("REPLACE INTO D(param, value) VALUES ('%s','%s')" % ('internalField', internalField_str)) # записываем файл D if os.path.exists(self.full_dir + '/0/D'): os.remove(self.full_dir + '/0/D') shutil.copyfile("./matches/Shablon/0/D", self.full_dir + '/0/D') D = open(self.full_dir + '/0/D', 'a') ###dimensions### dimensions_bl = '\n' + 'dimensions ' + '[' + dimensions_str + ']' + ';' + '\n' ###internalField### internalField_bl = '\n' + 'internalField ' + self.internalField.currentText() + ' ' + '(' + self.x.text() + ' ' + self.y.text() + ' ' + self.z.text() + ')' + ';' + '\n' ###boundaryField### boundaryField_bl_start = '\n' + 'boundaryField' + '\n' + '{' + '\n' D.write(dimensions_bl + internalField_bl + boundaryField_bl_start) i = 0 for el_p in self.patches_lst: if self.type_list_main[i].currentText() == "symmetryPlane" or self.type_list_main[i].currentText() == "empty": type_txt = self.main_grid_list[i].itemAtPosition(0, 1).widget().currentText() query.exec("REPLACE INTO D(param, value) VALUES ('%s','%s')" % (el_p, type_txt)) type_bl = ' ' + el_p + '\n' + ' ' + '{' + '\n' + ' ' + 'type' + ' ' + type_txt + ';' + '\n' + ' ' + '}' + '\n' D.write(type_bl) elif self.type_list_main[i].currentText() == "tractionDisplacement": type_txt = self.main_grid_list[i].itemAtPosition(0, 1).widget().currentText() traction_txt = self.main_grid_list[i].itemAtPosition(1, 1).widget().currentText() x_1_txt = self.main_grid_list[i].itemAtPosition(1, 2).widget().text() y_1_txt = self.main_grid_list[i].itemAtPosition(1, 3).widget().text() z_1_txt = self.main_grid_list[i].itemAtPosition(1, 4).widget().text() pressure_txt = self.main_grid_list[i].itemAtPosition(2, 1).widget().currentText() koord_txt = self.main_grid_list[i].itemAtPosition(2, 2).widget().text() value_txt = self.main_grid_list[i].itemAtPosition(3, 1).widget().currentText() x_2_txt = self.main_grid_list[i].itemAtPosition(3, 2).widget().text() y_2_txt = self.main_grid_list[i].itemAtPosition(3, 3).widget().text() z_2_txt = self.main_grid_list[i].itemAtPosition(3, 4).widget().text() complex_list = [type_txt, traction_txt, x_1_txt, y_1_txt, z_1_txt, pressure_txt, koord_txt, value_txt, x_2_txt, y_2_txt, z_2_txt] complex_str = ', '.join(complex_list) query.exec("REPLACE INTO D(param, value) VALUES ('%s','%s')" % (el_p, complex_str)) complex_bl = ' ' + el_p + '\n' + ' ' + '{' + '\n' + \ ' ' + 'type' + ' ' + type_txt + ';' + '\n' + \ ' ' + 'traction' + ' ' + traction_txt + ' ' + '(' + x_1_txt + ' ' + y_1_txt + ' ' + z_1_txt + ')' + ';' + '\n' + \ ' ' + 'pressure' + ' ' + pressure_txt + ' ' + koord_txt + ';' + '\n' + \ ' ' + 'value' + ' ' + value_txt + ' ' + '(' + x_2_txt + ' ' + y_2_txt + ' ' + z_2_txt + ')' + ';' + '\n' + \ ' ' + '}' + '\n' D.write(complex_bl) i = i + 1 boundaryField_bl_start = '}' + '\n\n' D.write(boundaryField_bl_start) close_str = '// ************************************************************************* //' D.write(close_str) D.close() self.par.cdw.setWidget(self.par.outf_scroll) outf = open(self.full_dir + '/0/D') if self.interface_lng_val == 'Russian': msg_lbl = QLabel( '<span style="color:green">Файл D сохранен</span>') elif self.interface_lng_val == 'English': msg_lbl = QLabel( '<span style="color:green">The D file was saved</span>') self.par.listWidget.clear() self.par.item = QListWidgetItem() self.par.listWidget.addItem(self.par.item) self.par.listWidget.setItemWidget(self.par.item, msg_lbl) data = outf.read() if self.interface_lng_val == 'Russian': self.par.outf_lbl.setText("Файл " + "<font color='peru'>" + 'D' + "</font>") elif self.interface_lng_val == 'English': self.par.outf_lbl.setText("<font color='peru'>" + 'D' + "</font>" + " file") self.par.outf_edit.setText(data) self.par.cdw.setTitleBarWidget(self.par.cdw_frame) outf.close()
def createItem(self): return QListWidgetItem()
def add_widget_to_list(widget_list, object): list_item = QListWidgetItem(widget_list) list_item.setSizeHint(object.sizeHint()) widget_list.addItem(list_item) widget_list.setItemWidget(list_item, object)
def append_event_item(self, event_item): item = EventWidget(self, event_item) list_item = QListWidgetItem(self) list_item.setSizeHint(item.sizeHint()) self.setItemWidget(list_item, item)
def deleteFile(self, item: QtWidgets.QListWidgetItem): del self.file2path[item.text()] self.takeItem(self.row(item))
class Ui_Form(object): def setupUi(self, Form): self.form = Form self.O_answer = {} self.A_answer = {} self.file_list = os.listdir("Images") with open("count") as f: self.num = int(f.read()) self.add_a = True self.add_o = False self.A_extra = {} self.O_extra = {} f = open('Attribute', encoding='utf-8-sig') self.A_dict = {} for line in f.readlines(): temp = line[:-1].split(':') self.A_dict[temp[0]] = temp[1].split(',') print(self.A_dict) f.close() f = open('Object', encoding='utf-8-sig') self.O_dict = {} for line in f.readlines(): temp = line[:-1].split(':') self.O_dict[temp[0]] = temp[1].split(',') f.close() print(self.O_dict) Form.setObjectName("Form") Form.resize(1179, 803) self.label_16 = QtWidgets.QLabel(Form) self.label_16.setGeometry(QtCore.QRect(30, 40, 441, 331)) pixmap = QPixmap("./Images/" + self.file_list[self.num]) self.label_16.setPixmap(pixmap) self.label_16.setScaledContents(True) self.label_17 = QtWidgets.QLabel(Form) self.label_17.setGeometry(QtCore.QRect(610, 720, 111, 31)) pixmap = QPixmap("logo_iair.png") self.label_17.setPixmap(pixmap) self.label_17.setScaledContents(True) self.label_18 = QtWidgets.QLabel(Form) self.label_18.setGeometry(QtCore.QRect(400, 720, 201, 31)) pixmap = QPixmap("xjtu_logo.png") self.label_18.setPixmap(pixmap) self.label_18.setScaledContents(True) self.groupBox = QtWidgets.QGroupBox(Form) self.groupBox.setGeometry(QtCore.QRect(490, 10, 351, 411)) font = QtGui.QFont() font.setPointSize(18) self.groupBox.setFont(font) self.groupBox.setObjectName("groupBox") self.A_comboBox_list = [] self.A_label_list = [] with open('QListWidgetQSS.qss', 'r') as f: # 导入QListWidget的qss样式 self.list_style = f.read() font = QtGui.QFont() font.setPointSize(10) self.left_widget = QListWidget(self.groupBox) # 左侧选项列表 self.left_widget.setGeometry(QtCore.QRect(40, 40, 181, 360)) self.left_widget.setStyleSheet(self.list_style) self.right_widget = QStackedWidget(self.groupBox) self.right_widget.setGeometry(QtCore.QRect(190, 40, 181, 360)) with open('oQListWigetQSS.qss', 'r') as f: # 导入QListWidget的qss样式 self.olist_style = f.read() self.groupBox_5 = QtWidgets.QGroupBox(Form) self.groupBox_5.setGeometry(QtCore.QRect(850, 10, 291, 361)) font = QtGui.QFont() font.setPointSize(10) self.oleft_widget = QListWidget(self.groupBox_5) # 左侧选项列表 self.oleft_widget.setGeometry(QtCore.QRect(10, 40, 181, 300)) self.oleft_widget.setStyleSheet(self.olist_style) self.oright_widget = QStackedWidget(self.groupBox_5) self.oright_widget.setGeometry(QtCore.QRect(150, 40, 181, 300)) font = QtGui.QFont() font.setPointSize(18) self.groupBox_5.setFont(font) self.groupBox_5.setAutoFillBackground(False) self.groupBox_5.setObjectName("groupBox_5") self.O_comboBox_list = [] self.O_label_list = [] self.pushButton = QtWidgets.QPushButton(Form) font = QtGui.QFont() font.setPointSize(18) self.pushButton.setFont(font) self.pushButton.setGeometry(QtCore.QRect(570, 610, 551, 61)) self.pushButton.clicked.connect(self.btn_save) self.pushButton.setObjectName("pushButton") self.pushButton_2 = QtWidgets.QPushButton(Form) font = QtGui.QFont() font.setPointSize(18) self.pushButton_2.setFont(font) self.pushButton_2.setGeometry(QtCore.QRect(570, 530, 551, 61)) self.pushButton_2.clicked.connect(self.btn_add_class) self.pushButton_2.setObjectName("pushButton_2") self.comboBox_11 = QtWidgets.QComboBox(Form) self.comboBox_11.setGeometry(QtCore.QRect(40, 440, 241, 31)) font = QtGui.QFont() font.setPointSize(18) self.comboBox_11.setFont(font) self.comboBox_11.setEditable(False) self.comboBox_11.setObjectName("comboBox_11") for i, key in enumerate(self.A_dict.keys()): self.comboBox_11.addItem("") for i, key in enumerate(self.O_dict.keys()): self.comboBox_11.addItem("") self.lineEdit_2 = QtWidgets.QLineEdit(Form) self.lineEdit_2.setGeometry(QtCore.QRect(930, 460, 201, 21)) self.lineEdit_2.setObjectName("lineEdit_2") self.pushButton_3 = QtWidgets.QPushButton(Form) font = QtGui.QFont() font.setPointSize(18) self.pushButton_3.setFont(font) self.pushButton_3.setGeometry(QtCore.QRect(40, 530, 461, 61)) self.pushButton_3.clicked.connect(self.btn_add_val) self.pushButton_3.setObjectName("pushButton_3") self.radioButton = QtWidgets.QRadioButton(Form) self.radioButton.setGeometry(QtCore.QRect(580, 470, 100, 20)) self.radioButton.setChecked(True) self.radioButton.toggled.connect(self.radio_msg) self.radioButton.setObjectName("radioButton") self.radioButton_2 = QtWidgets.QRadioButton(Form) self.radioButton_2.setGeometry(QtCore.QRect(670, 470, 100, 20)) self.radioButton_2.toggled.connect(self.radio_msg) self.radioButton_2.setObjectName("radioButton_2") self.textEdit = QtWidgets.QTextEdit(Form) self.textEdit.setGeometry(QtCore.QRect(300, 440, 201, 81)) self.textEdit.setObjectName("textEdit") self.label_11 = QtWidgets.QLabel(Form) self.label_11.setGeometry(QtCore.QRect(40, 410, 60, 31)) font = QtGui.QFont() font.setPointSize(18) self.label_11.setFont(font) self.label_11.setObjectName("label_11") self.label_12 = QtWidgets.QLabel(Form) self.label_12.setGeometry(QtCore.QRect(850, 460, 61, 21)) font = QtGui.QFont() font.setPointSize(18) self.label_12.setFont(font) self.label_12.setObjectName("label_12") self.label_13 = QtWidgets.QLabel(Form) self.label_13.setGeometry(QtCore.QRect(300, 410, 141, 21)) font = QtGui.QFont() font.setPointSize(18) self.label_13.setFont(font) self.label_13.setObjectName("label_13") self.label_9 = QtWidgets.QLabel(Form) self.label_9.setGeometry(QtCore.QRect(30, 380, 551, 31)) font = QtGui.QFont() font.setPointSize(18) self.label_9.setFont(font) self.label_9.setObjectName("label_9") self.label_15 = QtWidgets.QLabel(Form) self.label_15.setGeometry(QtCore.QRect(860, 490, 71, 21)) font = QtGui.QFont() font.setPointSize(18) self.label_15.setFont(font) self.label_15.setObjectName("label_15") self.lineEdit_3 = QtWidgets.QLineEdit(Form) self.lineEdit_3.setGeometry(QtCore.QRect(930, 490, 201, 21)) self.lineEdit_3.setObjectName("lineEdit_3") self.checkBox = QtWidgets.QCheckBox(Form) self.checkBox.setGeometry(QtCore.QRect(580, 490, 87, 20)) self.checkBox.setObjectName("checkBox") self.pushButton_4 = QtWidgets.QPushButton(Form) font = QtGui.QFont() font.setPointSize(18) self.pushButton_4.setFont(font) self.pushButton_4.setGeometry(QtCore.QRect(930, 380, 211, 41)) self.pushButton_4.setObjectName("pushButton_4") self.pushButton_4.clicked.connect(self.btn4_back) self.QTextEdit = QtWidgets.QTextEdit(Form) self.QTextEdit.setGeometry(QtCore.QRect(40, 610, 461, 91)) self.QTextEdit.setObjectName("QTextEdit") self.label_left = QtWidgets.QLabel(Form) self.label_left.setGeometry(QtCore.QRect(800, 700, 551, 31)) font = QtGui.QFont() font.setPointSize(18) self.label_left.setFont(font) self.label_left.setObjectName("label_left") self.retranslateUi(Form) QtCore.QMetaObject.connectSlotsByName(Form) def retranslateUi(self, Form): '''加载界面ui''' self.left_widget.currentRowChanged.connect( self.right_widget.setCurrentIndex) # list和右侧窗口的index对应绑定 self.oleft_widget.currentRowChanged.connect( self.oright_widget.setCurrentIndex) # list和右侧窗口的index对应绑定 # self.left_widget.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff) # 隐藏滚动条 self.left_widget.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff) for i, att_cl in enumerate(self.A_dict.keys()): self.item = QListWidgetItem(att_cl, self.left_widget) # 左侧选项的添加 font = QtGui.QFont() font.setPointSize(15) self.item.setFont(font) self.item.setSizeHint(QSize(15, 25)) self.item.setTextAlignment(Qt.AlignCenter) # 居中显示 locals()['stack' + str(i)] = QListWidget() # 左侧选项列表 locals()['stack' + str(i)].setGeometry(QtCore.QRect( 0, 0, 181, 360)) locals()['stack' + str(i)].setStyleSheet(self.list_style) for att_v in self.A_dict[att_cl]: self.ritem = QListWidgetItem(att_v, locals()['stack' + str(i)]) # 左侧选项的添加 font = QtGui.QFont() font.setPointSize(15) self.ritem.setFont(font) self.ritem.setSizeHint(QSize(15, 25)) self.ritem.setTextAlignment(Qt.AlignCenter) # 居中显示 self.right_widget.addWidget(locals()['stack' + str(i)]) self.A_comboBox_list.append(locals()["stack" + str(i)]) locals()['stack' + str(i)].currentRowChanged.connect( self.row_change) for i, obj_cl in enumerate(self.O_dict.keys()): self.oitem = QListWidgetItem(obj_cl, self.oleft_widget) # 左侧选项的添加 font = QtGui.QFont() font.setPointSize(15) self.oitem.setFont(font) self.oitem.setSizeHint(QSize(15, 25)) self.oitem.setTextAlignment(Qt.AlignCenter) # 居中显示 locals()['ostack' + str(i)] = QListWidget() # 左侧选项列表 locals()['ostack' + str(i)].setGeometry( QtCore.QRect(0, 0, 181, 360)) locals()['ostack' + str(i)].setStyleSheet(self.olist_style) for obj_v in self.O_dict[obj_cl]: self.oritem = QListWidgetItem(obj_v, locals()['ostack' + str(i)]) # 左侧选项的添加 font = QtGui.QFont() font.setPointSize(15) self.oritem.setFont(font) self.oritem.setSizeHint(QSize(15, 25)) self.oritem.setTextAlignment(Qt.AlignCenter) # 居中显示 self.oright_widget.addWidget(locals()['ostack' + str(i)]) self.O_comboBox_list.append(locals()["ostack" + str(i)]) locals()['ostack' + str(i)].currentRowChanged.connect( self.orow_change) _translate = QtCore.QCoreApplication.translate for i, key in enumerate(self.A_dict.keys()): self.comboBox_11.setItemText(i, _translate("Form", key)) for i, key in enumerate(self.O_dict.keys()): self.comboBox_11.setItemText(i + len(self.A_dict.keys()), _translate("Form", key)) Form.setWindowTitle(_translate("Form", "Anotation Tool")) self.groupBox.setTitle(_translate("Form", "属性")) self.groupBox_5.setTitle(_translate("Form", "对象")) self.pushButton_3.setText(_translate("Form", "完成添加")) self.radioButton.setText(_translate("Form", "属性")) self.radioButton_2.setText(_translate("Form", "对象")) self.label_11.setText(_translate("Form", "名称:")) self.label_12.setText(_translate("Form", "名称:")) self.label_13.setText(_translate("Form", "值:")) self.label_9.setText( _translate("Form", "文件名称:" + self.file_list[self.num])) self.label_left.setText( _translate( "Form", "图片已标注:" + str(len(os.listdir("Labels/"))) + ",还剩:" + str(len(self.file_list) - len(os.listdir("Labels/"))))) self.pushButton.setText(_translate("Form", "注释图片")) self.pushButton_2.setText(_translate("Form", "属性/对象完成添加")) self.label_15.setText(_translate("Form", "值:")) self.checkBox.setText(_translate("Form", "更新到图表")) self.pushButton_4.setText(_translate("Form", "上一张图片")) def row_change(self): cv = self.left_widget.currentIndex().data() i = self.left_widget.currentIndex().row() j = self.A_comboBox_list[i].currentIndex().row() vv = self.A_comboBox_list[i].currentIndex().data() self.A_answer[cv] = vv self.QTextEdit.setPlainText( str("对象:\n") + str(self.O_answer) + "\n" + str("属性:\n") + str(self.A_answer) + "\n") def orow_change(self): cv = self.oleft_widget.currentIndex().data() i = self.oleft_widget.currentIndex().row() j = self.O_comboBox_list[i].currentIndex().row() vv = self.O_comboBox_list[i].currentIndex().data() self.O_answer[cv] = vv self.QTextEdit.setPlainText( str("对象:\n") + str(self.O_answer) + "\n" + str("属性:\n") + str(self.A_answer) + "\n") def btn_save(self): self.num += 1 with open("count", "w") as f: f.write(str(self.num)) text = self.QTextEdit.toPlainText() O_an = eval(text.split('\n')[1]) A_an = eval(text.split('\n')[3]) if os.path.exists("./Labels/" + self.file_list[self.num - 1] + ".json"): os.remove("./Labels/" + self.file_list[self.num - 1] + ".json") with open("./Labels/" + self.file_list[self.num - 1] + ".json", mode="a") as f: json.dump(A_an, f, ensure_ascii=False) json.dump(O_an, f, ensure_ascii=False) if self.num > len(self.file_list) - 1: sys.exit(0) pixmap = QPixmap("./Images/" + self.file_list[self.num]) self.label_16.setPixmap(pixmap) self.label_16.setScaledContents(True) self.left_widget.reset() self.oleft_widget.reset() _translate = QtCore.QCoreApplication.translate self.label_9.setText( _translate("Form", "Image Name:" + self.file_list[self.num])) self.label_left.setText( _translate( "Form", "图片已标注:" + str(len(os.listdir("Labels/"))) + ",还剩:" + str(len(self.file_list) - len(os.listdir("Labels/"))))) for comboBox_i in self.A_comboBox_list: comboBox_i.reset() for comboBox_i in self.O_comboBox_list: comboBox_i.reset() self.A_answer = {} self.O_answer = {} self.QTextEdit.clear() def btn_add_val(self): my_key = self.comboBox_11.currentText() text = self.textEdit.toPlainText() text_list = text.split(',') _translate = QtCore.QCoreApplication.translate for i, key in enumerate(self.A_dict.keys()): if key == my_key: lines = [] with open("Attribute", encoding='utf-8-sig') as f: for line in f.readlines(): temp = line[:-1].split(':') if temp[0] == my_key: lines.append(line[:-1] + ',' + text + '\n') else: lines.append(line) with open("Attribute", 'w', encoding='utf-8') as f: s = ''.join(lines) f.write(str(s)) for txt in text_list: self.item = QListWidgetItem( txt, self.A_comboBox_list[i]) # 左侧选项的添加 font = QtGui.QFont() font.setPointSize(15) self.item.setFont(font) self.item.setSizeHint(QSize(15, 25)) self.item.setTextAlignment(Qt.AlignCenter) # 居中显示 self.A_dict[key] += text_list for i, key in enumerate(self.O_dict.keys()): if key == my_key: lines = [] with open("Object", encoding="utf-8-sig") as f: for line in f.readlines(): temp = line[:-1].split(':') if temp[0] == my_key: lines.append(line[:-1] + ',' + text + '\n') else: lines.append(line) with open("Object", 'w', encoding='utf-8') as f: s = ''.join(lines) f.write(str(s)) for txt in text_list: self.oitem = QListWidgetItem( txt, self.O_comboBox_list[i]) # 左侧选项的添加 font = QtGui.QFont() font.setPointSize(15) self.oitem.setFont(font) self.oitem.setSizeHint(QSize(15, 25)) self.oitem.setTextAlignment(Qt.AlignCenter) # 居中显示 self.O_dict[key] += text_list print([my_key, text]) self.textEdit.setText("") def radio_msg(self): if self.radioButton.isChecked(): self.add_a = True self.add_o = False if self.radioButton_2.isChecked(): self.add_o = True self.add_a = False def btn_add_class(self): if self.add_a: self.radioButton.setChecked(True) my_key = self.lineEdit_2.text() my_val = self.lineEdit_3.text() my_val = my_val.split(",") _translate = QtCore.QCoreApplication.translate if self.checkBox.isChecked(): if len(my_key) != 0: i = len(self.A_comboBox_list) self.item = QListWidgetItem(my_key, self.left_widget) # 左侧选项的添加 font = QtGui.QFont() font.setPointSize(15) self.item.setFont(font) self.item.setSizeHint(QSize(15, 25)) self.item.setTextAlignment(Qt.AlignCenter) # 居中显示 locals()['stack' + str(i)] = QListWidget() # 左侧选项列表 locals()['stack' + str(i)].setGeometry( QtCore.QRect(0, 0, 181, 360)) locals()['stack' + str(i)].setStyleSheet(self.list_style) for att_v in my_val: self.ritem = QListWidgetItem( att_v, locals()['stack' + str(i)]) # 左侧选项的添加 font = QtGui.QFont() font.setPointSize(15) self.ritem.setFont(font) self.ritem.setSizeHint(QSize(15, 25)) self.ritem.setTextAlignment(Qt.AlignCenter) # 居中显示 self.right_widget.addWidget(locals()['stack' + str(i)]) self.A_comboBox_list.append(locals()["stack" + str(i)]) locals()['stack' + str(i)].currentRowChanged.connect( self.row_change) self.A_dict[my_key] = my_val lines = [] with open("Attribute", encoding="utf-8-sig") as f: for line in f.readlines(): lines.append(line) lines.append('\n' + my_key + ":" + ",".join(my_val)) with open("Attribute", 'w', encoding="utf-8") as f: s = ''.join(lines) f.write(str(s)) self.comboBox_11.addItem("") self.comboBox_11.setItemText( len(self.A_dict.keys()) + len(self.O_dict.keys()) - 1, _translate("Form", my_key)) else: text = self.QTextEdit.toPlainText() if len(text) != 0: self.A_answer = eval(text.split('\n')[3]) self.O_answer = eval(text.split('\n')[1]) else: self.A_answer = {} self.O_answer = {} # print(A_an) self.A_answer[my_key] = my_val[0] self.QTextEdit.setPlainText( str("对象:\n") + str(self.O_answer) + "\n" + str("属性:\n") + str(self.A_answer) + "\n") if self.add_o: self.add_o = False self.radioButton.setChecked(True) my_key = self.lineEdit_2.text() my_val = self.lineEdit_3.text() my_val = my_val.split(",") _translate = QtCore.QCoreApplication.translate if self.checkBox.isChecked(): if len(my_key) != 0: i = len(self.O_comboBox_list) self.oitem = QListWidgetItem(my_key, self.oleft_widget) # 左侧选项的添加 font = QtGui.QFont() font.setPointSize(15) self.oitem.setFont(font) self.oitem.setSizeHint(QSize(15, 25)) self.oitem.setSizeHint(QSize(15, 20)) self.oitem.setTextAlignment(Qt.AlignCenter) # 居中显示 locals()['ostack' + str(i)] = QListWidget() # 左侧选项列表 locals()['ostack' + str(i)].setGeometry( QtCore.QRect(0, 0, 181, 360)) locals()['ostack' + str(i)].setStyleSheet(self.olist_style) for obj_v in my_val: self.oritem = QListWidgetItem( obj_v, locals()['ostack' + str(i)]) # 左侧选项的添加 font = QtGui.QFont() font.setPointSize(15) self.oritem.setFont(font) self.oritem.setSizeHint(QSize(15, 25)) self.oritem.setTextAlignment(Qt.AlignCenter) # 居中显示 self.oright_widget.addWidget(locals()['ostack' + str(i)]) self.O_comboBox_list.append(locals()["ostack" + str(i)]) locals()['ostack' + str(i)].currentRowChanged.connect( self.orow_change) self.O_dict[my_key] = my_val lines = [] with open("Object", encoding="utf-8-sig") as f: for line in f.readlines(): lines.append(line) lines.append('\n' + my_key + ":" + ",".join(my_val)) with open("Object", 'w', encoding="utf-8") as f: s = ''.join(lines) f.write(str(s)) self.comboBox_11.addItem("") self.comboBox_11.setItemText( len(self.A_dict.keys()) + len(self.O_dict.keys()) - 1, _translate("Form", my_key)) else: text = self.QTextEdit.toPlainText() if len(text) != 0: self.A_answer = eval(text.split('\n')[3]) self.O_answer = eval(text.split('\n')[1]) else: self.A_answer = {} self.O_answer = {} self.O_answer[my_key] = my_val[0] self.QTextEdit.setPlainText( str("对象:\n") + str(self.O_answer) + "\n" + str("属性:\n") + str(self.A_answer) + "\n") self.radio_flag = False self.checkBox.setChecked(False) self.lineEdit_2.setText("") self.lineEdit_3.setText("") def btn4_back(self): if self.num < 1: sys.exit(0) self.num = self.num - 1 with open("count", "w") as f: f.write(str(self.num)) pixmap = QPixmap("./Images/" + self.file_list[self.num]) self.label_16.setPixmap(pixmap) self.label_16.setScaledContents(True) _translate = QtCore.QCoreApplication.translate self.label_9.setText( _translate("Form", "Image Name:" + self.file_list[self.num])) for comboBox_i in self.A_comboBox_list: comboBox_i.reset() for comboBox_i in self.O_comboBox_list: comboBox_i.reset() self.QTextEdit.clear()
def getPath(self, item: QtWidgets.QListWidgetItem): return self.file2path[item.text()]
def retranslateUi(self, Form): '''加载界面ui''' self.left_widget.currentRowChanged.connect( self.right_widget.setCurrentIndex) # list和右侧窗口的index对应绑定 self.oleft_widget.currentRowChanged.connect( self.oright_widget.setCurrentIndex) # list和右侧窗口的index对应绑定 # self.left_widget.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff) # 隐藏滚动条 self.left_widget.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff) for i, att_cl in enumerate(self.A_dict.keys()): self.item = QListWidgetItem(att_cl, self.left_widget) # 左侧选项的添加 font = QtGui.QFont() font.setPointSize(15) self.item.setFont(font) self.item.setSizeHint(QSize(15, 25)) self.item.setTextAlignment(Qt.AlignCenter) # 居中显示 locals()['stack' + str(i)] = QListWidget() # 左侧选项列表 locals()['stack' + str(i)].setGeometry(QtCore.QRect( 0, 0, 181, 360)) locals()['stack' + str(i)].setStyleSheet(self.list_style) for att_v in self.A_dict[att_cl]: self.ritem = QListWidgetItem(att_v, locals()['stack' + str(i)]) # 左侧选项的添加 font = QtGui.QFont() font.setPointSize(15) self.ritem.setFont(font) self.ritem.setSizeHint(QSize(15, 25)) self.ritem.setTextAlignment(Qt.AlignCenter) # 居中显示 self.right_widget.addWidget(locals()['stack' + str(i)]) self.A_comboBox_list.append(locals()["stack" + str(i)]) locals()['stack' + str(i)].currentRowChanged.connect( self.row_change) for i, obj_cl in enumerate(self.O_dict.keys()): self.oitem = QListWidgetItem(obj_cl, self.oleft_widget) # 左侧选项的添加 font = QtGui.QFont() font.setPointSize(15) self.oitem.setFont(font) self.oitem.setSizeHint(QSize(15, 25)) self.oitem.setTextAlignment(Qt.AlignCenter) # 居中显示 locals()['ostack' + str(i)] = QListWidget() # 左侧选项列表 locals()['ostack' + str(i)].setGeometry( QtCore.QRect(0, 0, 181, 360)) locals()['ostack' + str(i)].setStyleSheet(self.olist_style) for obj_v in self.O_dict[obj_cl]: self.oritem = QListWidgetItem(obj_v, locals()['ostack' + str(i)]) # 左侧选项的添加 font = QtGui.QFont() font.setPointSize(15) self.oritem.setFont(font) self.oritem.setSizeHint(QSize(15, 25)) self.oritem.setTextAlignment(Qt.AlignCenter) # 居中显示 self.oright_widget.addWidget(locals()['ostack' + str(i)]) self.O_comboBox_list.append(locals()["ostack" + str(i)]) locals()['ostack' + str(i)].currentRowChanged.connect( self.orow_change) _translate = QtCore.QCoreApplication.translate for i, key in enumerate(self.A_dict.keys()): self.comboBox_11.setItemText(i, _translate("Form", key)) for i, key in enumerate(self.O_dict.keys()): self.comboBox_11.setItemText(i + len(self.A_dict.keys()), _translate("Form", key)) Form.setWindowTitle(_translate("Form", "Anotation Tool")) self.groupBox.setTitle(_translate("Form", "属性")) self.groupBox_5.setTitle(_translate("Form", "对象")) self.pushButton_3.setText(_translate("Form", "完成添加")) self.radioButton.setText(_translate("Form", "属性")) self.radioButton_2.setText(_translate("Form", "对象")) self.label_11.setText(_translate("Form", "名称:")) self.label_12.setText(_translate("Form", "名称:")) self.label_13.setText(_translate("Form", "值:")) self.label_9.setText( _translate("Form", "文件名称:" + self.file_list[self.num])) self.label_left.setText( _translate( "Form", "图片已标注:" + str(len(os.listdir("Labels/"))) + ",还剩:" + str(len(self.file_list) - len(os.listdir("Labels/"))))) self.pushButton.setText(_translate("Form", "注释图片")) self.pushButton_2.setText(_translate("Form", "属性/对象完成添加")) self.label_15.setText(_translate("Form", "值:")) self.checkBox.setText(_translate("Form", "更新到图表")) self.pushButton_4.setText(_translate("Form", "上一张图片"))
def listeDoldur(self): liste = self.db.sozlukListele(param="1 OR 1=1") for item in liste: yazi = str(item[0]) + "-" + item[1] nesne = QListWidgetItem(yazi) self.win.liste.addItem(nesne)
def on_btnSave_clicked(self): planeType_txt = self.planeType_edit.currentText() msg_list = [] x1_txt = self.x1.text() y1_txt = self.y1.text() z1_txt = self.z1.text() x2_txt = self.x2.text() y2_txt = self.y2.text() z2_txt = self.z2.text() xyz1_list = [] xyz1_list.append(x1_txt) xyz1_list.append(y1_txt) xyz1_list.append(z1_txt) xyz2_list = [] xyz2_list.append(x2_txt) xyz2_list.append(y2_txt) xyz2_list.append(z2_txt) planeTolerance_txt = self.planeTolerance_edit.text() if x1_txt == '': if self.interface_lng_val == 'Russian': msg = 'Укажите значение x для параметра point' elif self.interface_lng_val == 'English': msg = 'Specify the x value for the point parameter' msg_list.append(msg) if y1_txt == '': if self.interface_lng_val == 'Russian': msg = 'Укажите значение y для параметра point' elif self.interface_lng_val == 'English': msg = 'Specify the y value for the point parameter' msg_list.append(msg) if z1_txt == '': if self.interface_lng_val == 'Russian': msg = 'Укажите значение z для параметра point' elif self.interface_lng_val == 'English': msg = 'Specify the z value for the point parameter' msg_list.append(msg) if x2_txt == '': if self.interface_lng_val == 'Russian': msg = 'Укажите значение x для параметра normal' elif self.interface_lng_val == 'English': msg = 'Specify the x value for the normal parameter' msg_list.append(msg) if y2_txt == '': if self.interface_lng_val == 'Russian': msg = 'Укажите значение y для параметра normal' elif self.interface_lng_val == 'English': msg = 'Specify the y value for the normal parameter' msg_list.append(msg) if z2_txt == '': if self.interface_lng_val == 'Russian': msg = 'Укажите значение z для параметра normal' elif self.interface_lng_val == 'English': msg = 'Specify the z value for the normal parameter' msg_list.append(msg) if planeTolerance_txt == '': if self.interface_lng_val == 'Russian': msg = 'Укажите значение для параметра planeTolerance' elif self.interface_lng_val == 'English': msg = 'Specify the value for the planeTolerance parameter' msg_list.append(msg) for msg in msg_list: msg_lbl = QLabel('<span style="color:red">' + msg + '</span>') self.par.item = QListWidgetItem() self.par.listWidget.addItem(self.par.item) self.par.listWidget.setItemWidget(self.par.item, msg_lbl) if '' not in xyz1_list and '' not in xyz2_list and planeTolerance_txt != '': if 'mirrorMeshDict_x' not in self.con.tables(): query = QtSql.QSqlQuery() xyz1_str = x1_txt + ' ' + y1_txt + ' ' + z1_txt xyz2_str = x2_txt + ' ' + y2_txt + ' ' + z2_txt query.exec("CREATE TABLE mirrorMeshDict_x(name, value)") query.exec( "INSERT INTO mirrorMeshDict_x(name, value) VALUES ('%s', '%s')" % ('planeType', planeType_txt)) query.exec( "INSERT INTO mirrorMeshDict_x(name, value) VALUES ('%s', '%s')" % ('point', xyz1_str)) query.exec( "INSERT INTO mirrorMeshDict_x(name, value) VALUES ('%s', '%s')" % ('point', xyz2_str)) query.exec( "INSERT INTO mirrorMeshDict_x(name, value) VALUES ('%s', '%s')" % ('planeTolerance', planeTolerance_txt)) else: query = QtSql.QSqlQuery() xyz1_str = x1_txt + ' ' + y1_txt + ' ' + z1_txt xyz2_str = x2_txt + ' ' + y2_txt + ' ' + z2_txt query.prepare("DROP TABLE mirrorMeshDict_x") query.exec_() query.exec("CREATE TABLE mirrorMeshDict_x(name, value)") query.exec( "INSERT INTO mirrorMeshDict_x(name, value) VALUES ('%s', '%s')" % ('planeType', planeType_txt)) query.exec( "INSERT INTO mirrorMeshDict_x(name, value) VALUES ('%s', '%s')" % ('point', xyz1_str)) query.exec( "INSERT INTO mirrorMeshDict_x(name, value) VALUES ('%s', '%s')" % ('point', xyz2_str)) query.exec( "INSERT INTO mirrorMeshDict_x(name, value) VALUES ('%s', '%s')" % ('planeTolerance', planeTolerance_txt)) # записываем файл mirrorMeshDict.x if os.path.exists(self.full_dir + '/system/mirrorMeshDict.x'): os.remove(self.full_dir + '/system/mirrorMeshDict.x') shutil.copyfile("./matches/Shablon/system/mirrorMeshDict.x", self.full_dir + '/system/mirrorMeshDict.x') mMD_x = open(self.full_dir + '/system/mirrorMeshDict.x', 'a') planeType_bl = '\n' + 'planeType' + ' ' + planeType_txt + ';' + '\n' pAND_bl = '\n' + 'pointAndNormalDict' + '\n' + '{' + '\n' + ' ' + 'point' + ' ' + '(' + x1_txt + ' ' + y1_txt + ' ' + z1_txt + ');' + '\n' + \ ' ' + 'normal' + ' ' + '(' + x2_txt + ' ' + y2_txt + ' ' + z2_txt + ');' + '\n' + '}' + '\n\n' planeTolerance_bl = 'planeTolerance' + ' ' + planeTolerance_txt + ';' + '\n\n' mMD_x.write(planeType_bl + pAND_bl + planeTolerance_bl) close_str = '// ************************************************************************* //' mMD_x.write(close_str) mMD_x.close() if self.interface_lng_val == 'Russian': msg = 'Файл mirrorMeshDict.x сохранен' elif self.interface_lng_val == 'English': msg = 'The mirrorMeshDict.x file saved</span>' self.par.listWidget.clear() msg_lbl = QLabel('<span style="color:green">' + msg + '</span>') self.par.item = QListWidgetItem() self.par.listWidget.addItem(self.par.item) self.par.listWidget.setItemWidget(self.par.item, msg_lbl) self.data_reprint()
def __init__(self): super(exampleQMainWindow, self).__init__() # Create QListWidget self.myQListWidget = QListWidget(self) self.myQListWidget.setStyleSheet(""" QListWidget:item:selected:active { background-color:#A6A4FF;} """) self.setMinimumSize(350, 500) self.config = configparser.ConfigParser() self.config.read('prefs.cfg') self.extention = QLineEdit() self.filename = QLineEdit() self.add_type = QPushButton("add type") self.del_type = QPushButton("del type") self.color_button = color_picker(parent=self) self.pattern_icon = Pattern_button(parent=self) self.radio_button_one = QRadioButton('Classic') self.radio_button_two = QRadioButton('Magellan') self.radio_group = QGroupBox('operation mode') self.radio_group.setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Preferred) self.pattern_group = QGroupBox('window pattern and text color') self.pattern_group.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Preferred) self.button_group = QButtonGroup() self.button_group.addButton(self.radio_button_one) self.button_group.addButton(self.radio_button_two) self.button_group.setId(self.radio_button_one, 1) self.button_group.setId(self.radio_button_two, 2) self.mainlayout = QVBoxLayout() self.holdgroups_layout = QHBoxLayout() self.radio_button_layout = QVBoxLayout() self.pattern_label_layout = QHBoxLayout() self.add_filetype_layout = QFormLayout() self.add_del_button_layout = QHBoxLayout() # adding self.holdgroups_layout.addWidget(self.radio_group) self.holdgroups_layout.addWidget(self.pattern_group) self.pattern_label_layout.addWidget(self.pattern_icon) self.pattern_label_layout.addStretch(1) self.pattern_label_layout.addWidget(self.color_button) self.pattern_label_layout.addStretch(1) self.pattern_group.setLayout(self.pattern_label_layout) self.radio_button_layout.addWidget(self.radio_button_one) self.radio_button_layout.addWidget(self.radio_button_two) self.radio_group.setLayout(self.radio_button_layout) self.add_filetype_layout.addRow('extention', self.extention) self.add_filetype_layout.addRow('path to icon', self.filename) self.add_del_button_layout.addWidget(self.add_type) self.add_del_button_layout.addWidget(self.del_type) # layouts settings # self.radio_button_layout.setGeometry(QRect(10, 10, 10, 10)) self.add_filetype_layout.setFieldGrowthPolicy(QFormLayout.ExpandingFieldsGrow) # self.pattern_icon.setPixmap(QPixmap("./images/pattern.png").scaledToWidth(80)) self.mainlayout.setContentsMargins(5, 5, 5, 0) self.mainlayout.setSpacing(7) # reading stored settings for key, value in self.config.items('icons'): myQCustomQWidget = QCustomQWidget() myQCustomQWidget.setTextUp("filetype: " + key.upper()) myQCustomQWidget.setTextDown(value) myQCustomQWidget.setIcon(os.path.dirname(os.path.realpath(__file__)) + value) myQListWidgetItem = QListWidgetItem(self.myQListWidget) myQListWidgetItem.setSizeHint(myQCustomQWidget.sizeHint()) self.myQListWidget.addItem(myQListWidgetItem) self.myQListWidget.setItemWidget(myQListWidgetItem, myQCustomQWidget) # adding elements to layout self.mainlayout.addLayout(self.holdgroups_layout) self.mainlayout.insertSpacing(10, 10) self.mainlayout.addWidget(self.myQListWidget) self.mainlayout.addLayout(self.add_filetype_layout) self.mainlayout.addLayout(self.add_del_button_layout) self.setLayout(self.mainlayout)