def createActionItem(self, key):
        """
        Creates a new action item for the inputed key.
        
        :param      key | <str>
        
        :return     <QTreeWidgetItem>
        """
        action = self._actions.get(key)
        if (not action):
            text = 'Missing Action: %s' % key
            item = QTreeWidgetItem([text])
            ico = projexui.resources.find('img/log/warning.png')
            item.setIcon(0, QIcon(ico))
        else:
            item = QTreeWidgetItem([str(action.text()).replace('&', '')])
            item.setIcon(0, action.icon())

        item.setSizeHint(0, QSize(120, 20))
        item.setData(0, Qt.UserRole, qt.wrapVariant(key))

        flags = item.flags()
        flags ^= Qt.ItemIsDropEnabled
        item.setFlags(flags)

        return item
    def _add_symbol_to_tree_widget(self, symbol):
        """ Add the given symbol to the tree widget. If this
        is a new category create it, otherwise append it
        to the already existing one.

        """

        # find category
        category = symbol["category"]
        categoryItems = self.availableSymbolsWidget.findItems(category,
                                                Qt.MatchExactly, 0)

        name = symbol["name"]
        symbolItem = QTreeWidgetItem([name])
        symbolItem.setData(0, Qt.UserRole, name)
        symbolItem.setFlags(Qt.ItemIsSelectable |
                            Qt.ItemIsUserCheckable |
                            Qt.ItemIsEnabled)

        if categoryItems:
            categoryItems[0].addChild(symbolItem)
        else:
            categoryItem = QTreeWidgetItem(self.availableSymbolsWidget,
                                           [category])
            categoryItem.setFlags(Qt.ItemIsEnabled)
            categoryItem.addChild(symbolItem)

        self.availableSymbolsWidget.resizeColumnToContents(0)
        self.availableSymbolsWidget.sortItems(0, Qt.AscendingOrder)
        self.availableSymbolsWidget.setCurrentItem(symbolItem)
    def loadPlaylistFromIndex(self, ModelIndex):
        playlist = ModelIndex.data(Qt.UserRole).toPyObject()[0]
        self.emit(SIGNAL("start_loading"))
        print("Request for Playlist")
        thread = WorkerThread(playlist.listTracks)
        thread.start()
        while not thread.isFinished():
            QApplication.processEvents()
        tracks = thread.result()
        print("Request Done.")
        #tracks = playlist.listTracks()

        for Id, trackObj in tracks.iteritems():
            title = trackObj.title
            print("Title:", title)
            print("Modelindex:", ModelIndex)

            parentOfTitel = self.itemFromIndex(ModelIndex)

            entry2 = QTreeWidgetItem(parentOfTitel, [unicode(title)])
            entry2.setIcon(0, QIcon(":/mp3.png"))
            entry2.setData(0, Qt.UserRole, QVariant((trackObj, )))
            self.parentFromAlbum[unicode(title)] = entry2
            print("Created: ", unicode(title))

        self.emit(SIGNAL("stop_loading"))
    def updateLogList(self, logsAdded=None, logsRenamed=None):
        selectedMember = self.get_selected_log_member()

        if logsAdded == None:
            self.log_tree_view.clear()
            logsAdded = []
            for index, logFile in enumerate(reversed(self.listLogFilesForMember(selectedMember))):
                logsAdded.append((index, logFile))
            if len(logsAdded) == 0:
                self.log_tree_view.clear()
                self.log_tree_view.addTopLevelItem(
                    QTreeWidgetItem(self.log_tree_view, QStringList("No logs available."))
                )
                self.log_tree_view.setSelectionMode(QTreeWidget.NoSelection)
                self.logSizeLabel.setText("No logs")
                self.clearLogsButton.setEnabled(False)
                return

        if logsRenamed != None:
            for index, oldName, newName in logsRenamed:
                # index + 1 because of the "requesting" item
                item = self.log_tree_view.topLevelItem(index + 1)
                if item != None:
                    itemLogFile = convert_string(item.data(0, Qt.UserRole).toString())
                    if itemLogFile != oldName:
                        self.logger.warning(
                            "index does not correspond to item in list:\n\t%s\n\t%s", itemLogFile, oldName
                        )
                    self.initializeLogItem(item, newName)

        if len(logsAdded) == 0:
            self.log_tree_view.takeTopLevelItem(0)
        else:
            for index, logFile in logsAdded:
                oldItem = self.log_tree_view.topLevelItem(index)
                item = None
                if oldItem != None and oldItem.data(0, Qt.UserRole) == None:
                    # requested item has been received
                    item = oldItem
                else:
                    item = QTreeWidgetItem()
                    oldItem = None

                if logFile == None:
                    item.setData(0, Qt.DisplayRole, QVariant("Requesting..."))
                    QTimer.singleShot(6000, partial(self.requestTimedOut, item))
                else:
                    self.initializeLogItem(item, logFile)

                if oldItem == None:
                    # else, the old item is being modified
                    self.log_tree_view.insertTopLevelItem(index, item)
                self.log_tree_view.setSelectionMode(QTreeWidget.SingleSelection)

        totalSize = 0
        for aLogFile in self.listLogFilesForMember(selectedMember):
            totalSize += os.path.getsize(aLogFile)

        self.logSizeLabel.setText("%s consumed" % self.formatFileSize(totalSize))
        self.clearLogsButton.setEnabled(True)
