Python PyQt5.QtCore.Qt 模块,UserRole() 实例源码

我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用PyQt5.QtCore.Qt.UserRole()

项目:pbtk    作者:marin-m    | 项目源码 | 文件源码
def prompt_extractor(self, item):
        extractor = extractors[item.data(Qt.UserRole)]
        inputs = []
        if not assert_installed(self.view, **extractor.get('depends', {})):
            return

        if not extractor.get('pick_url', False):
            files, mime = QFileDialog.getOpenFileNames()
            for path in files:
                inputs.append((path, Path(path).stem))
        else:
            text, good = QInputDialog.getText(self.view, ' ', 'Input an URL:')
            if text:
                url = urlparse(text)
                inputs.append((url.geturl(), url.netloc))

        if inputs:
            wait = QProgressDialog('Extracting .proto structures...', None, 0, 0)
            wait.setWindowTitle(' ')
            self.set_view(wait)

            self.worker = Worker(inputs, extractor)
            self.worker.progress.connect(self.extraction_progress)
            self.worker.finished.connect(self.extraction_done)
            self.worker.start()
项目:continuum    作者:zyantific    | 项目源码 | 文件源码
def update(self):
        # Update files.
        self._ui.project_tree.clear()
        items = []
        icon_provider = QFileIconProvider()

        for cur_file in self.project.files:
            file_info = QFileInfo(cur_file)
            item = QTreeWidgetItem(None, [
                os.path.relpath(cur_file, self.project.proj_dir), 
                "N/A",
            ])
            item.setData(0, Qt.UserRole, Project.file_to_idb(cur_file))
            item.setIcon(0, icon_provider.icon(file_info))
            items.append(item)

        self._ui.project_tree.insertTopLevelItems(0, items)

        # Update other stuff.
        self._ui.project_path.setText(self.project.proj_dir)
项目:pyree-old    作者:DrLuke    | 项目源码 | 文件源码
def selectNode(self, position, inType:type=None, outType:type=None):
        if self.searchAndCompareModules():
            for nodeName in self.availableNodes:
                if self.availableNodes[nodeName].placeable:
                    returnItem = self.checkOrCreateCategory(self.availableNodes[nodeName].Category, self.ui.treeWidget)
                    newItem = QTreeWidgetItem(1002)  # Type 1002 for modules
                    newItem.setText(0, self.availableNodes[nodeName].name)
                    returnItem.addChild(newItem)
                    newItem.setData(1, Qt.UserRole, nodeName)

        self.exec()

        if len(self.ui.treeWidget.selectedItems()) == 1:
            selectedItem = self.ui.treeWidget.selectedItems()[0]
            selectedItem.setSelected(False)
            if selectedItem.data(1, Qt.UserRole) in self.availableNodes:
                classToSpawn = self.availableNodes[selectedItem.data(1, Qt.UserRole)]
                newNode = classToSpawn()
                newNode.sendMessageCallback = self.sendMessageCallback

                if self.scene is not None:
                    self.scene.undostack.push(AddNodeToSceneCommand(newNode, position, self.scene))
项目:bit-torrent    作者:borzunov    | 项目源码 | 文件源码
def _add_torrent_item(self, state: TorrentState):
        widget = TorrentListWidgetItem()
        widget.state = state

        item = QListWidgetItem()
        item.setIcon(file_icon if state.single_file_mode else directory_icon)
        item.setSizeHint(widget.sizeHint())
        item.setData(Qt.UserRole, state.info_hash)

        items_upper = 0
        for i in range(self._list_widget.count()):
            prev_item = self._list_widget.item(i)
            if self._list_widget.itemWidget(prev_item).state.suggested_name > state.suggested_name:
                break
            items_upper += 1
        self._list_widget.insertItem(items_upper, item)

        self._list_widget.setItemWidget(item, widget)
        self._torrent_to_item[state.info_hash] = item
项目:opcua-widgets    作者:FreeOpcUa    | 项目源码 | 文件源码
def _add_ref_row(self, ref):
        if ref.ReferenceTypeId.Identifier in ua.ObjectIdNames:
            typename = ua.ObjectIdNames[ref.ReferenceTypeId.Identifier]
        else:
            typename = str(ref.ReferenceTypeId)
        if ref.NodeId.NamespaceIndex == 0 and ref.NodeId.Identifier in ua.ObjectIdNames:
            nodeid = ua.ObjectIdNames[ref.NodeId.Identifier]
        else:
            nodeid = ref.NodeId.to_string()
        if ref.TypeDefinition.Identifier in ua.ObjectIdNames:
            typedef = ua.ObjectIdNames[ref.TypeDefinition.Identifier]
        else:
            typedef = ref.TypeDefinition.to_string()
        titem = QStandardItem(typename)
        titem.setData(ref, Qt.UserRole)
        self.model.appendRow([
            titem,
            QStandardItem(nodeid),
            QStandardItem(ref.BrowseName.to_string()),
            QStandardItem(typedef)
        ])
