当前位置: 首页>>代码示例>>Python>>正文


Python QTreeWidget.clear方法代码示例

本文整理汇总了Python中PyQt5.QtWidgets.QTreeWidget.clear方法的典型用法代码示例。如果您正苦于以下问题:Python QTreeWidget.clear方法的具体用法?Python QTreeWidget.clear怎么用?Python QTreeWidget.clear使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在PyQt5.QtWidgets.QTreeWidget的用法示例。


在下文中一共展示了QTreeWidget.clear方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: MemUsageDialog

# 需要导入模块: from PyQt5.QtWidgets import QTreeWidget [as 别名]
# 或者: from PyQt5.QtWidgets.QTreeWidget import clear [as 别名]
class MemUsageDialog(QDialog):
    def __init__(self, parent=None, update=True):
        QDialog.__init__(self, parent=parent)
        layout = QVBoxLayout()
        self.tree = QTreeWidget()
        layout.addWidget(self.tree)
        self.setLayout(layout)

        self._mgr = CacheMemoryManager()

        self._tracked_caches = {}

        # tree setup code
        self.tree.setHeaderLabels(
            ["cache", "memory", "roi", "dtype", "type", "info", "id"])
        self._idIndex = self.tree.columnCount() - 1
        self.tree.setColumnHidden(self._idIndex, True)
        self.tree.setSortingEnabled(True)
        self.tree.clear()

        self._root = TreeNode()

        # refresh every x seconds (see showEvent())
        self.timer = QTimer(self)
        if update:
            self.timer.timeout.connect(self._updateReport)

    def _updateReport(self):
        # we keep track of dirty reports so we just have to update the tree
        # instead of reconstructing it
        reports = []
        for c in self._mgr.getFirstClassCaches():
            r = MemInfoNode()
            c.generateReport(r)
            reports.append(r)
        self._root.handleChildrenReports(
            reports, root=self.tree.invisibleRootItem())

    def hideEvent(self, event):
        self.timer.stop()

    def showEvent(self, show):
        # update once so we don't have to wait for initial report
        self._updateReport()
        # update every 5 sec.
        self.timer.start(5*1000)
开发者ID:DerThorsten,项目名称:ilastik,代码行数:48,代码来源:memUsageDialog.py

示例2: ErrorsTree

# 需要导入模块: from PyQt5.QtWidgets import QTreeWidget [as 别名]
# 或者: from PyQt5.QtWidgets.QTreeWidget import clear [as 别名]
class ErrorsTree(QWidget):

    def __init__(self, parent=None):
        super().__init__(parent)
        IDE.register_service("errors_tree", self)
        box = QVBoxLayout(self)
        box.setContentsMargins(0, 0, 0, 0)
        self._tree = QTreeWidget()
        self._tree.header().setHidden(True)
        self._tree.setAnimated(True)
        box.addWidget(self._tree)

    def refresh(self, errors, path):
        self._tree.clear()
        parent = QTreeWidgetItem(self._tree, [path])
        for lineno, msg in errors.items():
            item = QTreeWidgetItem(parent, [msg])
            self._tree.addTopLevelItem(item)

    def display_name(self):
        return 'Errors'
开发者ID:ninja-ide,项目名称:ninja-ide,代码行数:23,代码来源:errors_tree.py

示例3: Results

# 需要导入模块: from PyQt5.QtWidgets import QTreeWidget [as 别名]
# 或者: from PyQt5.QtWidgets.QTreeWidget import clear [as 别名]
class Results(QWidget):

    """Show results of occurrences in files inside the tools dock."""

    def __init__(self, parent):
        super(Results, self).__init__(parent)
        self._parent = parent
        vbox = QVBoxLayout(self)
        self._tree = QTreeWidget()
        self._tree.setHeaderLabels((translations.TR_CONTENT,
            translations.TR_FILE, translations.TR_LINE))
        self._tree.header().setHorizontalScrollMode(
            QAbstractItemView.ScrollPerPixel)
        self._tree.header().setSectionResizeMode(0, QHeaderView.ResizeToContents)
        self._tree.header().setSectionResizeMode(1, QHeaderView.ResizeToContents)
        self._tree.header().setSectionResizeMode(2, QHeaderView.ResizeToContents)
        self._tree.header().setStretchLastSection(True)
        self._tree.sortByColumn(1, Qt.AscendingOrder)

        vbox.addWidget(self._tree)

        #Signals
        self._tree.itemActivated['QTreeWidgetItem*', int].connect(self._open_result)
        self._tree.itemClicked['QTreeWidgetItem*', int].connect(self._open_result)

    def _open_result(self, item, col):
        """Get the data of the selected item and open the file."""
        filename = item.toolTip(1)
        line = int(item.text(2)) - 1
        main_container = IDE.get_service('main_container')
        if main_container:
            main_container.open_file(filename=filename, line=line)
        self._parent.hide()

    def update_result(self, items):
        """Update the result tree with the new items."""
        self._tree.clear()
        for i in items:
            item = QTreeWidgetItem(self._tree, (i[3], i[0], str(i[2] + 1)))
            item.setToolTip(1, i[1])
开发者ID:Salmista-94,项目名称:Ninja_3.0_PyQt5,代码行数:42,代码来源:results.py

示例4: DebugViewer

# 需要导入模块: from PyQt5.QtWidgets import QTreeWidget [as 别名]
# 或者: from PyQt5.QtWidgets.QTreeWidget import clear [as 别名]