Beispiel #5
0
    def _add_symbol_to_tree_widget(self, symbol):
        """ Add the given symbol to the tree widget. If this
        is a new category create it, otherwise append it
        to the already existing one.

        """

        # find category
        category = symbol["category"]
        categoryItems = self.availableSymbolsWidget.findItems(
            category, Qt.MatchExactly, 0)

        name = symbol["name"]
        symbolItem = QTreeWidgetItem([name])
        symbolItem.setData(0, Qt.UserRole, name)
        symbolItem.setFlags(Qt.ItemIsSelectable | Qt.ItemIsUserCheckable
                            | Qt.ItemIsEnabled)

        if categoryItems:
            categoryItems[0].addChild(symbolItem)
        else:
            categoryItem = QTreeWidgetItem(self.availableSymbolsWidget,
                                           [category])
            categoryItem.setFlags(Qt.ItemIsEnabled)
            categoryItem.addChild(symbolItem)

        self.availableSymbolsWidget.resizeColumnToContents(0)
        self.availableSymbolsWidget.sortItems(0, Qt.AscendingOrder)
        self.availableSymbolsWidget.setCurrentItem(symbolItem)
    def _populate_repo_tree(self):
        """
        Initialize the tree widget of repos and volumes.
        """
        self._repo_treewidget.clear()
        
        if self._repos_info is None:
            return
        
        for repo_uuid, repo_info in sorted(self._repos_info.items()):
            if repo_info is None:
                continue
            repo_column_dict = collections.defaultdict(str)
            repo_column_dict["Alias"] = repo_info["Alias"]
            repo_column_dict["Details"] = "Created: " + repo_info["Created"]
            repo_column_dict["UUID"] = repo_uuid
            repo_column_values = [repo_column_dict[k] for k in TREEVIEW_COLUMNS]
            repo_item = QTreeWidgetItem( self._repo_treewidget, QStringList( repo_column_values ) )
            repo_item.setData( 0, Qt.UserRole, (repo_uuid, "", "") )
            for data_name, data_info in repo_info["DataInstances"].items():
                data_instance_dict = collections.defaultdict(str)
                data_instance_dict["Alias"] = data_name
                typename = data_info["Base"]["TypeName"]
                data_instance_dict["TypeName"] = typename

                is_voxels = (typename in VOXEL_TYPENAMES)
                if is_voxels:
                    start_coord = data_info["Extended"]["MinPoint"]
                    if start_coord:
                        start_coord = tuple(start_coord)
                    stop_coord = data_info["Extended"]["MaxPoint"]
                    if stop_coord:
                        stop_coord = tuple(x+1 for x in stop_coord)
                    if start_coord and stop_coord:
                        shape = tuple(b - a for a,b in zip(start_coord, stop_coord))
                    else:
                        shape = None
                    data_instance_dict["Details"] = "Size={} | Start={} | Stop={}".format( shape, start_coord, stop_coord )

                data_column_values = [data_instance_dict[k] for k in TREEVIEW_COLUMNS]
                data_item = QTreeWidgetItem( repo_item, data_column_values )
                data_item.setData( 0, Qt.UserRole, (repo_uuid, data_name, typename) )

                # If we're in specify_new mode, only the
                # repo parent items are selectable.
                # Also, non-volume items aren't selectable.
                if self._mode == 'specify_new' or typename not in self._selectable_types:
                    flags = data_item.flags()
                    flags &= ~Qt.ItemIsSelectable
                    flags &= ~Qt.ItemIsEnabled
                    data_item.setFlags( flags )
        
        self._repo_treewidget.collapseAll()
        self._repo_treewidget.setSortingEnabled(True)

        if self._hostname in self._default_nodes:
            self._select_node_uuid(self._default_nodes[self._hostname])

        self._repo_treewidget.resizeColumnToContents(0)
        self._repo_treewidget.setFocus()
Beispiel #7
0
 def setData(self, column, role, variant):
     if role == Qt.CheckStateRole:
         if variant == Qt.Checked:
             self.__page.selected(True)
         else:
             self.__page.selected(False)
     QTreeWidgetItem.setData(self, column, role, variant)
    def fillTreeWidget(self):
        """ Заполняем tree widget записями, на основе разбиения на категории"""
        self._loadingData = True
        self._ui.twEntries.clear()
        for key in self._categories:
            self._categories[key] = sorted(self._categories[key], key=attrgetter('title'))
            item = DateTreeWidgetItem(self._ui.twEntries)
            font = item.font(0)
            font.setPointSize(11)
            font.setBold(True)
            item.setFont(0, font)
            if settings.showEntryCountInCategory():
                item.setText(0, "{} ({})".format(key, len(self._categories[key])))
            else:
                item.setText(0, key)
            item.setData(0, Qt.UserRole, self._keyForCategory[key])
            for e in self._categories[key]:
                entryItem = QTreeWidgetItem(item)
                font = entryItem.font(0)
                font.setPointSize(12)
                entryItem.setCheckState(0, Qt.Checked if e.interesting else Qt.Unchecked)
                entryItem.setText(0, e.title)
                entryItem.setFont(0, font)
                entryItem.setData(0, Qt.UserRole, e.id)
                self._setToolTipForItem(e, entryItem)

        self._ui.twEntries.sortItems(0, Qt.AscendingOrder)
        self._ui.twEntries.expandAll()
        self._loadingData = False
 def createActionItem( self, key ):
     """
     Creates a new action item for the inputed key.
     
     :param      key | <str>
     
     :return     <QTreeWidgetItem>
     """
     action = self._actions.get(key)
     if ( not action ):
         text = 'Missing Action: %s' % key
         item = QTreeWidgetItem([text])
         ico = projexui.resources.find('img/log/warning.png')
         item.setIcon(0, QIcon(ico))
     else:
         item = QTreeWidgetItem([str(action.text()).replace('&', '')])
         item.setIcon(0, action.icon())
     
     item.setSizeHint(0, QSize(120, 20))
     item.setData(0, Qt.UserRole, qt.wrapVariant(key))
     
     flags = item.flags()
     flags ^= Qt.ItemIsDropEnabled
     item.setFlags(flags)
     
     return item
Beispiel #10
0
    def load_ui(self):
        sections = sorted(list(Preferences.configuration.keys()),
            key=lambda item: Preferences.configuration[item]['weight'])
        for section in sections:
            text = Preferences.configuration[section]['text']
            Widget = Preferences.configuration[section]['widget']
            widget = Widget(self)
            area = QScrollArea()
            area.setWidgetResizable(True)
            area.setWidget(widget)
            index = self.stacked.addWidget(area)
            item = QTreeWidgetItem([text])
            item.setData(0, Qt.UserRole, index)
            self.tree.addTopLevelItem(item)

            #Sort Item Children
            subcontent = Preferences.configuration[section].get(
                'subsections', {})
            subsections = sorted(list(subcontent.keys()),
                key=lambda item: subcontent[item]['weight'])
            for sub in subsections:
                text = subcontent[sub]['text']
                Widget = subcontent[sub]['widget']
                widget = Widget(self)
                area = QScrollArea()
                area.setWidgetResizable(True)
                area.setWidget(widget)
                index = self.stacked.addWidget(area)
                subitem = QTreeWidgetItem([text])
                subitem.setData(0, Qt.UserRole, index)
                item.addChild(subitem)

        self.tree.expandAll()
Beispiel #11
0
    def add(self,
            seq,
            text,
            position,
            foreground=False,
            background=False,
            icon=False):
        from PyQt4.QtGui import QTreeWidgetItem

        item = QTreeWidgetItem()

        item.setText(0, text)
        item.setData(0, Qt.UserRole, position)

        if foreground:
            item.setForeground(0, foreground)

        if background:
            item.setBackground(0, background)

        if icon:
            item.setIcon(0, icon)

        seq.append(item)
        return item