项目:opcua-widgets    作者:FreeOpcUa    | 项目源码 | 文件源码
def createEditor(self, parent, option, idx):
        print("CREATE EDITOR", parent, option, idx)
        if idx.column() > 1:
            return None
        data_idx = idx.sibling(idx.row(), 0)
        item = self._widget.model.itemFromIndex(data_idx)
        ref = item.data(Qt.UserRole)
        if idx.column() == 1:
            node = Node(self._widget.node.server, ref.NodeId)
            startnode = Node(self._widget.node.server, ua.ObjectIds.RootFolder)
            button = GetNodeTextButton(parent, node, startnode)
            return button
        elif idx.column() == 0:
            node = Node(self._widget.node.server, ref.ReferenceTypeId)
            startnode = Node(self._widget.node.server, ua.ObjectIds.ReferenceTypesFolder)
            button = GetNodeTextButton(parent, node, startnode)
            return button
项目:opcua-widgets    作者:FreeOpcUa    | 项目源码 | 文件源码
def setModelData(self, editor, model, idx):
        data_idx = idx.sibling(idx.row(), 0)
        ref = model.data(data_idx, Qt.UserRole)
        self._widget.do_remove_ref(ref, check=False)
        if idx.column() == 0:
            ref.ReferenceTypeId = editor.get_node().nodeid
            model.setData(idx, ref.ReferenceTypeId.to_string(), Qt.DisplayRole)
        elif idx.column() == 1:
            ref.NodeId = editor.get_node().nodeid
            ref.NodeClass = editor.get_node().get_node_class()
            model.setData(idx, ref.NodeId.to_string(), Qt.DisplayRole)
        model.setData(data_idx, ref, Qt.UserRole)
        if ref.NodeId.is_null() or ref.ReferenceTypeId.is_null():
            logger.info("Do not save yet. Need NodeId and ReferenceTypeId to be set")
            return
        self._write_ref(ref)
项目:opcua-widgets    作者:FreeOpcUa    | 项目源码 | 文件源码
def expand_to_node(self, node):
        """
        Expand tree until given node and select it
        """
        if isinstance(node, str):
            idxlist = self.model.match(self.model.index(0, 0), Qt.DisplayRole, node, 1, Qt.MatchExactly|Qt.MatchRecursive)
            node = self.model.data(idxlist[0], Qt.UserRole)
        path = node.get_path()
        for node in path:
            # FIXME: this would be the correct way if it would work
            #idxlist = self.model.match(self.model.index(0, 0), Qt.UserRole, QVariantnode, 2, Qt.MatchExactly|Qt.MatchRecursive)
            try:
                text = node.get_display_name().Text
            except UaError as ex:
                return
            idxlist = self.model.match(self.model.index(0, 0), Qt.DisplayRole, text, 1, Qt.MatchExactly|Qt.MatchRecursive)
            if idxlist:
                idx = idxlist[0]
                self.view.setExpanded(idx, True)
                self.view.setCurrentIndex(idx)
                self.view.activated.emit(idx)
项目:pbtk    作者:marin-m    | 项目源码 | 文件源码
def load_extractors(self):
        self.choose_extractor.extractors.clear()

        for name, meta in extractors.items():
            item = QListWidgetItem(meta['desc'], self.choose_extractor.extractors)
            item.setData(Qt.UserRole, name)

        self.set_view(self.choose_extractor)
项目:pbtk    作者:marin-m    | 项目源码 | 文件源码
def new_endpoint(self, path):
        if not self.proto_fs.isDir(path):
            path = self.proto_fs.filePath(path)

            if not getattr(self, 'only_resp_combo', False):
                self.create_endpoint.pbRequestCombo.clear()
            self.create_endpoint.pbRespCombo.clear()

            has_msgs = False
            for name, cls in load_proto_msgs(path):
                has_msgs = True
                if not getattr(self, 'only_resp_combo', False):
                    self.create_endpoint.pbRequestCombo.addItem(name, (path, name))
                self.create_endpoint.pbRespCombo.addItem(name, (path, name))
            if not has_msgs:
                QMessageBox.warning(self.view, ' ', 'There is no message defined in this .proto.')
                return

            self.create_endpoint.reqDataSubform.hide()

            if not getattr(self, 'only_resp_combo', False):
                self.create_endpoint.endpointUrl.clear()
                self.create_endpoint.transports.clear()
                self.create_endpoint.sampleData.clear()
                self.create_endpoint.pbParamKey.clear()
                self.create_endpoint.parsePbCheckbox.setChecked(False)

                for name, meta in transports.items():
                    item = QListWidgetItem(meta['desc'], self.create_endpoint.transports)
                    item.setData(Qt.UserRole, (name, meta.get('ui_data_form')))

            elif getattr(self, 'saved_transport_choice'):
                self.create_endpoint.transports.setCurrentItem(self.saved_transport_choice)
                self.pick_transport(self.saved_transport_choice)
                self.saved_transport_choice = None

            self.only_resp_combo = False
            self.set_view(self.create_endpoint)
项目:pbtk    作者:marin-m    | 项目源码 | 文件源码
def pick_transport(self, item):
        name, desc = item.data(Qt.UserRole)
        self.has_pb_param = desc and 'regular' in desc
        self.create_endpoint.reqDataSubform.show()
        if self.has_pb_param:
            self.create_endpoint.pbParamSubform.show()
        else:
            self.create_endpoint.pbParamSubform.hide()
        self.create_endpoint.sampleDataLabel.setText('Sample request data, one per line (in the form of %s):' % desc)