#.........这里部分代码省略.........
        
        self.debugServer.clientStack.connect(self.handleClientStack)
        
        self.__autoViewSource = Preferences.getDebugger("AutoViewSourceCode")
        self.sourceButton.setVisible(not self.__autoViewSource)
        
    def preferencesChanged(self):
        """
        Public slot to handle the preferencesChanged signal.
        """
        self.__autoViewSource = Preferences.getDebugger("AutoViewSourceCode")
        self.sourceButton.setVisible(not self.__autoViewSource)
        
    def setDebugger(self, debugUI):
        """
        Public method to set a reference to the Debug UI.
        
        @param debugUI reference to the DebugUI object (DebugUI)
        """
        self.debugUI = debugUI
        self.debugUI.clientStack.connect(self.handleClientStack)
        self.callStackViewer.setDebugger(debugUI)
        
    def handleResetUI(self):
        """
        Public method to reset the SBVviewer.
        """
        self.globalsViewer.handleResetUI()
        self.localsViewer.handleResetUI()
        self.__setGlobalsFilter()
        self.__setLocalsFilter()
        self.sourceButton.setEnabled(False)
        self.currentStack = None
        self.stackComboBox.clear()
        self.__threadList.clear()
        if self.embeddedShell:
            self.__tabWidget.setCurrentWidget(self.shellAssembly)
        else:
            if self.embeddedBrowser:
                self.__tabWidget.setCurrentWidget(self.browser)
            else:
                self.__tabWidget.setCurrentWidget(self.glvWidget)
        self.breakpointViewer.handleResetUI()
        
    def handleRawInput(self):
        """
        Public slot to handle the switch to the shell in raw input mode.
        """
        if self.embeddedShell:
            self.saveCurrentPage()
            self.__tabWidget.setCurrentWidget(self.shellAssembly)
        
    def initCallStackViewer(self, projectMode):
        """
        Public method to initialize the call stack viewer.
        
        @param projectMode flag indicating to enable the project mode (boolean)
        """
        self.callStackViewer.clear()
        self.callStackViewer.setProjectMode(projectMode)
        
    def isCallTraceEnabled(self):
        """
        Public method to get the state of the call trace function.
        
        @return flag indicating the state of the call trace function (boolean)
开发者ID:Darriall,项目名称:eric,代码行数:70,代码来源:DebugViewer.py

示例5: SqlConnectionWidget

# 需要导入模块: from PyQt5.QtWidgets import QTreeWidget [as 别名]
# 或者: from PyQt5.QtWidgets.QTreeWidget import clear [as 别名]
class SqlConnectionWidget(QWidget):
    """
    Class implementing a widget showing the SQL connections.
    
    @signal tableActivated(str) emitted after the entry for a table has been
        activated
    @signal schemaRequested(str) emitted when the schema display is requested
    @signal cleared() emitted after the connection tree has been cleared
    """
    tableActivated = pyqtSignal(str)
    schemaRequested = pyqtSignal(str)
    cleared = pyqtSignal()
    
    def __init__(self, parent=None):
        """
        Constructor
        
        @param parent reference to the parent widget (QWidget)
        """
        super(SqlConnectionWidget, self).__init__(parent)
        
        layout = QVBoxLayout(self)
        layout.setContentsMargins(0, 0, 0, 0)
        
        self.__connectionTree = QTreeWidget(self)
        self.__connectionTree.setObjectName("connectionTree")
        self.__connectionTree.setHeaderLabels([self.tr("Database")])
        if qVersion() >= "5.0.0":
            self.__connectionTree.header().setSectionResizeMode(
                QHeaderView.Stretch)
        else:
            self.__connectionTree.header().setResizeMode(QHeaderView.Stretch)
        refreshAction = QAction(self.tr("Refresh"), self.__connectionTree)
        self.__schemaAction = QAction(
            self.tr("Show Schema"), self.__connectionTree)
        
        refreshAction.triggered.connect(self.refresh)
        self.__schemaAction.triggered.connect(self.showSchema)
        
        self.__connectionTree.addAction(refreshAction)
        self.__connectionTree.addAction(self.__schemaAction)
        self.__connectionTree.setContextMenuPolicy(Qt.ActionsContextMenu)
        
        layout.addWidget(self.__connectionTree)
        
        self.__activating = False
        
        self.__connectionTree.itemActivated.connect(self.__itemActivated)
        self.__connectionTree.currentItemChanged.connect(
            self.__currentItemChanged)
        
        self.__activeDb = ""
    
    def refresh(self):
        """
        Public slot to refresh the connection tree.
        """
        self.__connectionTree.clear()
        self.cleared.emit()
        
        connectionNames = QSqlDatabase.connectionNames()
        
        foundActiveDb = False
        for name in connectionNames:
            root = QTreeWidgetItem(self.__connectionTree)
            db = QSqlDatabase.database(name, False)
            root.setText(0, self.__dbCaption(db))
            if name == self.__activeDb:
                foundActiveDb = True
                self.__setActive(root)
            if db.isOpen():
                tables = db.tables()
                for table in tables:
                    itm = QTreeWidgetItem(root)
                    itm.setText(0, table)
        
        if not foundActiveDb and connectionNames:
            self.__activeDb = connectionNames[0]
            self.__setActive(self.__connectionTree.topLevelItem(0))
    
    def showSchema(self):
        """
        Public slot to show schema data of a database.
        """
        cItm = self.__connectionTree.currentItem()
        if cItm is None or cItm.parent() is None:
            return
        self.__setActive(cItm.parent())
        self.schemaRequested.emit(cItm.text(0))
    
    def __itemActivated(self, itm, column):
        """
        Private slot handling the activation of an item.
        
        @param itm reference to the item (QTreeWidgetItem)
        @param column column that was activated (integer)
        """
        if itm is None:
            return
        
#.........这里部分代码省略.........
开发者ID:pycom,项目名称:EricShort,代码行数:103,代码来源:SqlConnectionWidget.py

示例6: SessionsManager

# 需要导入模块: from PyQt5.QtWidgets import QTreeWidget [as 别名]
# 或者: from PyQt5.QtWidgets.QTreeWidget import clear [as 别名]
class SessionsManager(QDialog):
    """Session Manager, to load different configurations of ninja."""

    def __init__(self, parent=None):
        super(SessionsManager, self).__init__(parent, Qt.Dialog)
        self._ninja = parent
        self.setModal(True)
        self.setWindowTitle(translations.TR_SESSIONS_TITLE)
        self.setMinimumWidth(550)
        self.setMinimumHeight(450)
        self._manager = _SessionManager(parent)
        self._load_ui()

    def install(self):
        self._manager.load_sessions()

    def _load_ui(self):
        main_layout = QVBoxLayout(self)
        main_layout.addWidget(QLabel(translations.TR_SESSIONS_DIALOG_BODY))
        main_hbox = QHBoxLayout()
        # Session list
        session_layout = QVBoxLayout()
        self._session_list = QTreeWidget()
        self._session_list.setHeaderLabels(["Session", "Last Modified"])
        session_layout.addWidget(self._session_list)
        # Content frame
        content_frame = QFrame()
        content_frame.hide()
        frame_layout = QVBoxLayout(content_frame)
        content_frame.setFrameStyle(QFrame.StyledPanel | QFrame.Sunken)
        session_layout.addWidget(content_frame)
        frame_layout.setContentsMargins(0, 0, 0, 0)
        self._content_list = QTreeWidget()
        self._content_list.setHeaderHidden(True)
        frame_layout.addWidget(self._content_list)
        # Separator line
        line_frame = QFrame()
        line_frame.setFrameStyle(QFrame.VLine | QFrame.Sunken)
        # Buttons
        btn_layout = QVBoxLayout()
        btn_create = QPushButton(translations.TR_SESSIONS_BTN_CREATE)
        btn_activate = QPushButton(translations.TR_SESSIONS_BTN_ACTIVATE)
        btn_update = QPushButton(translations.TR_SESSIONS_BTN_UPDATE)
        btn_delete = QPushButton(translations.TR_SESSIONS_BTN_DELETE)
        btn_details = QPushButton(translations.TR_SESSIONS_BTN_DETAILS)
        btn_details.setCheckable(True)
        # Add buttons to layout
        btn_layout.addWidget(btn_create)
        btn_layout.addWidget(btn_activate)
        btn_layout.addWidget(btn_update)
        btn_layout.addWidget(btn_delete)
        btn_layout.addStretch()
        btn_layout.addWidget(btn_details)
        # Add widgets and layouts to the main layout
        main_layout.addLayout(main_hbox)
        main_hbox.addLayout(session_layout)
        main_hbox.addWidget(line_frame)
        main_hbox.addLayout(btn_layout)
        main_hbox.setSizeConstraint(QLayout.SetFixedSize)
        btn_details.toggled[bool].connect(content_frame.setVisible)
        # Connections
        self._session_list.itemSelectionChanged.connect(
            self.load_session_content)
        btn_activate.clicked.connect(self.open_session)
        btn_update.clicked.connect(self.save_session)
        btn_create.clicked.connect(self.create_session)
        btn_delete.clicked.connect(self.delete_session)

    def __load_sessions(self):
        for session_name in self._manager.sessions:
            item = QTreeWidgetItem()
            item.setText(0, session_name)
            item.setText(1, "FIXME: manage this!")
            self._session_list.addTopLevelItem(item)
        self._session_list.setCurrentItem(
            self._session_list.topLevelItem(0))

    def load_session_content(self):
        """Load the selected session, replacing the current session."""
        item = self._session_list.currentItem()
        self._content_list.clear()
        if item is not None:
            key = item.text(0)
            files, projects = self._manager.get_session(key)
            files_parent = QTreeWidgetItem(
                self._content_list, [translations.TR_FILES])
            for ffile in files:
                QTreeWidgetItem(files_parent, [ffile[0]])
            projects_parent = QTreeWidgetItem(
                self._content_list, [translations.TR_PROJECT])
            for project in projects:
                QTreeWidgetItem(projects_parent, [project])

            files_parent.setExpanded(True)
            projects_parent.setExpanded(True)

    def create_session(self):
        """Create a new Session."""
        session_info = QInputDialog.getText(
            None, translations.TR_SESSIONS_CREATE_TITLE,
#.........这里部分代码省略.........
开发者ID:ninja-ide,项目名称:ninja-ide,代码行数:103,代码来源:session_manager.py

示例7: NodeSelector

# 需要导入模块: from PyQt5.QtWidgets import QTreeWidget [as 别名]
# 或者: from PyQt5.QtWidgets.QTreeWidget import clear [as 别名]
class NodeSelector(QDialog):
    """ Popup window for creating new nodes """
    def __init__(self, moduleManager, modfilter={}):
        super().__init__()

        self.modMan = moduleManager
        self.modfilter = modfilter

        self.gridLayout = QGridLayout(self)

        self.lineEdit = QLineEdit()
        self.lineEdit.textChanged.connect(self.textChanged)
        self.gridLayout.addWidget(self.lineEdit, 0, 0, 1, 1)

        self.treeWidget = QTreeWidget()
        self.treeWidget.itemActivated.connect(self.itemActivated)
        self.gridLayout.addWidget(self.treeWidget, 1, 0, 1, 1)

        self.data = {"node": None, "pin": None}

        self.rebuildTree()



    def rebuildTree(self):
        # Fill Tree with items
        ## Find all available Categories
        self.treeWidget.clear()
        self.categories = []
        for key in self.modMan.availableNodes:
            if self.modMan.availableNodes[key].placable and self.filterModule(self.modMan.availableNodes[key]):
                self.categories.append(self.modMan.availableNodes[key].category)
        self.categories = list(set(self.categories))  # Make list unique

        self.categoryTreeitems = {}
        for category in self.categories:
            newTreeitem = QTreeWidgetItem()
            newTreeitem.setText(0, category)
            self.treeWidget.addTopLevelItem(newTreeitem)

            self.categoryTreeitems[category] = newTreeitem

        self.moduleDict = {}
        for key in self.modMan.availableNodes:
            if self.modMan.availableNodes[key].placable and self.filterModule(self.modMan.availableNodes[key]): # Todo: Could reuse previous results if performance becomes critical
                newTreeitem = QTreeWidgetItem()
                newTreeitem.setText(0, self.modMan.availableNodes[key].name)
                newTreeitem.setToolTip(0, self.modMan.availableNodes[key].desc)
                self.categoryTreeitems[self.modMan.availableNodes[key].category].addChild(newTreeitem)

                self.moduleDict[key] = newTreeitem

        for key in self.categoryTreeitems:
            self.categoryTreeitems[key].setExpanded(True)


    def filterModule(self, module):
        ratio = 0
        compatibleType = False
        if "type" in self.modfilter:
            if self.modfilter["type"]["dir"] == "input":
                for input in module.inputDefs:
                    if input.pintype == self.modfilter["type"]["type"]:
                        compatibleType = True
                        break
            elif self.modfilter["type"]["dir"] == "output":
                for output in module.outputDefs:
                    if output.pintype == self.modfilter["type"]["type"]:
                        compatibleType = True
                        break

            if not compatibleType:
                return False

        if "text" in self.modfilter:    # Filter by text input
            if self.modfilter["text"] in module.name:
                return True
            if not self.modfilter["text"]:  # Text entry is empty
                return True
            ratio = fuzz.ratio(self.modfilter["text"], module.name)
            ratio = max(ratio, fuzz.partial_ratio(self.modfilter["text"], module.desc))
        else:
            return True     # Don't filter by text? Return all remaining

        if ratio > 40:
            return True
        else:
            return False

    def textChanged(self, newText):
        self.modfilter["text"] = newText
        self.rebuildTree()

    def itemActivated(self, item, column):
        for key in self.moduleDict:
            if self.moduleDict[key] == item:

                if "type" in self.modfilter:
                    if self.modfilter["type"]["dir"] == "input":
                        for input in self.modMan.availableNodes[key].inputDefs:
#.........这里部分代码省略.........
开发者ID:DrLuke,项目名称:gpnshader,代码行数:103,代码来源:sheetview.py

示例8: MainWindow

# 需要导入模块: from PyQt5.QtWidgets import QTreeWidget [as 别名]
# 或者: from PyQt5.QtWidgets.QTreeWidget import clear [as 别名]

#.........这里部分代码省略.........
        # newer API2 for PyQt. (PyQt on python 3 uses API2 by default.)
        # more here: http://srinikom.github.io/pyside-bz-archive/343.html
        # so perhaps we keep our current hack for now?
        # -- Jackson Lee, 2015/08/24

        if fname and any(fname) and (type(fname) is tuple):
            return fname[0]
        else:
            # if this hack isn't needed somehow...
            return fname

    def corpus_dir_dialog(self):
        """
        Pop up the "open a file" dialog and ask for which corpus text file
        to use
        """
        self.corpus_filename = self._get_filename_from_dialog(ftype='corpus')

        process_all_gui_events()

        if type(self.corpus_filename) != str:
            return

        # note that self.corpus_filename is an absolute full path
        self.corpus_name = os.path.basename(self.corpus_filename)
        self.corpus_stem_name = Path(self.corpus_name).stem

        self.lexicon = read_corpus(self.corpus_filename)
        self.initialize_lexicon_tree()
        self.load_main_window(major_display=QWidget(),
                              parameter_window=QWidget())
        process_all_gui_events()

        self.status.clearMessage()
        self.status.showMessage(
            'Corpus selected: {}'.format(self.corpus_filename))

    def wordlist_dir_dialog(self):
        """
        Pop up the "open a file" dialog and ask for which corpus text file
        to use
        """
        self.corpus_filename = self._get_filename_from_dialog(ftype='wordlist')

        process_all_gui_events()

        if type(self.corpus_filename) != str:
            return

        # note that self.corpus_filename is an absolute full path
        self.corpus_name = os.path.basename(self.corpus_filename)
        self.corpus_stem_name = Path(self.corpus_name).stem

        self.lexicon = read_wordlist(self.corpus_filename)
        self.initialize_lexicon_tree()
        self.load_main_window(major_display=QWidget(),
                              parameter_window=QWidget())
        process_all_gui_events()

        self.status.clearMessage()
        self.status.showMessage(
            'Wordlist selected: {}'.format(self.corpus_filename))

    def parameters_dialog(self):
        if self.lexicon is None:
            warning = QMessageBox()
开发者ID:linguistica-uchicago,项目名称:lxa5,代码行数:70,代码来源:main_window.py

示例9: QrcPackageEditor

# 需要导入模块: from PyQt5.QtWidgets import QTreeWidget [as 别名]
# 或者: from PyQt5.QtWidgets.QTreeWidget import clear [as 别名]
class QrcPackageEditor(QGridLayout):
    """ A resource file system package editor.  Note that this is a QLayout and
    not a QWidget.
    """

    # Emitted when the package has changed.
    package_changed = pyqtSignal()

    def __init__(self, show_root=False, scan="Scan", scan_whats_this='', whats_this=''):
        """ Initialise the editor. """

        super().__init__()

        self.package = None
        self.project = None

        self._show_root = show_root

        self._package_edit = QTreeWidget(whatsThis=whats_this)
        self._package_edit.header().hide()
        self._package_edit.itemChanged.connect(self._package_changed)
        self.addWidget(self._package_edit, 0, 0, 3, 1)

        self._scan_button = QPushButton(scan, whatsThis=scan_whats_this,
                clicked=self._scan, enabled=False)
        self.addWidget(self._scan_button, 0, 1)

        self._remove_button = QPushButton("Remove all",
                whatsThis="Remove all of the scanned directories and files.",
                clicked=self._remove_all, enabled=False)
        self.addWidget(self._remove_button, 0, 2)

        self._include_button = QPushButton("Include all",
                whatsThis="Select all of the scanned directories and files.",
                clicked=self._include_all, enabled=False)
        self.addWidget(self._include_button, 1, 1)

        self._exclude_button = QPushButton("Exclude all",
                whatsThis="Deselect all of the scanned directories and files.",
                clicked=self._exclude_all, enabled=False)
        self.addWidget(self._exclude_button, 1, 2)

        self._exclusions_edit = QTreeWidget(
                whatsThis="Any directory or file that matches any of the "
                        "these patterns will be automatically ignored when "
                        "scanning. Double-click on a pattern to edit or remove "
                        "it. Double-click below the last pattern in order to "
                        "add a new one.")
        self._exclusions_edit.setHeaderLabel("Exclusions")
        self._exclusions_edit.setEditTriggers(
                QTreeWidget.DoubleClicked|QTreeWidget.SelectedClicked|
                        QTreeWidget.EditKeyPressed)
        self._exclusions_edit.setRootIsDecorated(False)
        self._exclusions_edit.itemChanged.connect(self._exclusion_changed)

        self.addWidget(self._exclusions_edit, 2, 1, 1, 2)

    def configure(self, package, project):
        """ Configure the editor with the contents of the given package and
        project.
        """

        # Save the configuration.
        self.package = package
        self.project = project

        # Set the package itself.
        self._visualise()

        # Set the exclusions.
        self._exclusions_edit.clear()

        for exclude in package.exclusions:
            self._add_exclusion_item(exclude)

        # Add one to be edited to create a new entry.
        self._add_exclusion_item()

        self._scan_button.setEnabled(package is not None)

    def get_root_dir(self):
        """ Return the root directory to scan, or '' if there was an error or
        the user cancelled.
        """

        raise NotImplementedError

    def filter(self, name):
        """ See if a scanned name should be discarded. """

        # Include everything by default.
        return False

    def required(self, name):
        """ See if a scanned name is required. """

        # Nothing is required by default.
        return False

    def _add_exclusion_item(self, exclude=''):
#.........这里部分代码省略.........
开发者ID:doudz,项目名称:pyqtdeploy,代码行数:103,代码来源:qrc_package_editor.py

示例10: MainWindow

# 需要导入模块: from PyQt5.QtWidgets import QTreeWidget [as 别名]
# 或者: from PyQt5.QtWidgets.QTreeWidget import clear [as 别名]

#.........这里部分代码省略.........
            self.writeSettings()
            event.accept()
        else:
            event.ignore()

    def newFile(self):
        self.readDB()
        # if self.maybeSave():
        #     self.textEdit.clear()
        #     self.setCurrentFile('')

    def open(self):
        if self.maybeSave():
            fileName, _ = QFileDialog.getOpenFileName(self)
            if fileName:
                self.loadFile(fileName)

    def save(self):
        if self.curFile:
            return self.saveFile(self.curFile)

        return self.saveAs()

    def saveAs(self):
        fileName, _ = QFileDialog.getSaveFileName(self)
        if fileName:
            return self.saveFile(fileName)
        return False

    def on_sectionList_selection_changed(self):
        print('selected item index changed '),

    def populate_section_list(self, hierarchy, notebook_dict, section_dict):
        self.sectionTreeWidget.clear()
        for notebook_id in hierarchy.keys():
            notebook_sectionTreeWidget = QTreeWidgetItem(self.sectionTreeWidget,
                                                         [notebook_dict[notebook_id].name, notebook_id])
            for section_id in hierarchy[notebook_id].keys():
                QTreeWidgetItem(notebook_sectionTreeWidget, [section_dict[section_id].name, section_id])
        self.sectionTreeWidget.show()
        self.sectionTreeWidget.expandAll()

    def populate_notes_list(self, notebook_id, section_id):
        self.notesListWidget.clear()
        for page_id in self.hierarchy_dict[notebook_id][section_id]:
            item = QListWidgetItem(self.page_dict[page_id].title, self.notesListWidget)
            item.setData(1, QVariant(page_id))

    def readDB(self):

        self.dbm_obj.read()
        [self.hierarchy_dict, self.notebook_dict, self.section_dict, self.page_dict] = self.dbm_obj.get_hierarchy_dict()
        self.populate_section_list(self.hierarchy_dict, self.notebook_dict, self.section_dict)

    def sync(self):
        self.syncAllThread.syncCompleteSignal.connect(self.on_syncAllThread_syncComplete)
        self.statusBar().showMessage("Syncing")
        self.syncAllThread.sync()

    def about(self):
        QMessageBox.about(self, "About Application",
                          "The <b>Application</b> example demonstrates how to write "
                          "modern GUI applications using Qt, with a menu bar, "
                          "toolbars, and a status bar.")

    def documentWasModified(self):
开发者ID:lighht,项目名称:pyonenote-old,代码行数:70,代码来源:mainUI.py

示例11: InspectorWindow

# 需要导入模块: from PyQt5.QtWidgets import QTreeWidget [as 别名]
# 或者: from PyQt5.QtWidgets.QTreeWidget import clear [as 别名]

#.........这里部分代码省略.........
        app = QApplication.instance()
        self._font = app.currentFont()
        self._subscribeToFont(self._font)
        self._updateLayerAttributes()

    def _updateGlyphAttributes(self, notification=None):
        name = None
        unicodes = None
        width = None
        leftSideBearing = None
        rightSideBearing = None
        markColor = None
        if self._glyph is not None:
            name = self._glyph.name
            unicodes = " ".join("%06X" % u if u > 0xFFFF else "%04X" %
                                u for u in self._glyph.unicodes)
            width = str(int(self._glyph.width))
            if self._glyph.leftMargin is not None:
                leftSideBearing = str(int(self._glyph.leftMargin))
            if self._glyph.rightMargin is not None:
                rightSideBearing = str(int(self._glyph.rightMargin))
            if self._glyph.markColor is not None:
                markColor = QColor.fromRgbF(
                    *tuple(self._glyph.markColor))

        self.nameEdit.setText(name)
        self.unicodesEdit.setText(unicodes)
        self.widthEdit.setText(width)
        self.leftSideBearingEdit.setText(leftSideBearing)
        self.rightSideBearingEdit.setText(rightSideBearing)
        self.markColorWidget.setColor(markColor)

    def _updateLayerAttributes(self, notification=None):
        self.layerSetWidget.clear()
        if self._font is None:
            return
        layerSet = self._font.layers
        if layerSet is None:
            return
        for layer in layerSet:
            item = QTreeWidgetItem(self.layerSetWidget)
            item.setFlags(item.flags() | Qt.ItemIsEditable)
            item.setText(0, layer.name)
            widget = ColorVignette(self)
            color = layer.color
            if color is not None:
                color = QColor.fromRgbF(*tuple(color))
            widget.setColor(color)
            widget.setMargins(2, 2, 2, 2)
            widget.setMayClearColor(False)
            widget.colorChanged.connect(self.writeLayerColor)
            widget.setProperty("layer", layer)
            self.layerSetWidget.setItemWidget(item, 1, widget)
        self.layerSetWidget.setColumnWidth(1, 100)

    # ---------
    # Callbacks
    # ---------

    # glyph attributes

    def writeGlyphName(self):
        if self._glyph is None:
            return
        self._glyph.name = self.nameEdit.text()
开发者ID:madig,项目名称:trufont,代码行数:69,代码来源:inspectorWindow.py

示例12: select_param

# 需要导入模块: from PyQt5.QtWidgets import QTreeWidget [as 别名]
# 或者: from PyQt5.QtWidgets.QTreeWidget import clear [as 别名]
class select_param(QWidget):
	def init(self,treeview):
		self.dest_treeview=treeview
		
	def __init__(self):
		QWidget.__init__(self)
		self.win_list=windows()
		self.setFixedSize(400,700)
		self.main_vbox=QVBoxLayout()

		self.setWindowIcon(QIcon(os.path.join(get_image_file_path(),"scan.png")))

		self.setWindowTitle(_("Select simulation parameter (www.gpvdm.com)")) 


		self.tab = QTreeWidget()
		#self.tab.setHeaderItem("Scan items")


		self.main_vbox.addWidget(self.tab)

		self.hwidget=QWidget()

		okButton = QPushButton("OK")
		cancelButton = QPushButton("Cancel")

		hbox = QHBoxLayout()
		hbox.addStretch(1)
		hbox.addWidget(okButton)
		hbox.addWidget(cancelButton)

		self.hwidget.setLayout(hbox)

		self.main_vbox.addWidget(self.hwidget)

		self.setLayout(self.main_vbox)

		okButton.clicked.connect(self.tree_apply_click) 
		cancelButton.clicked.connect(self.close)

		#self.tab.itemSelectionChanged.connect(self.tree_apply_click)
		self.tab.header().close() 
		self.update()

		return

	def make_entry(self,root,text):
		depth=0
		pointer=root
		for depth in range(0,len(text)):
			found=False
			for i in range(0,pointer.childCount()):
				if pointer.child(i).text(0)==text[depth]:
					found=True
					pointer=pointer.child(i)
					break
			if found==False:
				pointer=QTreeWidgetItem(pointer, [text[depth]])
				


	def update(self):
		self.tab.clear()
		root = QTreeWidgetItem(self.tab, [_("Simulation parameters")])
		root.setExpanded(True)
		param_list=scan_items_get_list()
		i=0
		for item in range(0, len(param_list)):
			div_str=param_list[item].name.replace("\\", "/")
			div_str=div_str.split("/")
			piter=None
			self.make_entry(root,div_str)

	 

	def on_destroy(self):
		self.win_list.update(self,"scan_select")
		self.hide()
		return True

	def cal_path(self):
		getSelected = self.tab.selectedItems()
		if getSelected:
			item = getSelected[0]
#			getChildNode = baseNode.text(0)


			path = []
			while item is not None:
				path.append(str(item.text(0)))
				item = item.parent()

		ret="/".join(reversed(path))
		ret=ret.split('/', 1)[-1]
		ret=ret.replace("/", os.path.sep)
		return ret
	
	def tree_apply_click(self):
		index = self.dest_treeview.selectionModel().selectedRows()
		if len(index)>0:
#.........这里部分代码省略.........
开发者ID:roderickmackenzie,项目名称:gpvdm,代码行数:103,代码来源:scan_select.py

示例13: OTMainWindow

# 需要导入模块: from PyQt5.QtWidgets import QTreeWidget [as 别名]
# 或者: from PyQt5.QtWidgets.QTreeWidget import clear [as 别名]
class OTMainWindow(QWidget):
    def __init__(self, parent=None):
        super(OTMainWindow, self).__init__(parent, Qt.Window)
        self.setWindowTitle('OPC Python Tester')
        self.layout = QVBoxLayout()
        #
        self.tree = QTreeWidget(self)
        self.tree.setHeaderLabel('OPC server tree')
        self.tree_root = QTreeWidgetItem()
        self.tree_root.setText(0, 'not connected')
        self.tree.addTopLevelItem(self.tree_root)
        self.tree.itemDoubleClicked.connect(self.on_tree_item_double_clicked)
        #
        self.table = QTableWidget(self)
        self.table.setRowCount(0)
        self.table_column_labels = [
            'item_id', 'value', 'type', 'access', 'quality', 'timestamp']
        self.table.setColumnCount(len(self.table_column_labels))
        self.table.setHorizontalHeaderLabels(self.table_column_labels)
        self.table.horizontalHeader().setStretchLastSection(True)
        #
        self.splitter = QSplitter(Qt.Horizontal, self)
        self.splitter.setChildrenCollapsible(False)
        self.splitter.setHandleWidth(10)
        self.layout.addWidget(self.splitter)
        # final
        self.splitter.addWidget(self.tree)
        self.splitter.addWidget(self.table)
        self.splitter.setSizes([150, 300])
        self.setLayout(self.layout)

        # self.opcsrv = None
        self.cur_server_info = {}
        self.cur_comp_name = ''
        self.watched_itemids = []

        self.ssdialog = ServerSelectDialog(self)
        ssel_ret = self.ssdialog.exec_()
        if ssel_ret == QDialog.Accepted:
            self.do_connect(self.ssdialog.selected_server, self.ssdialog.selected_comp_name)
        else:
            print('Connection cancelled')

        self.timer = QTimer(self)
        self.timer.timeout.connect(self.on_timer_timeout)
        self.timer.start(1000)  # every 1 second

    def do_connect(self, srv_info: dict, comp_name: str):
        print('Connecting to "{0}" ({1}) on comp: {2}...'.format(
            srv_info['desc'], srv_info['guid'], comp_name))
        self.opcsrv = opc_helper.opc_connect(srv_info['guid'], comp_name)
        if self.opcsrv is None:
            return
        self.cur_comp_name = comp_name
        self.cur_server_info = srv_info
        print(self.opcsrv.get_status())
        self.fill_tree()

    def fill_tree(self):
        self.tree.clear()
        if self.opcsrv is None:
            return
        self.tree_root = QTreeWidgetItem(self.tree)
        self.tree_root.setChildIndicatorPolicy(QTreeWidgetItem.DontShowIndicatorWhenChildless)
        root_title = '{0}'.format(self.cur_server_info['desc'])
        if self.cur_comp_name != '':
            root_title = '{0} ({1})'.format(self.cur_server_info['desc'], self.cur_comp_name)
        self.tree_root.setText(0, root_title)
        self.tree.addTopLevelItem(self.tree_root)
        server_tree = self.opcsrv.browse(flat=False)
        #
        for oitem in server_tree:
            self.fill_item(oitem, self.tree_root)

    def fill_item(self, item: dict, parent: QTreeWidgetItem):
        tree_item = QTreeWidgetItem()
        tree_item.setChildIndicatorPolicy(QTreeWidgetItem.DontShowIndicatorWhenChildless)
        tree_item.setText(0, item['name'])
        if item['children'] is None:
            # set userdata = item_id only if this IS a LEAF node
            tree_item.setData(0, Qt.UserRole, item['item_id'])  # column, role, data
        parent.addChild(tree_item)
        # recurse into children
        if item['children'] is not None:
            for oitem in item['children']:
                self.fill_item(oitem, tree_item)

    @pyqtSlot(QTreeWidgetItem, int)
    def on_tree_item_double_clicked(self, item: QTreeWidgetItem, column: int):
        # void	itemDoubleClicked(QTreeWidgetItem * item, int column)
        # virtual QVariant	data(int column, int role) const
        item_data = item.data(0, Qt.UserRole)
        if item_data is None:
            return
        item_id = str(item_data)
        print('Double click on [{0}]'.format(item_id))
        self.opcsrv.get_item(item_id)
        if item_id not in self.watched_itemids:
            self.watched_itemids.append(item_id)

#.........这里部分代码省略.........
开发者ID:minlexx,项目名称:python_opc_test,代码行数:103,代码来源:test_qt.py

示例14: CueListDialog

# 需要导入模块: from PyQt5.QtWidgets import QTreeWidget [as 别名]
# 或者: from PyQt5.QtWidgets.QTreeWidget import clear [as 别名]
class CueListDialog(QDialog):

    def __init__(self, **kwargs):
        super().__init__(**kwargs)

        self.setMinimumSize(400, 300)

        self._cues = []

        self.list = QTreeWidget(self)
        self.list.setSelectionMode(self.list.SingleSelection)
        self.list.setSelectionBehavior(self.list.SelectRows)
        self.list.setAlternatingRowColors(True)
        self.list.setIndentation(0)
        self.list.setHeaderLabels(['Index', 'Name'])
        self.list.header().setSectionResizeMode(QHeaderView.Fixed)
        self.list.header().setSectionResizeMode(1, QHeaderView.Stretch)
        self.list.header().setStretchLastSection(False)

        self.setLayout(QVBoxLayout())
        self.layout().addWidget(self.list)

        self.buttons = QDialogButtonBox(self)
        self.buttons.addButton(QDialogButtonBox.Cancel)
        self.buttons.addButton(QDialogButtonBox.Ok)
        self.layout().addWidget(self.buttons)

        self.buttons.accepted.connect(self.accept)
        self.buttons.rejected.connect(self.reject)

    def add_cue(self, cue):
        try:
            item = QTreeWidgetItem()
            item.setTextAlignment(0, Qt.AlignCenter)

            for n, prop in enumerate(['index', 'name']):
                item.setText(n, str(cue.properties().get(prop, 'Undefined')))

            self._cues.append(cue)
            self.list.addTopLevelItem(item)
        except Exception:
            pass

    def add_cues(self, cues):
        for cue in cues:
            self.add_cue(cue)

    def remove_cue(self, index):
        self.list.takeTopLevelItem(index)
        return self._cues.pop(index)

    def reset(self):
        self.list.clear()
        self._cues.clear()

    def selected_cues(self):
        cues = []
        for item in self.list.selectedItems():
            index = self.list.indexOfTopLevelItem(item)
            cues.append(self._cues[index])
        return cues
开发者ID:tornel,项目名称:linux-show-player,代码行数:63,代码来源:cuelistdialog.py

示例15: OtherExtensionModulesPage

# 需要导入模块: from PyQt5.QtWidgets import QTreeWidget [as 别名]
# 或者: from PyQt5.QtWidgets.QTreeWidget import clear [as 别名]
class OtherExtensionModulesPage(QWidget):
    """ The GUI for the other extension modules page of a project. """

    # The page's label.
    label = "Other Extension Modules"

    @property
    def project(self):
        """ The project property getter. """

        return self._project

    @project.setter
    def project(self, value):
        """ The project property setter. """

        if self._project != value:
            self._project = value
            self._extension_modules_delegate.set_project(value)
            self._update_page()

    def __init__(self):
        """ Initialise the page. """

        super().__init__()

        self._project = None

        # Create the page's GUI.
        layout = QVBoxLayout()

        self._extension_modules_edit = QTreeWidget(
                whatsThis="This shows a list of additional compiled "
                        "extension modules to be linked with the application. "
                        "<b>Name</b> should be the full (dot separated) "
                        "package name of the extension module. <b>LIBS</b> "
                        "should be the value of the corresponding "
                        "<tt>qmake</tt> variable needed to link the extension "
                        "module. Double-click on an entry to edit or remove "
                        "it. Double-click below the last entry in order to "
                        "add a new one. Values may be prefixed by a platform "
                        "specific <tt>qmake</tt> scope.")
        self._extension_modules_edit.setHeaderLabels(["Name", "LIBS"])
        self._extension_modules_edit.setEditTriggers(
                QTreeWidget.DoubleClicked|QTreeWidget.SelectedClicked|
                QTreeWidget.EditKeyPressed)
        self._extension_modules_edit.setRootIsDecorated(False)
        self._extension_modules_edit.itemChanged.connect(
                self._extension_module_changed)

        self._extension_modules_delegate = FilenameEditorDelegate(
                "Extension Module Directory", directory=True)

        self._extension_modules_edit.setItemDelegateForColumn(1,
                self._extension_modules_delegate)

        layout.addWidget(self._extension_modules_edit)

        self.setLayout(layout)

    def _update_page(self):
        """ Update the page using the current project. """

        project = self.project

        # Set the extension modules.
        self._extension_modules_edit.clear()

        for extension_module in project.other_extension_modules:
            self._add_extension_module_item(extension_module)

        # Add one to be edited to create a new entry.
        self._add_extension_module_item()

    def _add_extension_module_item(self, extension_module=None):
        """ Add a QTreeWidgetItem that holds an exclusion. """

        if extension_module is not None:
            name = extension_module.name
            libs = extension_module.libs
        else:
            name = libs = ''

        itm = QTreeWidgetItem([name, libs])

        itm.setFlags(
                Qt.ItemIsSelectable|Qt.ItemIsEditable|Qt.ItemIsEnabled|
                        Qt.ItemNeverHasChildren)

        self._extension_modules_edit.addTopLevelItem(itm)

    def _extension_module_changed(self, itm, value):
        """ Invoked when an extension module has changed. """

        project = self.project
        em_edit = self._extension_modules_edit

        new_name = itm.data(0, Qt.DisplayRole).strip()
        new_libs = itm.data(1, Qt.DisplayRole).strip()
        itm_index = em_edit.indexOfTopLevelItem(itm)
#.........这里部分代码省略.........
开发者ID:doudz,项目名称:pyqtdeploy,代码行数:103,代码来源:other_extension_modules_page.py


注:本文中的PyQt5.QtWidgets.QTreeWidget.clear方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。