Beispiel #12
0
    def _populate_datasets_tree(self):
        """
        Initialize the tree widget of datasets and volumes.
        """
        self._data_treewidget.clear()

        if self._repos_info is None:
            return

        for dset_uuid, dset_info in sorted(self._repos_info.items()):
            dset_item = QTreeWidgetItem(self._data_treewidget,
                                        QStringList(dset_uuid))
            dset_item.setData(0, Qt.UserRole, (dset_uuid, ""))
            for data_name in dset_info["DataInstances"].keys():
                data_item = QTreeWidgetItem(dset_item, QStringList(data_name))
                data_item.setData(0, Qt.UserRole, (dset_uuid, data_name))
                if self._mode == 'specify_new':
                    # If we're in specify_new mode, only the dataset parent items are selectable.
                    flags = data_item.flags()
                    flags &= ~Qt.ItemIsSelectable
                    flags &= ~Qt.ItemIsEnabled
                    data_item.setFlags(flags)

        # Expand everything
        self._data_treewidget.expandAll()

        # Select the first item by default.
        if self._mode == "select_existing":
            first_item = self._data_treewidget.topLevelItem(0).child(0)
        else:
            first_item = self._data_treewidget.topLevelItem(0)
        self._data_treewidget.setCurrentItem(first_item, 0)
 def __add_themen(self):
     self.ui.TREE_THEMEN.headerItem().setText(0, '')
     #TODO: resize column to contents
     #all of these don't work??
     self.ui.TREE_THEMEN.header().resizeSection(0, 250)
     self.ui.TREE_THEMEN.header().setResizeMode(
         QHeaderView.ResizeToContents)
     self.ui.TREE_THEMEN.header().setStretchLastSection(True)
     themen = self.json_settings.themen()
     for thema_name, thema in themen.iteritems():
         tree_thema = QTreeWidgetItem(self.ui.TREE_THEMEN)
         tree_thema.setText(0, thema_name)
         tree_thema.setData(0, Qt.UserRole, thema)
         tree_thema.setFlags(tree_thema.flags() | Qt.ItemIsUserCheckable)
         if thema_name == 'DKM':
             tree_thema.setCheckState(0, Qt.Checked)
         else:
             tree_thema.setCheckState(0, Qt.Unchecked)
         if not thema.subthemen is None:
             for subthema in thema.subthemen:
                 if VRP_DEBUG is True:
                     QgsMessageLog.logMessage(
                         u'Subthema: {0}'.format(subthema.name),
                         DLG_CAPTION)
                 tree_subthema = QTreeWidgetItem()
                 tree_subthema.setText(0, subthema.name)
                 tree_subthema.setData(0, Qt.UserRole, subthema)
                 tree_subthema.setFlags(tree_subthema.flags()
                                        | Qt.ItemIsUserCheckable)
                 tree_subthema.setCheckState(0, Qt.Unchecked)
                 tree_thema.addChild(tree_subthema)
Beispiel #14
0
 def add_modify_account(self, add=False):
     dlg = AccountSettingsDialog(self)
     if not add:
         item = self.widgets.accounts.currentItem()
         if not item:
             return
         account = self.account_items.get(item)
         if not account:
             return
         #account = item.data(0, ITEM_PLACEHOLDER_ROLE).toPyObject()
         dlg.fill_from(account)
     else:
         item = QTreeWidgetItem()
     result = dlg.exec_()
     
     if not result == QDialog.Accepted:
         return
     new_a = dlg.values
     
     item.setText(0, new_a["name"])
     #get icon and name...
     name, icon = getProtoIconAndName(getattr(yobotproto, new_a["improto"], -1))
     item.setText(1, name)
     item.setIcon(1, icon)
     if add:
         if self.account_exists(new_a):
             print "account already exists.. not adding"
             return
         item.setData(0, ITEM_PLACEHOLDER_ROLE, new_a)
         self.widgets.accounts.addTopLevelItem(item)
         self.config.accounts.append(new_a)
     else:
         account.update(new_a)
    def updateMemberInformation(self, peerID=None, peerInfo=None):
        if peerID != None and peerID != self.get_selected_log_member():
            # only update if selected member updated
            return

        self.memberInformationTable.clear()

        if self.get_selected_log_member() == None:
            self.memberInformationTable.setColumnCount(0)
            self.memberInformationTable.setHeaderLabel("No member selected.")
            return

        if peerInfo == None:
            peerInfo = get_peers().getPeerInfo(pID=self.get_selected_log_member())

        if peerInfo == None:
            self.memberInformationTable.setColumnCount(0)
            self.memberInformationTable.setHeaderLabel("No member information available.")
            return

        self.memberInformationTable.setColumnCount(len(peerInfo))
        headers = sorted(peerInfo.keys(), key=lambda s: s.lower())
        self.memberInformationTable.setHeaderLabels(QStringList(headers))
        item = QTreeWidgetItem(self.memberInformationTable)
        for col, header in enumerate(headers):
            item.setData(col, Qt.DisplayRole, QVariant(peerInfo[header]))
        for col in range(self.memberInformationTable.columnCount()):
            self.memberInformationTable.resizeColumnToContents(col)
 def __add_themen(self):
     self.ui.TREE_THEMEN.headerItem().setText(0, '')
     #TODO: resize column to contents
     #all of these don't work??
     self.ui.TREE_THEMEN.header().resizeSection(0, 250)
     self.ui.TREE_THEMEN.header().setResizeMode(QHeaderView.ResizeToContents);
     self.ui.TREE_THEMEN.header().setStretchLastSection(True);
     themen = self.json_settings.themen()
     for thema_name, thema in themen.iteritems():
         tree_thema = QTreeWidgetItem(self.ui.TREE_THEMEN)
         tree_thema.setText(0, thema_name)
         tree_thema.setData(0, Qt.UserRole, thema)
         tree_thema.setFlags(tree_thema.flags() | Qt.ItemIsUserCheckable)
         if thema_name == 'DKM':
             tree_thema.setCheckState(0, Qt.Checked)
         else:
             tree_thema.setCheckState(0, Qt.Unchecked)
         if not thema.subthemen is None:
             for subthema in thema.subthemen:
                 if VRP_DEBUG is True: QgsMessageLog.logMessage(u'Subthema: {0}'.format(subthema.name), DLG_CAPTION)
                 tree_subthema = QTreeWidgetItem()
                 tree_subthema.setText(0, subthema.name)
                 tree_subthema.setData(0, Qt.UserRole, subthema)
                 tree_subthema.setFlags(tree_subthema.flags() | Qt.ItemIsUserCheckable)
                 tree_subthema.setCheckState(0, Qt.Unchecked)
                 tree_thema.addChild(tree_subthema)
 def _populate_datasets_tree(self):
     """
     Initialize the tree widget of datasets and volumes.
     """
     self._data_treewidget.clear()
     
     if self._repos_info is None:
         return
     
     for dset_uuid, dset_info in sorted(self._repos_info.items()):
         dset_item = QTreeWidgetItem( self._data_treewidget, QStringList( dset_uuid ) )
         dset_item.setData( 0, Qt.UserRole, (dset_uuid, "") )
         for data_name in dset_info["DataInstances"].keys():
             data_item = QTreeWidgetItem( dset_item, QStringList( data_name ) )
             data_item.setData( 0, Qt.UserRole, (dset_uuid, data_name) )
             if self._mode == 'specify_new':
                 # If we're in specify_new mode, only the dataset parent items are selectable.
                 flags = data_item.flags()
                 flags &= ~Qt.ItemIsSelectable
                 flags &= ~Qt.ItemIsEnabled
                 data_item.setFlags( flags )
     
     # Expand everything
     self._data_treewidget.expandAll()
     
     # Select the first item by default.
     if self._mode == "select_existing":
         first_item = self._data_treewidget.topLevelItem(0).child(0)
     else:
         first_item = self._data_treewidget.topLevelItem(0)            
     self._data_treewidget.setCurrentItem( first_item, 0 )