项目:mnelab    作者:cbrnr    | 项目源码 | 文件源码
def __init__(self, parent, info, title="Channel Properties"):
        super().__init__(parent)
        self.setWindowTitle(title)

        self.model = QStandardItemModel(info["nchan"], 4)
        self.model.setHorizontalHeaderLabels(["#", "Label", "Type", "Bad"])
        for index, ch in enumerate(info["chs"]):
            item = QStandardItem()
            item.setData(index, Qt.DisplayRole)
            item.setFlags(item.flags() & ~Qt.ItemIsEditable)
            self.model.setItem(index, 0, item)
            self.model.setItem(index, 1, QStandardItem(ch["ch_name"]))
            kind = channel_type(info, index).upper()
            self.model.setItem(index, 2, QStandardItem(str(kind)))
            bad = QStandardItem()
            bad.setData(ch["ch_name"] in info["bads"], Qt.UserRole)
            bad.setCheckable(True)
            bad.setEditable(False)
            checked = ch["ch_name"] in info["bads"]
            bad.setCheckState(Qt.Checked if checked else Qt.Unchecked)
            self.model.setItem(index, 3, bad)

        self.model.itemChanged.connect(bad_changed)
        self.proxymodel = MySortFilterProxyModel()
        self.proxymodel.setSourceModel(self.model)

        self.view = QTableView()
        self.view.setModel(self.proxymodel)
        self.view.setItemDelegateForColumn(2, ComboBoxDelegate(self.view))
        self.view.setEditTriggers(QAbstractItemView.AllEditTriggers)
        self.view.verticalHeader().setVisible(False)
        self.view.horizontalHeader().setStretchLastSection(True)
        self.view.setShowGrid(False)
        self.view.setSelectionMode(QAbstractItemView.NoSelection)
        self.view.setSortingEnabled(True)
        self.view.sortByColumn(0, Qt.AscendingOrder)
        self.view.resizeColumnsToContents()
        # for i in range(self.model.rowCount()):
        #         self.view.openPersistentEditor(self.model.index(i, 2))

        vbox = QVBoxLayout(self)
        vbox.addWidget(self.view)
        self.buttonbox = QDialogButtonBox(QDialogButtonBox.Ok |
                                          QDialogButtonBox.Cancel)
        vbox.addWidget(self.buttonbox)
        self.buttonbox.accepted.connect(self.accept)
        self.buttonbox.rejected.connect(self.reject)

        self.resize(400, 650)
项目:mnelab    作者:cbrnr    | 项目源码 | 文件源码
def lessThan(self, left, right):
        left_data = self.sourceModel().data(left)
        right_data = self.sourceModel().data(right)
        if left_data is None:
            left_data = self.sourceModel().data(left, Qt.UserRole)
        if right_data is None:
            right_data = self.sourceModel().data(right, Qt.UserRole)

        return left_data < right_data
项目:mnelab    作者:cbrnr    | 项目源码 | 文件源码
def bad_changed(item):
    if item.checkState() == Qt.Checked:
        item.setData(True, Qt.UserRole)
    else:
        item.setData(False, Qt.UserRole)
项目:continuum    作者:zyantific    | 项目源码 | 文件源码
def OnCreate(self, form):
        self._tform = form
        self._qwidget = self.FormToPyQtWidget(form, sys.modules[__name__])

        # Setup UI.
        self._ui = Ui_ProjectExplorerWidget()
        self._ui.setupUi(self._qwidget)

        # Load icons.
        self._ui.open_project_settings.setIcon(
            QIcon(os.path.join(ui_dir, 'page_gear.png'))
        )
        self._ui.refresh_project_files.setIcon(
            QIcon(os.path.join(ui_dir, 'arrow_refresh.png'))
        )

        # Subscribe events.
        self._ui.open_project_settings.clicked.connect(
            lambda _: self.open_project_settings_clicked.emit()
        )
        self._ui.refresh_project_files.clicked.connect(
            lambda _: self.refresh_project_clicked.emit()
        )
        self._ui.project_tree.itemDoubleClicked.connect(
            lambda item, _: self.focus_instance_clicked.emit(item.data(0, Qt.UserRole))
        )

        self.update()
项目:pyree-old    作者:DrLuke    | 项目源码 | 文件源码
def __init__(self, listItem:QListWidgetItem, propertiesDockWidget:QDockWidget, sendMessageCallback, data=None):
        self.sendMessageCallback = sendMessageCallback
        self.scene = QNodeScene(ModulePickerDialog(sendMessageCallback))
        self.view = QNodeView()
        self.view.setScene(self.scene)
        self.scene.setSceneRect(-2500, -2500, 5000, 5000)   # TODO: Make this less shitty
        self.listItem = listItem
        self.id = self.listItem.data(Qt.UserRole)   # Get ID from the listitem
        self.dockWidget = propertiesDockWidget

        self.availableModules = searchModules()

        self.scene.selectionChanged.connect(self.sceneSelectionChanged)

        self.sheetMap = {}  # key: sheetid, value: sheetname   special thing for subsheets so you can pick a subsheet. FIXME: Make this less special-casey

        # --- Pass scene changes
        self.sceneUndoStackIndexChangedCallback = None
        self.scene.undostack.indexChanged.connect(self.sceneUndoStackIndexChanged)

        self.workerManagerSendNodeData = None

        if data is not None:
            self.deserialize(data)
        else:
            self.initnode = InitNode()
            self.scene.addItem(self.initnode)
            self.loopnode = LoopNode()
            self.scene.addItem(self.loopnode)
            self.loopnode.setPos(QPointF(0, 100))

            self.name = self.listItem.text()
