def init_ana_widget(self): self.rlayout = QHBoxLayout() self.ana_widget.setLayout(self.rlayout) self.fig = Figure() self.canvas = FigureCanvas(self.fig) self.canvas_label = QLabel("Result") canvas_widget = QWidget() canvas_layout = QVBoxLayout() canvas_widget.setLayout(canvas_layout) canvas_layout.addWidget(self.canvas_label) canvas_layout.addWidget(self.canvas) canvas_layout.setStretch(0, 1) canvas_layout.setStretch(1, 20) self.tracklist_panel = QWidget() self.tracklist_layout = QVBoxLayout() self.tracklist_panel.setLayout(self.tracklist_layout) self.init_topic_tracklist() self.init_weibo_tracklist() self.tracklist_layout.addWidget(self.topic_tracklist_widget) self.tracklist_layout.addWidget(self.weibo_tracklist_widget) self.rlayout.addWidget(self.tracklist_panel) self.rlayout.addWidget(canvas_widget) cfg = self.scheduler.load_config() for topic_name in cfg['topic_tracklist']: self.topic_tracklist_model.appendRow(QStandardItem(topic_name)) for weibo_id in cfg["weibo_id_tracklist"]: self.weibo_tracklist_model.appendRow(QStandardItem(str(weibo_id)))
def log(self, msg, status_str="INFO"): time_str = datetime.now().strftime("%Y-%m-%d-%H:%M:%S") self.log_model.appendRow([ QStandardItem(status_str), QStandardItem(time_str), QStandardItem(msg) ])
def update_filename_box(self): doing_multiple = self.doing_multiple model = QStandardItemModel() self.filename_box.setModel(model) self.icon_file_names.sort(key=sort_key) if doing_multiple: item = QStandardItem(_('Open to see checkboxes')) item.setIcon(QIcon(I('blank.png'))) else: item = QStandardItem('') item.setFlags(Qt.ItemFlag(0)) model.appendRow(item) for i, filename in enumerate(self.icon_file_names): item = QStandardItem(filename) if doing_multiple: item.setFlags(Qt.ItemIsUserCheckable | Qt.ItemIsEnabled) item.setData(Qt.Unchecked, Qt.CheckStateRole) else: item.setFlags(Qt.ItemIsEnabled | Qt.ItemIsSelectable) icon = QIcon( QPixmap(os.path.join(self.icon_folder, filename)).scaled( self.filenamebox_view.iconSize(), transformMode=Qt.SmoothTransformation)) item.setIcon(icon) model.appendRow(item)
def __init__(self, obj_map): self.obj_map = obj_map super().__init__() self.setWindowTitle("Object File Browser") self.childen_windows = [] layout = QVBoxLayout() monospaced_font = get_monospaced_font() layout.addWidget(QLabel("Browse object files by dgo...")) # Set up the tree view self.tree = QTreeView() self.tree_model = QStandardItemModel() self.tree_root = self.tree_model.invisibleRootItem() for dgo_name, dgo in obj_map.dgo_files.items(): dgo_entry = QStandardItem(dgo_name) dgo_entry.setFont(monospaced_font) dgo_entry.setEditable(False) for obj_name, obj in dgo.obj_files.items(): obj_entry = QStandardItem(obj_name) obj_entry.setFont(monospaced_font) obj_entry.setEditable(False) dgo_entry.appendRow(obj_entry) self.tree_root.appendRow(dgo_entry) self.tree.setModel(self.tree_model) self.tree.clicked.connect(self.handle_tree_click) self.tree.doubleClicked.connect(self.handle_tree_double_click) layout.addWidget(self.tree) # Set up the Search Box layout.addWidget(QLabel("Or search for object (regex):")) self.search_box = QLineEdit() self.search_box.textChanged.connect(self.handle_search_change) layout.addWidget(self.search_box) # Set up Search Results self.search_result = QListView() layout.addWidget(self.search_result) self.search_result.clicked.connect(self.handle_search_result_click) self.search_result.doubleClicked.connect( self.handle_search_result_double_click) self.search_result.setMaximumHeight(200) # Set up the info box at the bottom self.text_box = QPlainTextEdit() self.text_box.setReadOnly(True) self.text_box.setFont(monospaced_font) layout.addWidget(self.text_box) self.text_box.setMaximumHeight(100) self.text_box.setPlainText( "Select an object file to see details. Double click to open.") # add it to the window! widget = QWidget() widget.setLayout(layout) self.setCentralWidget(widget)
def insertProject(self, project): """Função responsável por inserir um novo projeto na árvore da UI""" projeto = QStandardItem(project.name) # Adiciona todas as listas que o projeto possui for key in sorted(project.dirList): lista1 = QStandardItem(project.dirList[key].name) projeto.appendRow(lista1) self.rootNode.appendRow(projeto)
def __init__(self): super().__init__(1, 3) self.setHorizontalHeaderLabels(['Item', 'Show', 'Value']) # Label self.setItem(0, 0, QStandardItem('Antialias')) # Visibility checkbox checkItem = QStandardItem('') checkItem.setCheckable(True) checkItem.setCheckState(Qt.Checked) self.setItem(0, 1, checkItem) # sample count # todo spinbox sampleCount = QStandardItem('X') self.setItem(0, 2, sampleCount)
def update_usb_devices(self): model = QStandardItemModel() bus = dbus.SystemBus() self.iface = 'org.freedesktop.DBus.ObjectManager' #bus.add_signal_receiver(self.callback_function, signal, iface) proxy = bus.get_object("org.freedesktop.UDisks2", "/org/freedesktop/UDisks2") self.iface = dbus.Interface(proxy, "org.freedesktop.UDisks2") self.iface.connect_to_signal('DeviceAdded', self.device_added_callback) self.iface.connect_to_signal('DeviceRemoved', self.device_removed_callback) self.iface.connect_to_signal('InterfacesAdded', self.device_changed_callback) dev1 = get_usb() items = get_usb() #for text, checked in items: for text in sorted(items): text_item = QStandardItem(text) #checked_item = QStandardItem() #checked_item.setData(QVariant(checked), Qt.CheckStateRole) model.appendRow(text_item) #([text_item, checked_item]) view = QTreeView() view.header().hide() view.setRootIsDecorated(False) combo = self.ui.comboBox_device combo.setView(view) combo.setModel(model) combo.show()
def fillModelByCursor(self, cursor): i = 0 setheader = False self.modeldata = [] for item in cursor: j = 0 items = item.items() if setheader == False: self.setColumnCount(len(items)) self.labels = item.keys() if sys.version > '3': self.labels = sorted(self.labels) else: self.labels.sort() self.setHorizontalHeaderLabels(self.labels) setheader = True self.modeldata.append(item) for (field, value) in items: try: fieldindex = self.labels.index(field) except ValueError: self.labels.append(field) fieldindex = len(self.labels) - 1 self.setHorizontalHeaderLabels(self.labels) valueBytes = str(value).encode("utf_8") self.setItem( i, fieldindex, QStandardItem(valueBytes.decode(encoding='utf_8'))) j += 1 i += 1
def displaysql(self): db = pymysql.connect("localhost", "root", "123456", "flowdata", charset="UTF8") cursor = db.cursor() cursor.execute("SELECT *FROM ANOMALYTYPE") rows = cursor.fetchall() if rows != (): row = cursor.rowcount # 取得记录个数,用于设置表格的行数 vol = len(rows[0]) # 取得字段数,用于设置表格的列数 cursor.close() db.close() self.model = QStandardItemModel() self.model.setHorizontalHeaderLabels( ['异常发生时间', '异常流量源地址', '异常流量目的地址', '异常流量类型']) self.tableView.horizontalHeader().setStretchLastSection(True) self.tableView.horizontalHeader().setSectionResizeMode( QHeaderView.Stretch) for i in range(row): for j in range(vol): temp_data = rows[i][j] data = QStandardItem("%s" % (str(temp_data))) self.model.setItem(i, j, data) self.tableView.setModel(self.model) else: cursor.close() db.close()
def __init__(self, id_dict: dict, name_dict: dict, parent=None): """ Supers QComboBox, but also creates class references to the categories dictionaries. Args: id_dict: Categories dictionary with id numbers as keys. name_dict: Categories dictionary with names as keys. parent: Widget parent. """ super().__init__() self.id_dict = id_dict self.name_dict = name_dict cat_list = sorted(list(self.name_dict.keys())) self.fill_combo(cat_list) model = QStandardItemModel() for i, word in enumerate(cat_list): item = QStandardItem(word) model.setItem(i, 0, item) self.setModel(model) self.setModelColumn(0) if parent is not None: self.setParent(parent)
def _addSuggestions(self, suggestions): ''' @param: sugesstions QStringList ''' suggestionItems = self._s_model.suggestionItems() # Delete existing suggestions for item in suggestionItems: self._s_model.takeRow(item.row()) # Add new suggestions items = [] # QList<QStandardItem> for suggestion in suggestions: item = QStandardItem() item.setText(suggestion) item.setData(suggestion, LocationCompleterModel.TitleRole) item.setData(suggestion, LocationCompleterModel.UrlRole) item.setData(self._suggestionsTerm, LocationCompleterModel.SearchStringRole) item.setData(True, LocationCompleterModel.SearchSuggestionRole) items.append(item) self._s_model.addCompletions(items) self._oldSuggestions = suggestions if not self._popupClosed: self._showPopup()
def getRegisterViewRow(self): null = QStandardItem("") null.setEditable(False) return [ self.RegisterItem, self.address, self.length, self.signed, self.readWrite, self.title, self.description ]
def append_row(self,members,data_model): for (i,member) in enumerate(members): cells = [] user_name = member['UserName'] user_name_cell = QStandardItem(user_name) user_name_cell.setCheckable(True) cells.append(user_name_cell) user_avatar = self.contact_head_home + member['UserName']+".jpg" if not os.path.exists(user_avatar): user_avatar = self.default_head_icon dn = member['DisplayName'] or member['NickName'] if not dn: dn = member['NickName'] item = QStandardItem(QIcon(user_avatar),wechatutil.unicode(dn)) cells.append(item) data_model.appendRow(cells)
def updateList(self): #TODO Upgrade to a table, with more data self.fieldlistModel.clear() for field in self.registerLayout.fields: field.listItem = QStandardItem(field.name) field.listItem.setEditable(False) self.fieldlistModel.appendRow(field.listItem) if self.registerLayout.selected is not None: self.updateSelected(self.registerLayout.selected)
def OKBtn_click(self): val = [] self.model.removeRow(self.num - 1) self.HeJiMoney = self.HeJiMoney + self.je val.append(QStandardItem("%d" % self.num)) val.append(QStandardItem("%d" % self.Zhongliang.value())) val.append(QStandardItem("%.2f" % self.doubleSpinBox_2.value())) val.append(QStandardItem("%.1f" % self.je)) self.data.append(val) self.model.appendRow(val) self.model.item(self.num - 1, 0).setTextAlignment(Qt.AlignCenter) self.model.item(self.num - 1, 1).setTextAlignment(Qt.AlignCenter) self.model.item(self.num - 1, 2).setTextAlignment(Qt.AlignCenter) self.model.item(self.num - 1, 3).setTextAlignment(Qt.AlignCenter) self.model.setItem(self.num, 3, QStandardItem("合计:%.1f" % self.HeJiMoney)) self.model.item(self.num, 3).setTextAlignment(Qt.AlignCenter) self.tableView.scrollToBottom() #滚动到最底部 self.num += 1
def display_function(self, item): name = item.data() monospaced_font = get_monospaced_font() func = self.functions_by_name[name] basic_op_model = QStandardItemModel() basic_op_root = basic_op_model.invisibleRootItem() asm_model = QStandardItemModel() asm_root = asm_model.invisibleRootItem() self.basic_id_to_asm = [] self.current_function = name op_idx = 0 basic_idx = 0 for op in func["asm"]: if "label" in op: asm_item = QStandardItem(op["label"] + "\n " + op["asm_op"]) else: asm_item = QStandardItem(" " + op["asm_op"]) asm_item.setFont(monospaced_font) asm_item.setEditable(False) asm_root.appendRow(asm_item) if "basic_op" in op: if "label" in op: basic_item = QStandardItem(op["label"] + "\n " + op["basic_op"]) else: basic_item = QStandardItem(" " + op["basic_op"]) basic_item.setFont(monospaced_font) basic_item.setEditable(False) basic_op_root.appendRow(basic_item) self.basic_id_to_asm.append(op_idx) basic_idx = basic_idx + 1 op_idx = op_idx + 1 self.basic_id_to_asm.append(op_idx) self.basic_op_pane.setModel(basic_op_model) self.asm_pane.setModel(asm_model) self.warnings_label.setText(func["warnings"]) self.asm_display.setPlainText("") self.function_header_label.setText( "{}, type: {}\nfunc: {} obj: {}".format(name, func["type"], func["name"], func["parent_object"]))
def handle_search_change(self, text): objs = self.obj_map.get_objs_matching_regex(text) model = QStandardItemModel() root = model.invisibleRootItem() monospaced_font = get_monospaced_font() for x in objs: entry = QStandardItem(x) entry.setFont(monospaced_font) entry.setEditable(False) root.appendRow(entry) self.search_result.setModel(model)
def update_filename_box(self): doing_multiple = self.doing_multiple model = QStandardItemModel() self.filename_box.setModel(model) self.icon_file_names.sort(key=sort_key) if doing_multiple: item = QStandardItem(_('Open to see checkboxes')) else: item = QStandardItem('') model.appendRow(item) for i, filename in enumerate(self.icon_file_names): item = QStandardItem(filename) if doing_multiple: item.setFlags(Qt.ItemIsUserCheckable | Qt.ItemIsEnabled) item.setData(Qt.Unchecked, Qt.CheckStateRole) else: item.setFlags(Qt.ItemIsEnabled | Qt.ItemIsSelectable) icon = QIcon(os.path.join(self.icon_folder, filename)) item.setIcon(icon) model.appendRow(item)
def XiuGaiBtn_click(self): if len(self.data) != 0: #判断是否还有数据 self.HeJiMoney -= float(self.data[-1][3].text()) self.data.pop() if self.HeJiMoney < 0: self.HeJiMoney = 0 self.model.removeRow(self.num - 2) #删除最后一次数据 self.model.removeRow(self.num - 1) #删除合计金额行 self.model.setItem(self.num - 2, 3, QStandardItem("合计:%.1f" % self.HeJiMoney)) self.model.item(self.num - 2, 3).setTextAlignment(Qt.AlignCenter) self.num -= 1 if self.num < 1: self.num = 1
def _completeMostVisited(self): qs = HistoryDbModel.select().order_by( HistoryDbModel.count.desc()).limit(15) for history in qs: item = QStandardItem() url = QUrl(history.url) item.setText(url.toEncoded().data().decode()) item.setData(history.id, LocationCompleterModel.IdRole) item.setData(history.title, LocationCompleterModel.TitleRole) item.setData(url, LocationCompleterModel.UrlRole) item.setData(True, LocationCompleterModel.HistoryRole) self._items.append(item)
def __init__(self, parent=None): super(HighlightOptionsDialog, self).__init__(parent) self.form_layout = QFormLayout(self) self.form_layout.setFormAlignment(Qt.AlignLeft) self.form_layout.setLabelAlignment(Qt.AlignLeft) self.form_layout.setContentsMargins(2, 2, 2, 2) self.setWindowTitle("Highlight Options") check_box_layout = QHBoxLayout() self.timestamp_check = QCheckBox("Timestamp") self.timestamp_check.setChecked(False) self.timestamp_check.stateChanged.connect(self.timestamp_check_change) self.tag_check = QCheckBox("Tag") self.tag_check.setChecked(True) self.func_check = QCheckBox("Function") self.func_check.setChecked(False) self.module_source_check = QCheckBox("Module/Source") self.module_source_check.setChecked(False) check_box_layout.addWidget(self.timestamp_check, alignment=Qt.AlignLeft) check_box_layout.addWidget(self.tag_check, alignment=Qt.AlignLeft) check_box_layout.addWidget(self.func_check, alignment=Qt.AlignLeft) check_box_layout.addWidget(self.module_source_check, alignment=Qt.AlignLeft) highlight_label = QLabel("Highlight Options") self.timestamp_combo = QComboBox() model = self.timestamp_combo.model() for timestamp in LOGGER_TIMESTAMPS: item = QStandardItem(timestamp["name"]) model.appendRow(item) self.timestamp_combo.setCurrentIndex(0) self.timestamp_combo.setEnabled(self.timestamp_check.isChecked()) self.apply_button = QPushButton("Apply") self.apply_button.clicked.connect(self.apply) self.form_layout.addRow(highlight_label) self.form_layout.addRow(check_box_layout) self.form_layout.addRow("TimeStamp Type :", self.timestamp_combo) self.form_layout.addRow(self.apply_button)
def showTable(self): self.totalprice = 0 # 设置表格表头 self.tableView.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch) self.model.clear() self.model.setHorizontalHeaderLabels(self.title) self.tableView.setModel(self.model) # 设置内容 if self.materiallist: for b in self.materiallist: for col in range(3): item = QStandardItem("{}".format(b[col])) self.model.setItem(self.materiallist.index(b), col, item) self.tableView.setModel(self.model) for m in self.materiallist: self.totalprice += m[1] * m[2] self.lineEdit_5.setText("{}".format(self.totalprice))
def _runJob(self): if self._jobCancelled or gVar.app.isClosing(): return if not self._searchString: self._completeMostVisited() else: self._completeFromHistory() # Load all icons into QImage for item in self._items: if self._jobCancelled: return # QUrl url = item.data(LocationCompleterModel.UrlRole) item.setData(IconProvider.imageForUrl(url), LocationCompleterModel.ImageRole) if self._jobCancelled: return # Get domain completion if self._searchString and gVar.appSettings.useInlineCompletion: domainQuery = LocationCompleterModel.createDomainQuery( self._searchString) history = domainQuery.first() if history: self._domainCompletion = QUrl(history.url).host() if self._jobCancelled: return # Add search/visit item if self._searchString: item = QStandardItem() item.setText(self._searchString) item.setData(self._searchString, LocationCompleterModel.UrlRole) item.setData(self._searchString, LocationCompleterModel.SearchStringRole) item.setData(True, LocationCompleterModel.VisitSearchItemRole) if self._domainCompletion: url = QUrl('http://%s' % self._domainCompletion) item.setData(IconProvider.imageForDomain(url), LocationCompleterModel.ImageRole) self._items.insert(0, item)
def get_output_tableitem(item): """ Return centered QTableWidgetItem with output :param item: host or service item :type item: alignak_app.items.host.Host | alignak_app.items.service.Service :return: table item with text :rtype: QStandardItem """ if not item.data['ls_output']: item.data['ls_output'] = 'n\\a' tableitem = QStandardItem(item.data['ls_output']) tableitem.setData(item, Qt.UserRole) tableitem.setTextAlignment(Qt.AlignLeft | Qt.AlignVCenter) return tableitem
def on_open_dir(self): data_dir = QFileDialog.getExistingDirectory(self, "选取文件夹", "./") self.data_dir = data_dir test_data = os.listdir(data_dir) test_data.sort() self.test_data = test_data self.num_data = len(test_data) self.image_ids = list(range(self.num_data)) self.image_id = 0 self.label_img_info.setText("image_id: {}\nname: {}".format( self.image_id, self.test_data[self.image_id])) # 目录树显示 path_data_name = self.model.invisibleRootItem() for i in range(len(test_data)): gos_data = QStandardItem(test_data[i]) path_data_name.setChild(i, gos_data)
def func(): index = self._s_model.index(0, 0) if index.data(LocationCompleterModel.VisitSearchItemRole): self._s_model.setData(index, trimmedStr, Qt.DisplayRole) self._s_model.setData(index, trimmedStr, LocationCompleterModel.UrlRole) self._s_model.setData(index, self._locationBar.text(), LocationCompleterModel.SearchStringRole) else: item = QStandardItem() item.setText(trimmedStr) item.setData(trimmedStr, LocationCompleterModel.UrlRole) item.setData(self._locationBar.text(), LocationCompleterModel.SearchStringRole) item.setData(True, LocationCompleterModel.VisitSearchItemRole) self._s_model.setCompletions([item]) self._addSuggestions(self._oldSuggestions) self._showPopup() if not self._s_view.currentIndex().isValid(): self._ignoreCurrentChanged = True self._s_view.setCurrentIndex(self._s_model.index(0, 0)) self._ignoreCurrentChanged = False
def get_tableitem(self, item): """ Return centered QTableWidgetItem with problem :param item: host or service item :type item: alignak_app.items.host.Host | alignak_app.items.service.Service :return: table item with text :rtype: QStandardItem """ tableitem = QStandardItem(self.get_item_text(item)) tableitem.setData(item, Qt.UserRole) icon = QIcon(settings.get_image( get_icon_name_from_state(item.item_type, item.data['ls_state']) )) tableitem.setIcon(icon) tableitem.setTextAlignment(Qt.AlignLeft | Qt.AlignVCenter) return tableitem
def update_view(self, problems_data): """ Update QTableView model and proxy filter :param problems_data: problems found in database :type problems_data: dict :return: proxy filter to connect with line edit :rtype: QSortFilterProxyModel """ problems_model = QStandardItemModel() problems_model.setRowCount(len(problems_data['problems'])) problems_model.setColumnCount(len(self.headers_list)) if problems_data['problems']: for row, item in enumerate(problems_data['problems']): problems_model.setItem(row, 0, self.get_tableitem(item)) problems_model.setItem(row, 1, self.get_output_tableitem(item)) else: tableitem = QStandardItem('No problem to report.') icon = QIcon(settings.get_image('checked')) tableitem.setIcon(icon) tableitem.setTextAlignment(Qt.AlignCenter) problems_model.setItem(0, 0, tableitem) proxy_filter = QSortFilterProxyModel() proxy_filter.setFilterCaseSensitivity(Qt.CaseInsensitive) proxy_filter.setSourceModel(problems_model) problems_model.setHorizontalHeaderLabels(self.headers_list) self.setModel(proxy_filter) self.setColumnWidth(0, 500) self.setColumnWidth(1, 300) return proxy_filter
def _generate_model(self, account_hierarchy: Node): stack = [account_hierarchy] while stack: account: Node = stack.pop() # push all children stack += sorted(account.children, key=lambda a: a.value, reverse=True) path_of_account = [account] # reach to root while account.parent is not None: path_of_account.append(account.parent) account = account.parent # pop root from path account_seg: Node = path_of_account.pop() # get root of the data model tree_model_node: QStandardItem = self.root_node # append the whole path to data model while path_of_account: account_seg = path_of_account.pop() tree_model_child: QStandardItem = None # find corresponding node in the data model for child_idx in range(tree_model_node.rowCount()): child = tree_model_node.child(child_idx) if child.text() == account_seg.value: tree_model_child = child break # if not found if tree_model_child is None: # append item = QStandardItem(account_seg.value) item.setEditable(False) tree_model_node.appendRow(item) # get the child just appended and proceed tree_model_node = tree_model_node.child( tree_model_node.rowCount() - 1) else: # continue tree_model_node = tree_model_child
def __init__(self, parent=None): super(FilterPanel, self).__init__(parent) self.form_layout = QFormLayout(parent) self.form_layout.setFormAlignment(Qt.AlignLeft) self.form_layout.setLabelAlignment(Qt.AlignLeft) self.form_layout.setContentsMargins(1, 0, 0, 1) self.filter_layout_1 = QHBoxLayout() self.filter_label = QLabel("Filtro :") self.filter_line = QLineEdit() self.log_types = QComboBox() model = self.log_types.model() for tag in LOGGER_TAGS: item = QStandardItem(tag['name']) item.setForeground(QColor(tag['color'])) model.appendRow(item) self.log_types.colorCount() self.log_types.setCurrentText(LOGGER_TAGS[0]["name"]) self.log_types.currentTextChanged.connect(self.get_log_type) self.filter_layout_1.addWidget(self.log_types) self.filter_layout_1.addWidget(self.filter_line) self.filter_layout_2 = QHBoxLayout() self.filter_search_button = QPushButton("Search") self.filter_clear_button = QPushButton("Clear") self.filter_layout_2.addWidget(self.filter_search_button) self.filter_layout_2.addWidget(self.filter_clear_button) self.form_layout.addRow(self.filter_label, self.filter_layout_1) self.form_layout.addRow(self.filter_layout_2)