Beispiel #18
0
 def addParent(self, parent, column, title, data, status):
     item = QTreeWidgetItem(parent, [title])
     item.setData(column, Qt.UserRole, data)
     item.setChildIndicatorPolicy(QTreeWidgetItem.ShowIndicator)
     item.setCheckState (column, self.getCheckStatus(status))
     item.setExpanded (False)
     return item
Beispiel #19
0
    def loadPlaylistFromIndex(self, ModelIndex):
        playlist = ModelIndex.data(Qt.UserRole).toPyObject()[0]
        self.emit(SIGNAL("start_loading"))
        print("Request for Playlist")
        thread = WorkerThread(playlist.listTracks)
        thread.start()
        while not thread.isFinished():
            QApplication.processEvents()
        tracks = thread.result()
        print("Request Done.")
        #tracks = playlist.listTracks()

        for Id, trackObj in tracks.iteritems():
            title = trackObj.title
            print("Title:", title)
            print("Modelindex:", ModelIndex)

            parentOfTitel = self.itemFromIndex(ModelIndex)

            entry2 = QTreeWidgetItem(parentOfTitel, [unicode(title)])
            entry2.setIcon(0, QIcon(":/mp3.png"))
            entry2.setData(0, Qt.UserRole, QVariant((trackObj,)))
            self.parentFromAlbum[unicode(title)] = entry2
            print("Created: ", unicode(title))


        self.emit(SIGNAL("stop_loading"))
Beispiel #20
0
    def _loadDir(self, base_path, tree):
        for element in os.listdir(base_path):
            path = os.path.join(base_path, element)
            if (not os.path.isdir(path)) and (not path.endswith(".csv")):
                continue

            if os.path.isdir(path):
                parent_itm = QTreeWidgetItem(tree, [element])
                self._loadDir(path, parent_itm)
                if parent_itm.childCount() == 0:
                    parent = parent_itm.parent()
                    root = parent_itm.treeWidget().invisibleRootItem()
                    (parent or root).removeChild(parent_itm)
                else:
                    parent_itm.setIcon(
                        0,
                        QIcon(
                            "/usr/share/icons/ubuntu-mono-light/places/16/folder-home.svg"
                        ))
                    # parent_itm.setExpanded(True)
            else:
                if Graph.getGraphDesc(path) is None:
                    continue
                # item = GraphFileTreeWidgetItem(tree, element)
                item = QTreeWidgetItem(tree, [element])
                item.setData(0, Qt.UserRole, path)
                item.setCheckState(0, Qt.Unchecked)
Beispiel #21
0
    def fill_fields(self):

        search_word = self.filterEdit.text()
        if search_word.strip() != '':
            search_str = stem_str(search_word)
        else:
            search_str = ''

        query = QSqlQuery(self.local_cn)
        LIMIT = 100
        OFFSET = 0
        query.prepare(show_termins_in_link_selector_query)
        query.bindValue(':search_str', search_str + '%')
        query.bindValue(':linked', 1)
        query.bindValue(':limit', LIMIT.__str__())
        query.bindValue(':offset', OFFSET.__str__())
        if query.exec_():
            self.root.takeChildren()
            while query.next():
                c = QTreeWidgetItem()
                c.setText(0, query.value(0))  # Заглавное слово
                c.setData(1, 0, query.value(1))  # uuid
                self.root.addChild(c)
        else:
            print(query.lastError().text())
            print("not exec")
        self.treeWidget.scrollToTop()
Beispiel #22
0
    def populate(self, tagsmap):
        for tags in tagsmap:
            tagsItem = self.checkBoxItem(self)
            self.expandItem(tagsItem)
            tagsItem.setText(0, tags)
            tagsItem.setFlags(Qt.ItemIsUserCheckable | Qt.ItemIsSelectable
                              | Qt.ItemIsEnabled)
            self.addTopLevelItem(tagsItem)
            modulesArePostProcess = 1
            for module in tagsmap[tags]:
                moduleItem = self.checkBoxItem(self, tagsItem)
                moduleItem.setText(0, module.name)
                moduleItem.setFlags(Qt.ItemIsUserCheckable
                                    | Qt.ItemIsSelectable | Qt.ItemIsEnabled)
                if self.ppModules().isSet(module.name):
                    moduleItem.setData(0, Qt.CheckStateRole,
                                       QVariant(Qt.Checked))
                else:
                    moduleItem.setData(0, Qt.CheckStateRole,
                                       QVariant(Qt.Unchecked))
                    modulesArePostProcess = 0
                if module.icon:
                    icon = QIcon(QPixmap(module.icon))
                else:
                    icon = QIcon(QPixmap(":module2.png"))
                moduleItem.setIcon(0, icon)

            if modulesArePostProcess:
                tagsItem.setData(0, Qt.CheckStateRole, QVariant(Qt.Checked))
            else:
                QTreeWidgetItem.setData(tagsItem, 0, Qt.CheckStateRole,
                                        QVariant(Qt.Unchecked))
Beispiel #23
0
    def load_ui(self):
        sections = sorted(
            list(Preferences.configuration.keys()),
            key=lambda item: Preferences.configuration[item]['weight'])
        for section in sections:
            text = Preferences.configuration[section]['text']
            Widget = Preferences.configuration[section]['widget']
            widget = Widget(self)
            area = QScrollArea()
            area.setWidgetResizable(True)
            area.setWidget(widget)
            index = self.stacked.addWidget(area)
            item = QTreeWidgetItem([text])
            item.setData(0, Qt.UserRole, index)
            self.tree.addTopLevelItem(item)

            #Sort Item Children
            subcontent = Preferences.configuration[section].get(
                'subsections', {})
            subsections = sorted(list(subcontent.keys()),
                                 key=lambda item: subcontent[item]['weight'])
            for sub in subsections:
                text = subcontent[sub]['text']
                Widget = subcontent[sub]['widget']
                widget = Widget(self)
                area = QScrollArea()
                area.setWidgetResizable(True)
                area.setWidget(widget)
                index = self.stacked.addWidget(area)
                subitem = QTreeWidgetItem([text])
                subitem.setData(0, Qt.UserRole, index)
                item.addChild(subitem)

        self.tree.expandAll()