项目:pyree-old    作者:DrLuke    | 项目源码 | 文件源码
def loadFromFile(self, path):
        """Load project from file"""
        self.filePath = path

        with open(path, "r") as f:
            data = json.load(f)

        for sheetdata in data["sheets"]:
            newTreeItem = QListWidgetItem(sheetdata["name"], self.ui.sheetListWidget)
            newTreeItem.setData(Qt.UserRole, sheetdata["uuid"])  # Add some uniquely identifying data to make it hashable


            self.newSheet(newTreeItem, sheetdata)
项目:pyree-old    作者:DrLuke    | 项目源码 | 文件源码
def saveToFile(self, path):
        """Save current project to file"""
        self.filePath = path

        data = {}
        data["sheets"] = []
        for i in range(self.listWidget.count()):
            listItem = self.ui.sheetListWidget.item(i)
            sheetid = listItem.data(Qt.UserRole)
            data["sheets"].append(self.sheets[sheetid].serialize())

        with open(path, "w") as f:
            json.dump(data, f)
项目:pyree-old    作者:DrLuke    | 项目源码 | 文件源码
def newSheet(self, listItem, data=None):
        """Create a new sheet and store it in sheets"""
        listItem.setToolTip(str(listItem.data(Qt.UserRole)))
        newSheet = Sheet(listItem, self.ui.propertiesScrollArea, self.workerManager.sendNodedataToAll, data)
        self.sheets[listItem.data(Qt.UserRole)] = newSheet  # Add sheet to list of sheets
        newSheet.sceneUndoStackIndexChangedCallback = self.workerManager.sheetChangeHook    # Set change-hook
        self.workerManager.sheetChangeHook(newSheet)    # Call hook once manually to set up initial state

        for sheet in self.sheets.values():
            sheet.sheetsChanged(self.sheets)
项目:pyree-old    作者:DrLuke    | 项目源码 | 文件源码
def addSheetPushButtonClicked(self, checked):
        if self.ui.addSheetLineEdit.text():     # If the text field isn't empty
            newTreeItem = QListWidgetItem(self.ui.addSheetLineEdit.text(), self.ui.sheetListWidget)
            newTreeItem.setData(Qt.UserRole, uuid.uuid4().int)  # Add some uniquely identifying data to make it hashable
            self.currentProject.newSheet(newTreeItem)
项目:pyree-old    作者:DrLuke    | 项目源码 | 文件源码
def sheetListWidgetItemChanges(self, item):
        # If the listItem changes, update tab name
        try:
            if self.currentProject is not None:
                tabIndx = self.ui.tabWidget.indexOf(self.currentProject.sheets[item.data(Qt.UserRole)].view)
                if not tabIndx == -1:
                    self.ui.tabWidget.setTabText(tabIndx, item.text())
        except KeyError:
            pass
项目:pyree-old    作者:DrLuke    | 项目源码 | 文件源码
def sheetListWidgetItemClicked(self, item):
        self.currentProject.selectedSheet = item.data(Qt.UserRole)
项目:pyree-old    作者:DrLuke    | 项目源码 | 文件源码
def sheetListWidgetItemDoubleClicked(self, item):
        tabIndx = self.ui.tabWidget.indexOf(self.currentProject.sheets[item.data(Qt.UserRole)].view)
        if tabIndx == -1:   # Widget not found
            tabIndx = self.ui.tabWidget.addTab(self.currentProject.sheets[item.data(Qt.UserRole)].view, item.text())

        self.ui.tabWidget.setCurrentIndex(tabIndx)
项目:pyree-old    作者:DrLuke    | 项目源码 | 文件源码
def updateSheets(self):
        if self.sheets is not None and self.ownsheet is not None:
            self.listSheetItems = {}
            self.listWidget.clear()
            for sheetId in self.sheets:
                if not sheetId == self.ownsheet:
                    newItem = QListWidgetItem(self.sheets[sheetId])
                    newItem.setToolTip(str(sheetId))
                    newItem.setData(Qt.UserRole, sheetId)
                    self.listSheetItems[sheetId] = newItem
                    self.listWidget.addItem(newItem)

                    if sheetId == self.selectedSheet:
                        boldFont = QFont()
                        boldFont.setBold(True)
                        newItem.setFont(boldFont)
项目:MDT    作者:cbclab    | 项目源码 | 文件源码
def __init__(self, controller, parent=None):
        super(TabMapSpecific, self).__init__(parent)
        self.setupUi(self)

        self.map_specific_tab = MapSpecificOptions(controller, self)
        self.mapSpecificOptionsPosition.addWidget(self.map_specific_tab)

        self._controller = controller
        self._controller.model_updated.connect(self.model_updated)

        self.selectedMap.currentIndexChanged.connect(
            lambda ind: self._update_map_specifics(self.selectedMap.itemData(ind, Qt.UserRole)))
项目:MDT    作者:cbclab    | 项目源码 | 文件源码
def model_updated(self, model):
        config = model.get_config()
        map_names = config.maps_to_show

        with blocked_signals(self.selectedMap):
            current_selected = self.selectedMap.currentData(Qt.UserRole)

            self.selectedMap.clear()
            self.selectedMap.addItems(map_names)

            for index, map_name in enumerate(map_names):
                self.selectedMap.setItemData(index, map_name, Qt.UserRole)

                if map_name in config.map_plot_options and config.map_plot_options[map_name].title:
                    title = config.map_plot_options[map_name].title
                    self.selectedMap.setItemData(index, map_name + ' (' + title + ')', Qt.DisplayRole)

            for ind in range(self.selectedMap.count()):
                if self.selectedMap.itemData(ind, Qt.UserRole) == current_selected:
                    self.selectedMap.setCurrentIndex(ind)
                    break

        if self.selectedMap.count():
            self._update_map_specifics(self.selectedMap.currentData(Qt.UserRole))
        else:
            self._update_map_specifics(None)