Beispiel #24
0
    def gotEvent(self, event):
        found = False
        for i in xrange(self.ui.typeBox.count()):
            s = self.ui.typeBox.itemData(i)
            if s == event.type:
                found = True
        if not found:
            print(event.type)
            self.ui.typeBox.addItem(event.type.capitalize(), event.type)
            if event.type == self.event_filter:
                self.ui.typeBox.setCurrentIndex(self.ui.typeBox.count()-1)

        if self.event_filter and self.event_filter != event.type:
            return

        if not event.contact:
            return

        contact = event.contact
        contact.backend = event.backend
        status = ''

        if contact.status == contact.STATUS_ONLINE:
            status = u'Online'
            status_color = 0x00aa00
        elif contact.status == contact.STATUS_OFFLINE:
            status = u'Offline'
            status_color = 0xff0000
        elif contact.status == contact.STATUS_AWAY:
            status = u'Away'
            status_color = 0xffad16
        else:
            status = u'Unknown'
            status_color = 0xaaaaaa

        if contact.status_msg:
            status += u' — %s' % contact.status_msg

        name = '<h2>%s</h2><font color="#%06X">%s</font><br /><i>%s</i>' % (contact.name, status_color, status, event.backend)
        date = event.date.strftime('%Y-%m-%d %H:%M')
        type = event.type
        message = event.message

        item = QTreeWidgetItem(None, [name, date, type, message])
        item.setData(0, Qt.UserRole, event)
        if contact.photos is NotLoaded:
            process = QtDo(self.weboob, lambda c: self.setPhoto(c, item))
            process.do('fillobj', contact, ['photos'], backends=contact.backend)
            self.photo_processes[contact.id] = process
        elif len(contact.photos) > 0:
            if not self.setPhoto(contact, item):
                photo = contact.photos.values()[0]
                process = QtDo(self.weboob, lambda p: self.setPhoto(contact, item))
                process.do('fillobj', photo, ['thumbnail_data'], backends=contact.backend)
                self.photo_processes[contact.id] = process

        self.ui.eventsList.addTopLevelItem(item)
        self.ui.eventsList.resizeColumnToContents(0)
        self.ui.eventsList.resizeColumnToContents(1)
 def setResults(self, results_list):
     self.results_list.clear()
     self.selectableitems = {}
     for (pointer, count, pokestring) in results_list:
         p = QTreeWidgetItem(['%X'%pointer, repr(count), pokestring.getText()])
         p.setData(0, Qt.UserRole, pointer)
         #self.selectableitems[p] = pointer
         self.results_list.addTopLevelItem(p)
 def addNode(self, parent, text="", data=""):
     node = QTreeWidgetItem(parent)
     node.setText(0, text)
     node.setCheckState(0, Qt.Unchecked)
     node.setFlags(Qt.ItemIsUserCheckable | Qt.ItemIsEnabled
                   | Qt.ItemIsSelectable)
     node.setData(0, Qt.UserRole, data)
     return node
Beispiel #27
0
    def _populate_reporting_tab(self):
        """Populate trees about layers."""
        self.tree.clear()
        self.add_layer.setEnabled(False)
        self.remove_layer.setEnabled(False)
        self.move_up.setEnabled(False)
        self.move_down.setEnabled(False)
        self.tree.setColumnCount(1)
        self.tree.setRootIsDecorated(False)
        self.tree.setHeaderHidden(True)

        analysis_branch = QTreeWidgetItem(self.tree.invisibleRootItem(),
                                          [FROM_ANALYSIS['name']])
        analysis_branch.setFont(0, bold_font)
        analysis_branch.setExpanded(True)
        analysis_branch.setFlags(Qt.ItemIsEnabled)

        if self._multi_exposure_if:
            expected = self._multi_exposure_if.output_layers_expected()
            for group, layers in expected.iteritems():
                group_branch = QTreeWidgetItem(analysis_branch, [group])
                group_branch.setFont(0, bold_font)
                group_branch.setExpanded(True)
                group_branch.setFlags(Qt.ItemIsEnabled)

                for layer in layers:
                    layer = definition(layer)
                    if layer.get('allowed_geometries', None):
                        item = QTreeWidgetItem(group_branch,
                                               [layer.get('name')])
                        item.setData(0, LAYER_ORIGIN_ROLE,
                                     FROM_ANALYSIS['key'])
                        item.setData(0, LAYER_PARENT_ANALYSIS_ROLE, group)
                        item.setData(0, LAYER_PURPOSE_KEY_OR_ID_ROLE,
                                     layer['key'])
                        item.setFlags(Qt.ItemIsEnabled | Qt.ItemIsSelectable)

        canvas_branch = QTreeWidgetItem(self.tree.invisibleRootItem(),
                                        [FROM_CANVAS['name']])
        canvas_branch.setFont(0, bold_font)
        canvas_branch.setExpanded(True)
        canvas_branch.setFlags(Qt.ItemIsEnabled)

        # List layers from the canvas
        loaded_layers = QgsMapLayerRegistry.instance().mapLayers().values()
        canvas_layers = self.iface.mapCanvas().layers()
        flag = setting('visibleLayersOnlyFlag', expected_type=bool)
        for loaded_layer in loaded_layers:
            if flag and loaded_layer not in canvas_layers:
                continue

            title = loaded_layer.name()
            item = QTreeWidgetItem(canvas_branch, [title])
            item.setData(0, LAYER_ORIGIN_ROLE, FROM_CANVAS['key'])
            item.setData(0, LAYER_PURPOSE_KEY_OR_ID_ROLE, loaded_layer.id())
            item.setFlags(Qt.ItemIsEnabled | Qt.ItemIsSelectable)

        self.tree.resizeColumnToContents(0)
Beispiel #28
0
    def makeTreeItem(self, item):
        if self.creator and item.getType() != self.creator.getType():
            item = self.creator(item)  #make new item

        textString = item.stringList()  #has all info
        treeItem = QTreeWidgetItem(self.ui.treeWidget, textString)
        treeItem.setData(0, 0, item)

        return treeItem
Beispiel #29
0
    def makeTreeItem(self,item):
        if self.creator and item.getType() != self.creator.getType():
            item = self.creator(item) #make new item
            
        textString = item.stringList() #has all info
        treeItem = QTreeWidgetItem(self.ui.treeWidget, textString)
        treeItem.setData(0,0,item)

        return treeItem
Beispiel #30
0
 def setData(self, column, role, value):
     QTreeWidgetItem.setData(self, column, role, value)
     if role == Qt.CheckStateRole:
         if self.childCount() != 0:
             for childIndex in xrange(0, self.childCount()):
                 child = self.child(childIndex)
                 child.setData(0, Qt.CheckStateRole, value)
                 self.setPostProcessState(str(child.text(0)), value)
         else:
             self.setPostProcessState(str(self.text(0)), value)
 def setResults(self, results_list):
     self.results_list.clear()
     self.selectableitems = {}
     for (pointer, count, pokestring) in results_list:
         p = QTreeWidgetItem(
             ['%X' % pointer,
              repr(count),
              pokestring.getText()])
         p.setData(0, Qt.UserRole, pointer)
         #self.selectableitems[p] = pointer
         self.results_list.addTopLevelItem(p)