项目:MDT    作者:cbclab    | 项目源码 | 文件源码
def select_maps_context_menu(self, position):
        global_position = self.general_map_selection.mapToGlobal(position)

        def get_header_action(parent, map_name):
            label = QLabel(map_name)

            font = label.font()
            font.setBold(True)
            label.setFont(font)
            label.setStyleSheet('color: black; margin:5px; margin-left: 15px;')

            action = QWidgetAction(parent)
            action.setDisabled(True)
            action.setDefaultWidget(label)

            return action

        if self.general_map_selection.count():
            row = self.general_map_selection.indexAt(position)
            if row:
                element = self.general_map_selection.item(row.row())
                if element:
                    map_name = element.data(Qt.UserRole)
                    file_path = self._controller.get_model().get_data().get_file_path(map_name)

                    menu = QMenu()
                    menu.addAction(get_header_action(menu, map_name))
                    menu.addSeparator()

                    show_in_folder = menu.addAction('&Show in folder', lambda:
                        QDesktopServices.openUrl(QUrl.fromLocalFile(os.path.dirname(file_path))))
                    if file_path is None:
                        show_in_folder.setEnabled(False)

                    menu.addAction('Use as &mask', lambda: self._controller.apply_action(SetGeneralMask(map_name)))
                    menu.addAction('R&emove', lambda: self._controller.apply_action(
                        NewDataAction(self._controller.get_model().get_data().get_updated(removals=[map_name]))))
                    menu.exec(global_position)
项目:MDT    作者:cbclab    | 项目源码 | 文件源码
def _reorder_maps(self):
        items = [self.general_display_order.item(ind) for ind in range(self.general_display_order.count())]
        map_names = [item.data(Qt.UserRole) for item in items]
        self._controller.apply_action(SetMapsToShow(map_names))
项目:MDT    作者:cbclab    | 项目源码 | 文件源码
def _update_maps_to_show(self):
        current_model = self._controller.get_model()
        map_names = copy.copy(current_model.get_config().maps_to_show)

        for item in [self.general_map_selection.item(ind) for ind in range(self.general_map_selection.count())]:
            map_name = item.data(Qt.UserRole)

            if item.isSelected():
                if map_name not in map_names:
                    self._insert_alphabetically(map_name, map_names)
            else:
                if map_name in map_names:
                    map_names.remove(map_name)

        self._controller.apply_action(SetMapsToShow(map_names))
项目:Milis-Yukleyici    作者:sonakinci41    | 项目源码 | 文件源码
def treeWidgetItemOlustur(self, bolum, kullanim, boyut, format, islev, bolumno):
        item = QTreeWidgetItem()
        item.setText(0, str(bolum))
        item.setText(1, str(kullanim))
        item.setText(2, str(boyut) + " GB ")
        item.setText(3, str(format))
        item.setData(0,Qt.UserRole, bolumno)
        return item
项目:Milis-Yukleyici    作者:sonakinci41    | 项目源码 | 文件源码
def bolumSecildiFonk(self, tiklanan):
        if tiklanan.data(0,Qt.UserRole) != "ayrilmamis":
            self.bolumSilBtn.setEnabled(True)
        else:
            self.bolumSilBtn.setEnabled(False)
项目:Milis-Yukleyici    作者:sonakinci41    | 项目源码 | 文件源码
def bolumFormatSecFonk(self, tiklanan):
        if tiklanan.data(0,Qt.UserRole) != "ayrilmamis":
            self.seciliDisk = tiklanan
            diskOzellikPencere = diskOzellikleriSinif(self)
            diskOzellikPencere.exec_()
            if self.sistemDiski[0] != "":
                self.e.milis_ayarlar["disk_bolum"] = self.sistemDiski[0]
                self.e.milis_ayarlar["disk_format"] = self.sistemDiski[1]
            if self.takasDiski[0] != "":
                self.e.milis_ayarlar["disk_takasbolum"] = self.takasDiski[0]
            else:
                self.e.milis_ayarlar["disk_takasbolum"] = ""

            if self.sistemDiski[0] == "":
                pass
            elif self.sistemDiski[0] != "" and self.takasDiski[0] == "":
                QMessageBox.information(self, self.e.d[self.e.s_d]["Bilgi"], self.e.d[self.e.s_d]["Takas Alan? Belirtmediniz Takas alan? ram miktar?n?z?n dü?ük oldu?u durumlarda ram yerine disk kullanarak i?lemlerin devam etmesini sa?lar."])
                self.e.ileri_dugme.setDisabled(False)
                self.bolumListeYenile()
            elif self.sistemDiski[0] != "" and self.takasDiski[0] != "":
                if self.sistemDiski[0] == self.takasDiski[0]:
                    QMessageBox.warning(self, self.e.d[self.e.s_d]["Hata"], self.takasDiski[0] + self.e.d[self.e.s_d][" diskini hem sistem hem takas için seçtiniz. Ayn? diski hem sistem hem takas olarak kullanmazs?n?z."])
                    self.e.ileri_dugme.setDisabled(True)
                else:
                    self.e.ileri_dugme.setDisabled(False)
                    self.bolumListeYenile()
项目:Milis-Yukleyici    作者:sonakinci41    | 项目源码 | 文件源码
def bolumSilFonk(self):
        if self.bolumListeKutu.currentItem().data(0,Qt.UserRole) != "ayrilmamis":
            bolumNo = int(self.bolumListeKutu.currentItem().data(0,Qt.UserRole))
            for bolum in self.e.disk.partitions:
                if bolum.number == bolumNo:
                    try:
                        self.e.disk.deletePartition(bolum)
                        self.bolumListeYenile()
                    except parted.PartitionException:
                        QMessageBox.warning(self, self.e.d[self.e.s_d]["Uyar?"], self.e.d[self.e.s_d]["Lütfen uzat?lm?? bölümleri silmeden önce mant?ksal bölümleri siliniz."])
            self.bolumSilBtn.setDisabled(True)
项目:vidcutter    作者:ozmartian    | 项目源码 | 文件源码
def paint(self, painter: QPainter, option: QStyleOptionViewItem, index: QModelIndex) -> None:
        r = option.rect
        pencolor = Qt.white if self.theme == 'dark' else Qt.black
        if self.parent.isEnabled():
            if option.state & QStyle.State_Selected:
                painter.setBrush(QColor(150, 190, 78, 150))
            elif option.state & QStyle.State_MouseOver:
                painter.setBrush(QColor(227, 212, 232))
                pencolor = Qt.black
            else:
                brushcolor = QColor(79, 85, 87, 175) if self.theme == 'dark' else QColor('#EFF0F1')
                painter.setBrush(Qt.transparent if index.row() % 2 == 0 else brushcolor)
        painter.setPen(Qt.NoPen)
        painter.drawRect(r)
        thumb = QIcon(index.data(Qt.DecorationRole + 1))
        starttime = index.data(Qt.DisplayRole + 1)
        endtime = index.data(Qt.UserRole + 1)
        externalPath = index.data(Qt.UserRole + 2)
        r = option.rect.adjusted(5, 0, 0, 0)
        thumb.paint(painter, r, Qt.AlignVCenter | Qt.AlignLeft)
        painter.setPen(QPen(pencolor, 1, Qt.SolidLine))
        r = option.rect.adjusted(110, 8, 0, 0)
        painter.setFont(QFont('Noto Sans UI', 10 if sys.platform == 'darwin' else 8, QFont.Bold))
        painter.drawText(r, Qt.AlignLeft, 'FILENAME' if len(externalPath) else 'START')
        r = option.rect.adjusted(110, 20, 0, 0)
        painter.setFont(QFont('Noto Sans UI', 11 if sys.platform == 'darwin' else 9, QFont.Normal))
        if len(externalPath):
            painter.drawText(r, Qt.AlignLeft, self.clipText(os.path.basename(externalPath), painter))
        else:
            painter.drawText(r, Qt.AlignLeft, starttime)
        if len(endtime) > 0:
            r = option.rect.adjusted(110, 45, 0, 0)
            painter.setFont(QFont('Noto Sans UI', 10 if sys.platform == 'darwin' else 8, QFont.Bold))
            painter.drawText(r, Qt.AlignLeft, 'RUNTIME' if len(externalPath) else 'END')
            r = option.rect.adjusted(110, 60, 0, 0)
            painter.setFont(QFont('Noto Sans UI', 11 if sys.platform == 'darwin' else 9, QFont.Normal))
            painter.drawText(r, Qt.AlignLeft, endtime)
        if self.parent.verticalScrollBar().isVisible():
            self.parent.setFixedWidth(210)
        else:
            self.parent.setFixedWidth(190)
项目:TrezorSymmetricFileEncryption    作者:8go    | 项目源码 | 文件源码
def __init__(self, deviceMap):
        """
        Create dialog and fill it with labels from deviceMap

        @param deviceMap: dict device string -> device label
        """
        QDialog.__init__(self)
        self.setupUi(self)

        for deviceStr, label in deviceMap.items():
            item = QListWidgetItem(label)
            item.setData(Qt.UserRole, QVariant(deviceStr))
            self.trezorList.addItem(item)
        self.trezorList.setCurrentRow(0)
项目:TrezorSymmetricFileEncryption    作者:8go    | 项目源码 | 文件源码
def chosenDeviceStr(self):
        """
        Returns device string of chosen Trezor
        in Py3: must return str, i.e. bytes; not unicode!
        """
        itemData = self.trezorList.currentItem().data(Qt.UserRole)
        deviceStr = encoding.tobytes(itemData)
        return deviceStr
项目:opcua-modeler    作者:FreeOpcUa    | 项目源码 | 文件源码
def paint(self, painter, option, idx):
        new_idx = idx.sibling(idx.row(), 0)
        item = self.model.itemFromIndex(new_idx)
        if item and item.data(Qt.UserRole) in self.added_node_list:
            option.font.setWeight(QFont.Bold)
        QStyledItemDelegate.paint(self, painter, option, idx)