Beispiel #32
0
 def recusive_add_group(self,  parentTreeWidgetItem,  pwGroup):
     treeWidgetItem = QTreeWidgetItem(parentTreeWidgetItem)
     treeWidgetItem.setText(0,  pwGroup.Name)
     treeWidgetItem.setData(1,  Qt.UserRole,  pwGroup)
     
     for childGroup in pwGroup.Groups:
         self.recusive_add_group(treeWidgetItem,  childGroup)
             
     treeWidgetItem.setExpanded(True)
     
     return treeWidgetItem
Beispiel #33
0
 def setData(self, column, role, variant):
     if role == Qt.CheckStateRole:
         if variant == Qt.Checked:
             self.__category.selected(True)
             for pageItem in self.__pageItems:
                 pageItem.setCheckState(0, Qt.Checked)
         else:
             self.__category.selected(False)
             for pageItem in self.__pageItems:
                 pageItem.setCheckState(0, Qt.Unchecked)
     QTreeWidgetItem.setData(self, column, role, variant)
Beispiel #34
0
    def add_program_to_tree(self, program):
        program_info = ProgramInfoMain(self.session, self.script_manager, self.image_version, self.executable_versions, program)
        program_info.name_changed.connect(self.refresh_program_name)
        program_info.status_changed.connect(self.refresh_program_status)

        item = QTreeWidgetItem([program.cast_custom_option_value('name', unicode, '<unknown>'),
                                get_program_short_status(program)])
        item.setData(0, Qt.UserRole, program_info)

        self.tree_programs.addTopLevelItem(item)
        self.stacked_container.addWidget(program_info)
Beispiel #35
0
    def recusive_add_group(self, parentTreeWidgetItem, pwGroup):
        treeWidgetItem = QTreeWidgetItem(parentTreeWidgetItem)
        treeWidgetItem.setText(0, pwGroup.Name)
        treeWidgetItem.setData(1, Qt.UserRole, pwGroup)

        for childGroup in pwGroup.Groups:
            self.recusive_add_group(treeWidgetItem, childGroup)

        treeWidgetItem.setExpanded(True)

        return treeWidgetItem
Beispiel #36
0
    def makeTreeItem(self,item):#Overload if needed
        if item.getType() != 'VisitAnimal':
            item = SqlHandler.VisitAnimal(item)
        
        textString = item.stringList()
        textString.insert(self.iconplace, '')
        treeItem = QTreeWidgetItem(self.ui.treeWidget, textString)
        treeItem.setIcon(self.iconplace,self.getIcon(item.animal.picurePath()))
        treeItem.setData(0,0,item)

        return treeItem
 def _addRequirements(self):
     for requirement, component, reason, optional in self._requirements:
         item = QTreeWidgetItem()
         item.setCheckState(0, Qt.Checked)
         if not optional:
             item.setFlags(Qt.ItemFlags(int(item.flags()) & ~Qt.ItemIsEnabled))
         item.setText(0, requirement)
         item.setText(1, reason)
         item.setText(2, component)
         item.setData(0, self._REQUIREMENT_ROLE, QVariant(requirement))
         self._reqTable.addTopLevelItem(item)
Beispiel #38
0
class TaskItem(Base):
    __tablename__ = 'tasks'

    id = Column(Integer, primary_key=True)
    task = Column(String)
    priority = Column(Integer)
    description = Column(String)
    complete = Column(Integer)
    date = Column(Date)

    def __init__(self, task, priority, description, complete, date):
        self.task = task
        self.priority = priority
        self.description = description
        self.complete = complete
        self.date = date
        #self.id = id
        

    def makeWidget(self):
        self.treeWidget = QTreeWidgetItem()
        timeleft = int((self.date - datetime.date.today()).days)
        weekday = self.date.strftime("%A")

        if self.complete:
            sofont = QtGui.QFont()
            font = QtGui.QFont()
            sofont.setStrikeOut(1)
            self.treeWidget.setFont(0, sofont)
    
        self.treeWidget.setData(0, 0, self.task)
        self.treeWidget.setData(1, 0, self.priority)
        self.treeWidget.setData(3, 0, self.id)
        
        if timeleft <2:
            pass
        elif timeleft >1 and timeleft <=7:
            self.treeWidget.setData(2, 0, str(weekday))
        else:
            self.treeWidget.setData(2, 0, str(self.date))

        self.treeWidget.setCheckState(0, self.complete)

        return self.treeWidget

    def timeLeft(self):
        return (self.date - datetime.date.today()).days
    def getCompleted(self):
        return self.complete
    def getWidget(self):
        return self.treeWidget

    def __repr__(self):
        return self.task
Beispiel #39
0
        def add_children(child_nodes, parent):
            children = []
            for node in child_nodes:
                twitem = QTreeWidgetItem((node['label'], ))
                twitem.setFlags(Qt.ItemIsUserCheckable | Qt.ItemIsEnabled)
                twitem.setCheckState(0, Qt.Unchecked)
                twitem.setData(0, Qt.UserRole, node)
                if 'children' in node:
                    add_children(node['children'], twitem)
                children.append(twitem)

            parent.addChildren(children)
Beispiel #40
0
        def add_children(child_nodes, parent):
            children = []
            for node in child_nodes:
                twitem = QTreeWidgetItem((node['label'], ))
                twitem.setFlags(Qt.ItemIsUserCheckable | Qt.ItemIsEnabled)
                twitem.setCheckState(0, Qt.Unchecked)
                twitem.setData(0, Qt.UserRole, node)
                if 'children' in node:
                    add_children(node['children'], twitem)
                children.append(twitem)

            parent.addChildren(children)
    def populate_classified_values(self, unassigned_values, assigned_values,
                                   default_classes):
        """Populate lstUniqueValues and treeClasses.from the parameters.

        :param unassigned_values: List of values that haven't been assigned
            to a class. It will be put in self.lstUniqueValues.
        :type unassigned_values: list

        :param assigned_values: Dictionary with class as the key and list of
            value as the value of the dictionary. It will be put in
            self.treeClasses.
        :type assigned_values: dict

        :param default_classes: Default classes from unit.
        :type default_classes: list
        """
        # Populate the unique values list
        self.lstUniqueValues.clear()
        self.lstUniqueValues.setSelectionMode(
            QAbstractItemView.ExtendedSelection)
        for value in unassigned_values:
            value_as_string = value is not None and unicode(value) or 'NULL'
            list_item = QListWidgetItem(self.lstUniqueValues)
            list_item.setFlags(Qt.ItemIsEnabled | Qt.ItemIsSelectable
                               | Qt.ItemIsDragEnabled)
            list_item.setData(Qt.UserRole, value)
            list_item.setText(value_as_string)
            self.lstUniqueValues.addItem(list_item)
        # Populate assigned values tree
        self.treeClasses.clear()
        self.treeClasses.invisibleRootItem().setFlags(Qt.ItemIsEnabled)
        for default_class in default_classes:
            # Create branch for class
            tree_branch = QTreeWidgetItem(self.treeClasses)
            tree_branch.setFlags(Qt.ItemIsDropEnabled | Qt.ItemIsEnabled)
            tree_branch.setExpanded(True)
            tree_branch.setFont(0, bold_font)
            if 'name' in default_class:
                default_class_name = default_class['name']
            else:
                default_class_name = default_class['key']
            tree_branch.setText(0, default_class_name)
            tree_branch.setData(0, Qt.UserRole, default_class['key'])
            if 'description' in default_class:
                tree_branch.setToolTip(0, default_class['description'])
            # Assign known values
            for value in assigned_values[default_class['key']]:
                string_value = value is not None and unicode(value) or 'NULL'
                tree_leaf = QTreeWidgetItem(tree_branch)
                tree_leaf.setFlags(Qt.ItemIsEnabled | Qt.ItemIsSelectable
                                   | Qt.ItemIsDragEnabled)
                tree_leaf.setData(0, Qt.UserRole, value)
                tree_leaf.setText(0, string_value)