项目:deen    作者:takeshixx    | 项目源码 | 文件源码
def _process_row(self, y, row):
        cols = self.columnCount()
        for x, i in enumerate(range(0, len(row), self._width)):
            block = row[i:i+self._width]
            item = QTableWidgetItem(codecs.encode(block, 'hex').decode())
            item.setBackground(QBrush(QColor('lightgray')))
            item.setForeground(QBrush(QColor('black')))
            item.setTextAlignment(Qt.AlignHCenter | Qt.AlignVCenter)
            item.setData(Qt.UserRole, block)  # store original data
            if self._read_only:
                item.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEnabled)
            else:
                item.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEnabled | Qt.ItemIsEditable)
            self.setItem(y, x, item)

        # process remaining, unfilled cells
        for j in range(x+1, cols):
            item = QTableWidgetItem()
            item.setBackground(QBrush(QColor('white')))
            item.setFlags(Qt.NoItemFlags)
            item.setTextAlignment(Qt.AlignHCenter)
            self.setItem(y, j, item)

        text = self._bytes_to_ascii(row)
        item = QTableWidgetItem(text)
        item.setData(Qt.UserRole, row)  # store original data
        item.setTextAlignment(Qt.AlignLeft| Qt.AlignVCenter)
        item.setBackground(QBrush(QColor('lightblue')))
        item.setForeground(QBrush(QColor('black')))
        if self._read_only:
            item.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEnabled)
        else:
            item.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEnabled | Qt.ItemIsEditable)
        self.setItem(y, cols - 1, item)
项目:deen    作者:takeshixx    | 项目源码 | 文件源码
def _item_changed(self, item):
        def reset_hex_text(orig_data):
            text = codecs.encode(orig_data, 'hex').decode()
            item.setText(text)
        col = item.column()
        row = item.row()
        text = item.text()
        orig_data = item.data(Qt.UserRole)
        offset = row * self._bytes_per_line
        if col != self.columnCount() - 1:  # hex part
            text = text.strip()
            fmt = "{{:>0{}}}".format(self._width * 2)
            text = fmt.format(text)
            if len(text) != self._width * 2:
                reset_hex_text(orig_data)
                return
            offset += col * self._width
            try:
                value = codecs.decode(text, 'hex')
            except ValueError:
                reset_hex_text(orig_data)
                return
        else:  # ascii part
            if len(orig_data) != len(text):
                text = self._bytes_to_ascii(orig_data)
                item.setText(text)
                return
            value = bytearray()
            for a, b in zip(orig_data, text.encode()):
                if b == b'.'[0]:
                    value.append(a)
                else:
                    value.append(b)
        self._data[offset:offset+len(value)] = value
        self.bytesChanged.emit()
        self._reconstruct_table()
项目:Mac-Python-3.X    作者:L1nwatch    | 项目源码 | 文件源码
def changeIcon(self):
        icon = QIcon()

        for row in range(self.imagesTable.rowCount()):
            item0 = self.imagesTable.item(row, 0)
            item1 = self.imagesTable.item(row, 1)
            item2 = self.imagesTable.item(row, 2)

            if item0.checkState() == Qt.Checked:
                if item1.text() == "Normal":
                    mode = QIcon.Normal
                elif item1.text() == "Active":
                    mode = QIcon.Active
                elif item1.text() == "Disabled":
                    mode = QIcon.Disabled
                else:
                    mode = QIcon.Selected

                if item2.text() == "On":
                    state = QIcon.On
                else:
                    state = QIcon.Off

                fileName = item0.data(Qt.UserRole)
                image = QImage(fileName)
                if not image.isNull():
                    icon.addPixmap(QPixmap.fromImage(image), mode, state)

        self.previewArea.setIcon(icon)
项目:Mac-Python-3.X    作者:L1nwatch    | 项目源码 | 文件源码
def addImage(self):
        fileNames, _ = QFileDialog.getOpenFileNames(self, "Open Images", '',
                "Images (*.png *.xpm *.jpg);;All Files (*)")

        for fileName in fileNames:
            row = self.imagesTable.rowCount()
            self.imagesTable.setRowCount(row + 1)

            imageName = QFileInfo(fileName).baseName()
            item0 = QTableWidgetItem(imageName)
            item0.setData(Qt.UserRole, fileName)
            item0.setFlags(item0.flags() & ~Qt.ItemIsEditable)

            item1 = QTableWidgetItem("Normal")
            item2 = QTableWidgetItem("Off")

            if self.guessModeStateAct.isChecked():
                if '_act' in fileName:
                    item1.setText("Active")
                elif '_dis' in fileName:
                    item1.setText("Disabled")
                elif '_sel' in fileName:
                    item1.setText("Selected")

                if '_on' in fileName:
                    item2.setText("On")

            self.imagesTable.setItem(row, 0, item0)
            self.imagesTable.setItem(row, 1, item1)
            self.imagesTable.setItem(row, 2, item2)
            self.imagesTable.openPersistentEditor(item1)
            self.imagesTable.openPersistentEditor(item2)

            item0.setCheckState(Qt.Checked)
项目:examples    作者:pyqt    | 项目源码 | 文件源码
def changeIcon(self):
        icon = QIcon()

        for row in range(self.imagesTable.rowCount()):
            item0 = self.imagesTable.item(row, 0)
            item1 = self.imagesTable.item(row, 1)
            item2 = self.imagesTable.item(row, 2)

            if item0.checkState() == Qt.Checked:
                if item1.text() == "Normal":
                    mode = QIcon.Normal
                elif item1.text() == "Active":
                    mode = QIcon.Active
                elif item1.text() == "Disabled":
                    mode = QIcon.Disabled
                else:
                    mode = QIcon.Selected

                if item2.text() == "On":
                    state = QIcon.On
                else:
                    state = QIcon.Off

                fileName = item0.data(Qt.UserRole)
                image = QImage(fileName)
                if not image.isNull():
                    icon.addPixmap(QPixmap.fromImage(image), mode, state)

        self.previewArea.setIcon(icon)
项目:examples    作者:pyqt    | 项目源码 | 文件源码
def addImage(self):
        fileNames, _ = QFileDialog.getOpenFileNames(self, "Open Images", '',
                "Images (*.png *.xpm *.jpg);;All Files (*)")

        for fileName in fileNames:
            row = self.imagesTable.rowCount()
            self.imagesTable.setRowCount(row + 1)

            imageName = QFileInfo(fileName).baseName()
            item0 = QTableWidgetItem(imageName)
            item0.setData(Qt.UserRole, fileName)
            item0.setFlags(item0.flags() & ~Qt.ItemIsEditable)

            item1 = QTableWidgetItem("Normal")
            item2 = QTableWidgetItem("Off")

            if self.guessModeStateAct.isChecked():
                if '_act' in fileName:
                    item1.setText("Active")
                elif '_dis' in fileName:
                    item1.setText("Disabled")
                elif '_sel' in fileName:
                    item1.setText("Selected")

                if '_on' in fileName:
                    item2.setText("On")

            self.imagesTable.setItem(row, 0, item0)
            self.imagesTable.setItem(row, 1, item1)
            self.imagesTable.setItem(row, 2, item2)
            self.imagesTable.openPersistentEditor(item1)
            self.imagesTable.openPersistentEditor(item2)

            item0.setCheckState(Qt.Checked)
项目:bit-torrent    作者:borzunov    | 项目源码 | 文件源码
def _control_action_triggered(self, action):
        for item in self._list_widget.selectedItems():
            widget = self._list_widget.itemWidget(item)
            if widget.waiting_control_action:
                continue

            info_hash = item.data(Qt.UserRole)
            asyncio.run_coroutine_threadsafe(MainWindow._invoke_control_action(action, info_hash),
                                             self._control_thread.loop)
            widget.waiting_control_action = True

        self._update_control_action_state()
项目:OpenTutorials_PyQt    作者:RavenKyu    | 项目源码 | 文件源码
def data(self, QModelIndex, role=None):
        data = self.itemData(QModelIndex)
        if role == Qt.DisplayRole:
            return "%s" % (data[role])
        elif role in data and role == Qt.DecorationRole:
            return QPixmap(data[role]).scaledToHeight(25)
        elif role == Qt.UserRole:
            print(data[role])
        return QVariant()
项目:OpenTutorials_PyQt    作者:RavenKyu    | 项目源码 | 文件源码
def data(self, QModelIndex, role=None):
        data = self.itemData(QModelIndex)
        if role == Qt.DisplayRole:
            return "%s" % (data[role])
        elif role == Qt.UserRole:
            print(data[role])
        return QVariant()
项目:OpenTutorials_PyQt    作者:RavenKyu    | 项目源码 | 文件源码
def slot_change_format(self, idx):
        # ????? ?? ???
        # ????? ??, ??, ??? ???
        # ?? ?? ???
        # ???? ?????? ???
        self.le.clear()
        self.le.setCursorPosition(0)
        self.le.setInputMask(self.cb.itemData(idx, Qt.UserRole))
        self.lb.clear()
        self.le.setFocus()
项目:opcua-widgets    作者:FreeOpcUa    | 项目源码 | 文件源码
def _item_collapsed(self, idx):
        it = self.model.itemFromIndex(idx.sibling(0, 1))
        data = it.data(Qt.UserRole)
        it.setText(val_to_string(data.value))
项目:opcua-widgets    作者:FreeOpcUa    | 项目源码 | 文件源码
def _show_attr(self, attr, dv):
        if attr == ua.AttributeIds.DataType:
            string = data_type_to_string(dv.Value.Value)
        elif attr in (ua.AttributeIds.AccessLevel,
                      ua.AttributeIds.UserAccessLevel,
                      ua.AttributeIds.WriteMask,
                      ua.AttributeIds.UserWriteMask,
                      ua.AttributeIds.EventNotifier):
            string = enum_to_string(attr, dv.Value.Value)
        else:
            string = val_to_string(dv.Value.Value)
        name_item = QStandardItem(attr.name)
        vitem = QStandardItem(string)
        vitem.setData(AttributeData(attr, dv.Value.Value, dv.Value.VariantType), Qt.UserRole)
        self.model.appendRow([name_item, vitem, QStandardItem(dv.Value.VariantType.name)])
项目:opcua-widgets    作者:FreeOpcUa    | 项目源码 | 文件源码
def _show_value_attr(self, attr, dv):
        name_item = QStandardItem("Value")
        vitem = QStandardItem()
        items = self._show_val(name_item, None, "Value", dv.Value.Value, dv.Value.VariantType)
        items[1].setData(AttributeData(attr, dv.Value.Value, dv.Value.VariantType), Qt.UserRole)
        row = [name_item, vitem, QStandardItem(dv.Value.VariantType.name)]
        self.model.appendRow(row)
        self._show_timestamps(name_item, dv)