Beispiel #42
0
    def makeTreeItem(self, item):  #Overload if needed
        if item.getType() != 'VisitAnimal':
            item = SqlHandler.VisitAnimal(item)

        textString = item.stringList()
        textString.insert(self.iconplace, '')
        treeItem = QTreeWidgetItem(self.ui.treeWidget, textString)
        treeItem.setIcon(self.iconplace,
                         self.getIcon(item.animal.picurePath()))
        treeItem.setData(0, 0, item)

        return treeItem
Beispiel #43
0
    def makeTreeItem(self,item):
        if 'Base' in item.getType():
            if item.hasList():
                item = type(item).ObjectCreator(type(item))(item.price, item.description, base=item, items=item.items)
            else:
                item = type(item).ObjectCreator(type(item))(item.price, item.description, base=item)
            self.session.add(item)

        treeItem = QTreeWidgetItem(self.ui.treeWidget, item.stringList())
        treeItem.setData(0,0,item)

        return treeItem
Beispiel #44
0
    def updateTimes(self, times):
    
        self.timesList.clear()

        for value in times:
        
            item = QTreeWidgetItem()
            item.setText(0, value.strftime(self.iso_format))
            item.setData(0, Qt.UserRole, value)
            self.timesList.addTopLevelItem(item)

        self.timesList.resizeColumnToContents(0)
Beispiel #45
0
    def show_termins_in_list(self, page):
        self.currentPage = page
        # фильтрация списка терминов
        search_word = self.searchLineEdit.text()
        if search_word.strip() != '':
            search_str = search_word
        else:
            search_str = ''

        # показ уже обработанных терминов
        if self.showLinkedCheck.isChecked():
            show_linked = 1
        else:
            show_linked = 0

        query = QSqlQuery(self.local_cn)
        LIMIT = int(self.terminsPerPageComboBos.currentText())
        OFFSET = (page - 1) * LIMIT
        query.prepare(show_termins_in_list_query)
        query.bindValue(':search_str', search_str + '%')
        query.bindValue(':linked', show_linked)
        query.bindValue(':limit', LIMIT.__str__())
        query.bindValue(':offset', OFFSET.__str__())
        if query.exec_():
            self.root.takeChildren()
            i = 1
            f = QFont()
            f.setBold(True)
            while query.next():
                c = QTreeWidgetItem()
                c.setText(0, query.value(0))  # Заглавное слово
                c.setData(1, 0, query.value(1))  # uuid
                c.setData(2, 0, i)  # номерок
                if query.value(2) == 1:
                    c.setFont(0, f)
                self.root.addChild(c)
                i += 1

            pages = 1
            query.prepare(show_termins_in_list_count_query)
            query.bindValue(':search_str', search_str + '%')
            query.bindValue(':linked', show_linked)
            if query.exec_() and query.next():
                try:
                    pages = math.ceil(query.value(0) / LIMIT)
                except:
                    pages = 1

            self.draw_paginator(pages, page)
        else:
            print(query.lastError().text())
            print("not exec")
        self.terminsTreeWidget.scrollToTop()
Beispiel #46
0
    def _insert_message(self, message, top):
        item = QTreeWidgetItem(None, [message.title or '', message.sender or 'Unknown',
                                      time.strftime('%Y-%m-%d %H:%M:%S', message.date.timetuple())])
        item.setData(0, Qt.UserRole, message)
        if message.flags & message.IS_UNREAD:
            item.setForeground(0, QBrush(Qt.darkYellow))
            item.setForeground(1, QBrush(Qt.darkYellow))
            item.setForeground(2, QBrush(Qt.darkYellow))

        top.addChild(item)

        for child in message.children:
            self._insert_message(child, item)
Beispiel #47
0
		def _add_children(item, mod):
			for ref in mod.refs:
				try:
					childMod = self.project.get_module_at_filename(ref)
				except KeyError:
					childMod = self.project.get_module_at_dottedname(ref)

				if childMod in visited: return
				visited.add(childMod)

				child = QTreeWidgetItem(item)
				child.setText(0, ref)
				self._setup_font(child, ref, childMod.owner)
				child.setIcon(0, self._select_icon(childMod.owner))
				child.setData(0, self.TYPE_MODULE, childMod)
				child.setData(0, self.TYPE_NODE, None)
				item.addChild(child)
				_add_children(child, childMod)

			for name, sym in mod.symbols.items():
				if not isinstance(sym, Name): continue
				child = QTreeWidgetItem(item)
				child.setText(0, name)
				self._setup_font(child, name, sym)
				child.setIcon(0, self._select_icon(sym))
				child.setData(0, self.TYPE_MODULE, mod)
				child.setData(0, self.TYPE_NODE, mod.symbols[name])
				item.addChild(child)
    def _load_bookmarks(self):
        self.bookmark_tree.clear()
        lane_index = self.topLevelOperatorView.current_view_index()
        lane_nickname = self.topLevelOperatorView.InputImages.meta.nickname or "Lane {}".format(lane_index)
        bookmarks = self.topLevelOperatorView.Bookmarks.value
        group_item = QTreeWidgetItem( self.bookmark_tree, QStringList(lane_nickname) )

        for coord, notes in bookmarks:
            item = QTreeWidgetItem( group_item, QStringList() )
            item.setText(0, str(coord))
            item.setData(0, Qt.UserRole, (coord, notes))
            item.setText(1, notes)

        self.bookmark_tree.expandAll()
Beispiel #49
0
    def loadPagesList(self, checkable=False):
        self.clear()
        for section in self.user_settings['pagesindex'].sections:
            root = QTreeWidgetItem([section.title])
            root.setData(0, Qt.UserRole, QVariant(QString(section.name)))
            root.setData(0, Qt.DecorationRole, QVariant(QIcon(section.icon)))
            self.addTopLevelItem(root)

            for page_id, page in section.pages:
                if not page:
                    page = self.getPage(page_id)
                if page.title:
                    page_title = page.title
                else:
                    page_title = tr('(No name)')
                item = QTreeWidgetItem([page_title])
                item.setData(0, Qt.UserRole ,QVariant(QString(page_id)))
                if checkable:
                    item.setFlags(item.flags() | Qt.ItemIsUserCheckable)
                    item.setCheckState(0, Qt.Unchecked)
                root.addChild(item)
                if page == self.window.current_page:
                    f = QFont()
                    f.setWeight(QFont.Bold)
                    item.setData(0, Qt.FontRole, QVariant(f))
                    self.setCurrentItem(item)

        self.expandAll()
Beispiel #50
0
    def makeTreeItem(self, item):  #Overload if needed
        textString = item.stringList()
        #add '' to icon place
        treeItem = None
        if self.iconplace >= 0:
            textString.insert(self.iconplace, '')
            print('makeTreeItem() textString', textString)
            treeItem = QTreeWidgetItem(self.ui.treeWidget, textString)
            treeItem.setIcon(self.iconplace, self.getIcon(item.picurePath()))
        else:
            print('makeTreeItem() textString', textString)
            treeItem = QTreeWidgetItem(self.ui.treeWidget, textString)

        treeItem.setData(0, 0, item)
        return treeItem
Beispiel #51
0
 def makeTreeItem(self,item):#Overload if needed
     textString = item.stringList()
     #add '' to icon place
     treeItem = None
     if self.iconplace >= 0:
         textString.insert(self.iconplace, '')
         print('makeTreeItem() textString', textString)
         treeItem = QTreeWidgetItem(self.ui.treeWidget,textString)
         treeItem.setIcon(self.iconplace,self.getIcon(item.picurePath()))
     else:
         print('makeTreeItem() textString', textString)
         treeItem = QTreeWidgetItem(self.ui.treeWidget,textString)
     
     treeItem.setData(0,0,item)
     return treeItem
    def createSeparatorItem(self):
        """
        Creates a new separator item.
        
        :return     <QTreeWidgetItem>
        """
        item = QTreeWidgetItem(['                                    '])
        font = item.font(0)
        font.setStrikeOut(True)
        item.setFont(0, font)
        item.setData(0, Qt.UserRole, qt.wrapVariant('separator'))
        flags = item.flags()
        flags ^= Qt.ItemIsDropEnabled
        item.setFlags(flags)

        return item
 def createMenuItem( self, title ):
     """
     Creates a new menu item with the given title.
     
     :param      title | <str>
     
     :return     <QTreeWidgetItem>
     """
     item = QTreeWidgetItem([title])
     ico = projexui.resources.find('img/folder.png')
     
     item.setIcon(0, QIcon(ico))
     item.setSizeHint(0, QSize(120, 20))
     item.setData(0, Qt.UserRole, qt.wrapVariant('menu'))
     
     return item
    def _load_bookmarks(self):
        self.bookmark_tree.clear()
        lane_index = self.topLevelOperatorView.current_view_index()
        lane_nickname = self.topLevelOperatorView.InputImages.meta.nickname or "Lane {}".format(
            lane_index)
        bookmarks = self.topLevelOperatorView.Bookmarks.value
        group_item = QTreeWidgetItem(self.bookmark_tree,
                                     QStringList(lane_nickname))

        for coord, notes in bookmarks:
            item = QTreeWidgetItem(group_item, QStringList())
            item.setText(0, str(coord))
            item.setData(0, Qt.UserRole, (coord, notes))
            item.setText(1, notes)

        self.bookmark_tree.expandAll()
    def createMenuItem(self, title):
        """
        Creates a new menu item with the given title.
        
        :param      title | <str>
        
        :return     <QTreeWidgetItem>
        """
        item = QTreeWidgetItem([title])
        ico = projexui.resources.find('img/folder.png')

        item.setIcon(0, QIcon(ico))
        item.setSizeHint(0, QSize(120, 20))
        item.setData(0, Qt.UserRole, qt.wrapVariant('menu'))

        return item
 def createSeparatorItem( self ):
     """
     Creates a new separator item.
     
     :return     <QTreeWidgetItem>
     """
     item = QTreeWidgetItem(['                                    '])
     font = item.font(0)
     font.setStrikeOut(True)
     item.setFont(0, font)
     item.setData(0, Qt.UserRole, qt.wrapVariant('separator'))
     flags = item.flags()
     flags ^= Qt.ItemIsDropEnabled
     item.setFlags(flags)
     
     return item
Beispiel #57
0
    def makeTreeItem(self, item):
        if 'Base' in item.getType():
            if item.hasList():
                item = type(item).ObjectCreator(type(item))(item.price,
                                                            item.description,
                                                            base=item,
                                                            items=item.items)
            else:
                item = type(item).ObjectCreator(type(item))(item.price,
                                                            item.description,
                                                            base=item)
            self.session.add(item)

        treeItem = QTreeWidgetItem(self.ui.treeWidget, item.stringList())
        treeItem.setData(0, 0, item)

        return treeItem
Beispiel #58
0
    def autoSuggest(self):
        self.ui.popup.setUpdatesEnabled(False)
        self.ui.popup.clear()
        stringList = None

        print(self.params)
        print(self.function)

        if self.params != None:
            items_list = self.function(session=self.session,
                                       question=self.ui.editor.text(),
                                       params=self.params)
        else:
            items_list = self.function(session=self.session,
                                       question=self.ui.editor.text())

        for item in items_list:  #TODO test that this works
            TreeWidgetItem = QTreeWidgetItem(self.ui.popup)
            stringList = item.stringList()
            if self.ui.popup.columnCount() < len(stringList):
                self.ui.popup.setColumnCount(len(stringList))

            for index in range(0, len(stringList)):
                TreeWidgetItem.setText(index, stringList[index])
            TreeWidgetItem.setData(self.itemplace, 0, item)

        self.ui.popup.setCurrentItem(self.ui.popup.topLevelItem(0))

        if stringList != None:
            for index in range(0, len(stringList)):
                self.ui.popup.resizeColumnToContents(index)

        self.ui.popup.adjustSize()
        self.ui.popup.setUpdatesEnabled(True)

        self.ui.popup.resize(
            self.ui.editor.width() if self.ui.editor.width() > 300 else 300,
            self.ui.popup.sizeHintForRow(0) * 10)

        self.ui.popup.move(
            self.ui.editor.mapToGlobal(QPoint(0, self.ui.editor.height())))
        self.ui.popup.setFocus()
        self.ui.popup.show()
Beispiel #59
0
    def _insert_message(self, message, top):
        item = QTreeWidgetItem(None, [message.title or '', message.sender or 'Unknown',
                                      time.strftime('%Y-%m-%d %H:%M:%S', message.date.timetuple())])
        item.setData(0, Qt.UserRole, message)
        if message.flags & message.IS_UNREAD:
            item.setForeground(0, QBrush(Qt.darkYellow))
            item.setForeground(1, QBrush(Qt.darkYellow))
            item.setForeground(2, QBrush(Qt.darkYellow))

        if top is not None:
            # threads
            top.addChild(item)
        else:
            # discussion
            self.ui.messagesTree.invisibleRootItem().insertChild(0, item)

        if message.children is not None:
            for child in message.children:
                self._insert_message(child, top and item)