def cb_success(programs):
            sorted_programs = {}

            for program in programs:
                first_upload = program.cast_custom_option_value('first_upload', int, 0)

                if first_upload in sorted_programs:
                    sorted_programs[first_upload][program.identifier] = program
                else:
                    sorted_programs[first_upload] = {program.identifier: program}

            for first_upload in sorted(sorted_programs.keys()):
                for identifier in sorted(sorted_programs[first_upload].keys()):
                    program  = sorted_programs[first_upload][identifier]
                    language = program.cast_custom_option_value('language', str, '<unknown>')

                    try:
                        language = Constants.get_language_display_name(language)
                    except:
                        pass

                    item = QTreeWidgetItem([program.cast_custom_option_value('name', str, '<unknown>'), identifier, language])

                    self.tree_programs.addTopLevelItem(item)
                    item.setSelected(True)

            self.refresh_in_progress = False
            self.update_ui_state()
            self.tree_programs.setFocus()
        def cb_success(result):
            programs, message = result

            if message != None:
                QMessageBox.critical(get_main_window(), 'Import Error', message)
            else:
                sorted_programs = {}

                for program in programs:
                    first_upload = program[4]

                    if first_upload in sorted_programs:
                        sorted_programs[first_upload][program[1]] = program
                    else:
                        sorted_programs[first_upload] = {program[1]: program}

                for first_upload in sorted(sorted_programs.keys()):
                    for identifier in sorted(sorted_programs[first_upload].keys()):
                        program = sorted_programs[first_upload][identifier]
                        item    = QTreeWidgetItem(program[0:4])

                        self.tree_programs.addTopLevelItem(item)

                        item.setSelected(True)

            self.refresh_in_progress = False
            self.update_ui_state()
            self.tree_programs.setFocus()
Exemple #3
0
    def appendPage(self, path, widget, icon=None):
        """Append page to the tree. Called by a plugin for creating own page. Example:
        ::

            widget = MitSchemeSettings(dialog)
            dialog.appendPage(u"Modes/MIT Scheme", widget, QIcon(':/enkiicons/languages/scheme.png'))

        """
        pathParts = path.split('/')
        if len(pathParts) == 1:
            parentItem = None
        else:
            parentItem = self._itemByPath(pathParts[:-1])

        twItem = QTreeWidgetItem([pathParts[-1]])
        if icon is not None:
            twItem.setIcon(0, icon)
        else:
            twItem.setIcon(0, QIcon(':/enkiicons/transparent.png'))

        if parentItem is not None:
            parentItem.addChild(twItem)
            self.twMenu.expandAll()
        else:
            self.twMenu.addTopLevelItem(twItem)

        self.swPages.addWidget(widget)
        self._pageForItem[path] = widget
 def update(self):
     if self.conn.poll():
         msg = self.conn.recv()
         if msg[0] == 'pkt':
             if msg[1][0] == 'parsepkt':
                 if self.ui.treeWidget.topLevelItemCount() and self.ui.treeWidget.topLevelItem(0).text(0) == 'parsepkt':
                     self.ui.treeWidget.takeTopLevelItem(0)
                 item = QTreeWidgetItem(None, msg[1])
                 for i in range(self.ui.treeWidget.columnCount()):
                     item.setBackground(i, QBrush(Qt.green))
                     if 5 < i < 10:
                         item.setTextAlignment(i, Qt.AlignRight)
                 self.ui.treeWidget.insertTopLevelItem(0, item)
                 self.ui.treeWidget.scrollToTop()
                 self.parsepkt = msg[1:]
             else:
                 self.buf.append(msg[1:])
                 self.add_treeitem(msg[1:])
                 if self.ui.checkBox_autoscroll.isChecked():
                     self.ui.treeWidget.scrollToBottom()
             for i in range(self.ui.treeWidget.columnCount()):
                  self.ui.treeWidget.resizeColumnToContents(i)
         elif msg[0] == 'msg':
             self.ui.plainTextEdit_log.appendPlainText('[msg]%s.' % msg[1])
         elif msg[0] == 'err':
             self.ui.plainTextEdit_log.appendPlainText(msg[1])
    def __createServerCertificateEntry(self, server, cert):
        """
        Private method to create a server certificate entry.
        
        @param server server name of the certificate (string)
        @param cert certificate to insert (QSslCertificate)
        """
        # step 1: extract the info to be shown
        if qVersion() >= "5.0.0":
            organisation = Utilities.decodeString(", ".join(cert.subjectInfo(QSslCertificate.Organization)))
            commonName = Utilities.decodeString(", ".join(cert.subjectInfo(QSslCertificate.CommonName)))
        else:
            organisation = Utilities.decodeString(cert.subjectInfo(QSslCertificate.Organization))
            commonName = Utilities.decodeString(cert.subjectInfo(QSslCertificate.CommonName))
        if organisation is None or organisation == "":
            organisation = self.tr("(Unknown)")
        if commonName is None or commonName == "":
            commonName = self.tr("(Unknown common name)")
        expiryDate = cert.expiryDate().toString("yyyy-MM-dd")

        # step 2: create the entry
        items = self.serversCertificatesTree.findItems(organisation, Qt.MatchFixedString | Qt.MatchCaseSensitive)
        if len(items) == 0:
            parent = QTreeWidgetItem(self.serversCertificatesTree, [organisation])
        else:
            parent = items[0]

        itm = QTreeWidgetItem(parent, [commonName, server, expiryDate])
        itm.setData(0, self.CertRole, cert.toPem())
    def __init__(self):
        QTreeWidgetItem.__init__(self)
        self.download_info = None
        self._logger = logging.getLogger('TriblerGUI')

        bar_container = QWidget()
        bar_container.setLayout(QVBoxLayout())
        bar_container.setStyleSheet("background-color: transparent;")

        self.progress_slider = QProgressBar()

        # We have to set a zero pixel border to get the background working on Mac.
        self.progress_slider.setStyleSheet("""
        QProgressBar {
            background-color: white;
            color: black;
            font-size: 12px;
            text-align: center;
            border: 0px solid transparent;
        }

        QProgressBar::chunk {
            background-color: #e67300;
        }
        """)

        bar_container.layout().addWidget(self.progress_slider)
        bar_container.layout().setContentsMargins(4, 4, 8, 4)

        self.progress_slider.setAutoFillBackground(True)
        self.bar_container = bar_container
 def on_treeWidget_itemExpanded(self, item):
     if item.checkState(1) != Qt.Checked:
         categoryParentID = item.text(1)
         session = Session()
         count = session.query(Category).filter(Category.category_parent_id == categoryParentID).count()
         if count == 0:
             shopping = Shopping(warnings = False)
             response = shopping.execute(
                 'GetCategoryInfo',
                 {
                     'CategoryID': categoryParentID,
                     'IncludeSelector': 'ChildCategories'
                 }
             )
             reply = response.reply
             categoryArray = reply.CategoryArray.Category
             for category in categoryArray:
                 if category.CategoryID == categoryParentID:
                     continue
                 session.add(Category(
                     name=category.CategoryName,
                     path=category.CategoryNamePath,
                     category_id=category.CategoryID,
                     category_parent_id=category.CategoryParentID,
                     leaf_category=category.LeafCategory)
                 )
             session.commit()
             
         for category in session.query(Category).filter(Category.category_parent_id == categoryParentID).order_by(Category.id).all():
             child = QTreeWidgetItem(item, [category.name, category.category_id, category.path, category.leaf_category])
             if category.leaf_category == 'false':
                 child.setChildIndicatorPolicy(QTreeWidgetItem.ShowIndicator)
         item.setCheckState(1, Qt.Checked)
Exemple #8
0
    def populateTemplates(self):
        self.tree.clear()
        self.tree.setIndentation(0)

        # Add templates
        item = self.addTopLevelItem(self.tr("Fiction"))
        templates = [i for i in self.templates() if i[2] == "Fiction"]
        for t in templates:
            sub = QTreeWidgetItem(item, [t[0]])

        # Add templates: non-fiction
        item = self.addTopLevelItem(self.tr("Non-fiction"))
        templates = [i for i in self.templates() if i[2] == "Non-fiction"]
        for t in templates:
            sub = QTreeWidgetItem(item, [t[0]])


        # Add Demo project
        item = self.addTopLevelItem(self.tr("Demo projects"))
        dir = QDir(appPath("sample-projects"))
        for f in dir.entryList(["*.msk"], filters=QDir.Files):
            sub = QTreeWidgetItem(item, [f[:-4]])
            sub.setData(0, Qt.UserRole, f)

        self.tree.expandAll()
Exemple #9
0
class PlaylistUI(QTreeWidget):
    def __init__(self):
        super().__init__()
        self.test = QTreeWidgetItem()
        self.test.setText(0, "Hello")
        self.header().close()
        self.addTopLevelItem(self.test)
 def restore_item(self, datastream, _):
     num_childs = datastream.readUInt32()
     for _ in range(0, num_childs):
         child = QTreeWidgetItem()
         child.read(datastream)
         self.bar.addAction(obtainAction(child.text(0), self.iface))
         self.restore_item(datastream, child)
Exemple #11
0
 def build_menu_item(action):
     """Return a QTreeWidgetItem with children for all the actions in the submenu."""
     menuitem = QTreeWidgetItem()
     text = qutil.removeAccelerator(action.text())
     menuitem.setText(0, _("Menu {name}").format(name=text))
     add_actions(menuitem, action.menu().actions())
     return menuitem
 def restore_item(self, datastream, item):
     num_childs = datastream.readUInt32()
     for i in range(0, num_childs):
         child = QTreeWidgetItem()
         child.read(datastream)
         item.addChild(child) 
         self.restore_item(datastream, child)
Exemple #13
0
 def __init__(self, action, collection, name):
     QTreeWidgetItem.__init__(self)
     self.collection = collection
     self.name = name
     self.setIcon(0, action.icon())
     self.setText(0, qutil.removeAccelerator(action.text()))
     self._shortcuts = {}
    def populate_item_tree(self, nodes):
        _translate = QCoreApplication.translate
        self.selected_nodes = []
        with Session() as session:
            all_selected_nodes = [n.id for n in session.query(Node)]
            for n in session.query(Node):
                if n.parent_id not in all_selected_nodes and n.id not in self.selected_nodes:
                    self.selected_nodes.append(n.id)

        for node in sorted(nodes, key=lambda n: n.title):
            tree_item = QTreeWidgetItem(self.treeWidget)
            tree_item.setCheckState(self.PROJECT_SYNC_COLUMN,
                                    Qt.Checked if node.id in self.selected_nodes else Qt.Unchecked)
            tree_item.setText(self.PROJECT_NAME_COLUMN,
                              _translate('Preferences', '{} - {}'.format(node.title, node.id)))

            self.tree_items.append((tree_item, node))

        self.treeWidget.resizeColumnToContents(self.PROJECT_SYNC_COLUMN)
        self.treeWidget.resizeColumnToContents(self.PROJECT_NAME_COLUMN)
        self.treeWidget.unsetCursor()
        self.treeWidget.setStyleSheet("background-color: white")
        self.changeFolderButton_2.setEnabled(True)
        self.pushButton.setEnabled(True)
        self.pushButton_2.setEnabled(True)
Exemple #15
0
    def init_playlist(self, lib):
        for song_meta in lib.values():
            info = ['' for i in range(7)]
            try:
                for i in range(7):
                    if i == 4:
                        length = int(song_meta.get(self.meta[i])[0]) / 1000
                        mins = int(length / 60)
                        secs = int(length - 60 * mins)
                        info[i] = str(mins) + ":%02d" % secs
                    elif i == 5:
                        info[i] = song_meta.get(self.meta[i])[0] + " kbit/s"
                    else:
                        info[i] = song_meta.get(self.meta[i])[0]
            except:
                pass

            item = QTreeWidgetItem()
            for i in range(7):
                item.setText(i, info[i])

            item.setData(0, 1, QUrl.fromLocalFile(song_meta.get("DIR")))
            self.addTopLevelItem(item)

        headers = ["#", "Title", "Artist", "Album", "Dur.", "Bitrate", "Genre"]
        self.setColumnCount(6)
        self.header().setDefaultAlignment(Qt.AlignCenter)
        self.setHeaderLabels(headers)
        self.setColumnWidth(0, 50)
        self.setColumnWidth(1, 200)
        self.setColumnWidth(2, 150)
        self.setColumnWidth(3, 150)
        self.setColumnWidth(4, 50)
        self.setColumnWidth(5, 100)
        self.setColumnWidth(6, 50)
Exemple #16
0
    def initialize_with_rss_feeds(self, rss_feeds):
        self.my_channel_rss_feeds_list.clear()
        for feed in rss_feeds:
            item = QTreeWidgetItem(self.my_channel_rss_feeds_list)
            item.setText(0, feed["url"])

            self.my_channel_rss_feeds_list.addTopLevelItem(item)
Exemple #17
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)
Exemple #18
0
 def add_items_to_tree(self, tree, items, keys):
     tree.clear()
     for item in items:
         widget_item = QTreeWidgetItem(tree)
         for index, key in enumerate(keys):
             value = format_size(item[key]) if key in ["bytes_up", "bytes_down"] else str(item[key])
             widget_item.setText(index, value)
         tree.addTopLevelItem(widget_item)
 def _load_shortcuts(self):
     for action in resources.CUSTOM_SHORTCUTS:
         shortcut_action = resources.get_shortcut(action)
         #populate the tree widget
         tree_data = [self.shortcuts_text[action],
             shortcut_action.toString(QKeySequence.NativeText), action]
         item = QTreeWidgetItem(self.result_widget, tree_data)
         item.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEnabled)
 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))
Exemple #21
0
    def initialize_with_torrents(self, torrents):
        self.my_channel_torrents_list.clear()
        for torrent in torrents:
            item = QTreeWidgetItem(self.my_channel_torrents_list)
            item.setText(0, torrent["name"])
            item.setText(1, str(torrent["added"]))

            self.my_channel_torrents_list.addTopLevelItem(item)
Exemple #22
0
 def add_widget(self, button, widget):
     """creates a QWidgetItem containing the widget,
     as child of the button-QWidgetItem
     """
     section = QTreeWidgetItem(button)
     section.setDisabled(True)
     self.tree.setItemWidget(section, 0, widget)
     return section
 def setData(self, column, role, value):
     state = self.checkState(column)
     QTreeWidgetItem.setData(self, column, role, value)
     if (role == Qt.CheckStateRole and
         state != self.checkState(column)):
         treewidget = self.treeWidget()
         if treewidget is not None:
             treewidget.itemChecked.emit(self, column)
Exemple #24
0
 def __init__(self, parent, items):
     QTreeWidget.__init__( self )
     self.setColumnCount( 2 )
     header = QTreeWidgetItem( SubtleTreeWidget.ITEM_ROLE )
     header.setText(0, 'File')
     header.setText(1, 'Status')
     self.setHeaderItem( header )
     self.addTopLevelItems( items )
Exemple #25
0
    def initialize_with_rss_feeds(self, rss_feeds):
        if not rss_feeds:
            return
        self.window().edit_channel_rss_feeds_list.clear()
        for feed in rss_feeds["rssfeeds"]:
            item = QTreeWidgetItem(self.window().edit_channel_rss_feeds_list)
            item.setText(0, feed["url"])

            self.window().edit_channel_rss_feeds_list.addTopLevelItem(item)
Exemple #26
0
 def __createSummaryItem(self, col0, col1):
     """
     Private slot to create a new item in the summary list.
     
     @param col0 string for column 0 (string)
     @param col1 string for column 1 (string)
     """
     itm = QTreeWidgetItem(self.summaryList, [col0, col1])
     itm.setTextAlignment(1, Qt.Alignment(Qt.AlignRight))
Exemple #27
0
 def examineChildElements(self, parentElement, parentItem):
     # Traverse the document.
     element = parentElement.firstChild()
     while not element.isNull():
         item = QTreeWidgetItem()
         item.setText(0, element.tagName())
         parentItem.addChild(item)
         self.examineChildElements(element, item)
         element = element.nextSibling()
 def __init__(self, item, overlayPathName):
     """
     item:            OverlayTreeWidgetItem
     overlayPathName: string
                      full name of the overlay, for example 'File Overlays/My Data'
     """
     self.overlayPathName = overlayPathName
     QTreeWidgetItem.__init__(self, [item.name])
     self.item = item
Exemple #29
0
 def __createSummaryItem(self, label, contents):
     """
     Private method to create an entry in the summary list.
     
     @param label text of the first column (string)
     @param contents text of the second column (string)
     """
     itm = QTreeWidgetItem(self.summaryList, [label, contents])
     itm.setTextAlignment(1, Qt.AlignRight)
 def __init__(self, parent=None):
     super(CategoryInfoDialog, self).__init__(parent)
     
     self.ui = Ui_CategoryInfo()
     self.ui.setupUi(self)
     self.resize(800, 600)
     
     root = QTreeWidgetItem(self.ui.treeWidget, ['All Categories', '-1', 'Root', 'false'])
     root.setChildIndicatorPolicy(QTreeWidgetItem.ShowIndicator)
Exemple #31
0
    def changeInterface(self, contents):
        from PyQt5.QtWidgets import QTreeWidget, QTreeWidgetItem

        self.layout.removeWidget(self.diskRawChkBox)
        self.diskRawChkBox.hide()
        self.layout.removeWidget(self.diskRawGroupBox)
        self.diskRawGroupBox.hide()
        self.layout.removeItem(self.spacerItem2)
        self.layout.removeWidget(self.ntfsLogFileChkBox)
        self.ntfsLogFileChkBox.hide()
        self.layout.removeWidget(self.ntfsLogGroupBox)
        self.ntfsLogGroupBox.hide()
        self.layout.removeItem(self.spacerItem3)
        self.layout.removeWidget(self.submitBtn)

        self.diskNameLabel = QLabel("Image Name:\t" + contents[0][0], self)
        self.diskSizeLabel = QLabel(
            "Image Size:\t{} Bytes".format(contents[0][1]), self)
        self.diskSizeLabel.setFixedHeight(20)
        self.diskSizeLabel.setAlignment(Qt.AlignVCenter)
        self.diskPartLabel = QLabel("Partition:", self)
        self.diskPartLabel.setFixedHeight(20)
        self.diskPartLabel.setAlignment(Qt.AlignBottom)

        self.partitionTree = QTreeWidget(self)
        self.partitionTree.setHeaderLabels([
            "Order", "File System", "Active", "Starting Offset",
            "Total Sector", "Size"
        ])
        self.partitionTree.itemChanged.connect(self.itemChanged)
        self.partitionTree.resizeColumnToContents(2)
        self.partitionTree.resizeColumnToContents(3)
        self.partitionTree.resizeColumnToContents(4)
        self.partitionTree.headerItem().setTextAlignment(0, Qt.AlignCenter)
        self.partitionTree.headerItem().setTextAlignment(1, Qt.AlignCenter)

        self.partitionItems = []
        for row in range(1, 5):
            self.partitionTree.headerItem().setTextAlignment(
                row + 1, Qt.AlignCenter)
            item = QTreeWidgetItem(self.partitionTree)
            item.setText(0, str(row))
            item.setTextAlignment(0, Qt.AlignLeft)
            if not contents[row]:
                item.setText(1, "None")
                item.setCheckState(0, Qt.Unchecked)
                item.setDisabled(True)
                continue
            for col in range(5):
                item.setText(col + 1, contents[row][col])
                item.setTextAlignment(col + 1, Qt.AlignCenter)
            item.setTextAlignment(1, Qt.AlignLeft)
            item.setCheckState(0, Qt.Unchecked)
            self.partitionItems.append(item)

        self.layout.addWidget(self.diskNameLabel)
        self.layout.addWidget(self.diskSizeLabel)
        self.layout.addWidget(self.diskPartLabel)
        self.layout.addWidget(self.partitionTree)
        self.layout.addItem(QSpacerItem(10, 10))
        self.layout.addWidget(self.submitBtn, alignment=Qt.AlignCenter)
 def get_images(self):
     self.treeWidget_imagenamelist.clear()
     condition = {'prodid': self.autoid, 'flag': self.img_status}
     res = self.PC.get_data(2, False, **condition)
     if not len(res):
         return
     self.images_list = res
     for item in res:
         qtreeitem = QTreeWidgetItem(self.treeWidget_imagenamelist)
         qtreeitem.setText(0, str(item.autoid))
         qtreeitem.setText(1, str(item.imgid_id))
         qtreeitem.setText(2, item.imagename)
         qtreeitem.setText(3, item.modifierid + item.modifiername)
         qtreeitem.setText(4, str(item.modifydate))
 def get_stuffrep_gt_zero(self, stuffkind_list):
     self.treeWidget_stuffrepository.clear()
     row_tuple = ('autoid', 'stuffkind', 'stuffid', 'stuffname', 'spec',
                  'package', 'batchno', 'mbatchno', 'amount', 'producer',
                  'supid', 'supname', 'content', 'cunit', 'water',
                  'rdensity', 'impurity', 'basicunit', 'lrid', 'stufftype')
     res = self.WC.get_stuffrepository(False,
                                       *row_tuple,
                                       stuffkind__in=stuffkind_list,
                                       amount__gt=0)
     self.stuff_repository = res
     if len(res):
         for item in res:
             qtreeitem = QTreeWidgetItem(self.treeWidget_stuffrepository)
             qtreeitem.setText(0, str(item['autoid']))
             qtreeitem.setText(1, str(item['stuffkind']))
             qtreeitem.setText(2, item['stuffid'] + ' ' + item['stuffname'])
             qtreeitem.setText(3, item['spec'])
             qtreeitem.setText(4, item['package'])
             qtreeitem.setText(5, item['batchno'])
             qtreeitem.setText(6, item['mbatchno'])
             qtreeitem.setText(7, str(item['amount']) + item['basicunit'])
             qtreeitem.setText(9, item['supid'] + ' ' + item['supname'])
             qtreeitem.setText(10, item['producer'])
             qtreeitem.setText(11, str(item['content']) + item['cunit'])
             qtreeitem.setText(12, str(item['water']) + '%')
             qtreeitem.setText(13, str(item['rdensity']))
             qtreeitem.setText(14, str(item['impurity']))
         self.treeWidget_stuffrepository.hideColumns(0, 1, 15)
         column_list = [i for i in range(2, 15)]
         self.treeWidget_stuffrepository.resizeColumns(120, *column_list)
Exemple #34
0
 def buildTree(self):
     self.ContentTree.clear()
     self.doubleclicked = False
     self.lastColumn = 0
     for title in self.packetDict.keys():
         tree_item = QTreeWidgetItem(self.ContentTree)
         tree_item.setText(0, title)
         tree_item.setExpanded(True)
         detail_dic = self.packetDict[title]
         for i in detail_dic.keys():
             #print(i,detail_dic[i])
             leaf = QTreeWidgetItem(tree_item, [i, str(detail_dic[i])])
             tree_item.addChild(leaf)
             leaf.setToolTip(1, str(detail_dic[i]))
             self.lastItem = tree_item
         self.ContentTree.addTopLevelItem(tree_item)
    def get_formula(self):
        if self.detail['pltype'] == 0:
            table = ['Productdictionary']
            condition = [
                'Productdictionary.autoid=Productprescription.prodid',
                'Productdictionary.prodid=' + self.detail['prodid']
            ]
        else:
            table = ['Stuffdictionary']
            condition = [
                'Stuffdictionary.autoid=Productprescription.prodid',
                'Stuffdictionary.stuffid=' + self.detail['prodid']
            ]
        # 获得配方
        if self.kind == 0:
            res = self.PLC.get_formula(version=self.detail['version'],
                                       stufftype__in=(0, 1, 2),
                                       prodtype=self.detail['pltype']).extra(
                                           tables=table, where=condition)
        else:
            res = self.PLC.get_formula(version=self.detail['version'],
                                       stufftype=self.kind + 2,
                                       prodtype=self.detail['pltype']).extra(
                                           tables=table, where=condition)
        stuffkind_list = []
        if len(res):
            # 显示配方
            for item in res:
                qtreeitem = QTreeWidgetItem(self.treeWidget_formula)
                qtreeitem.setText(1, STUFFTYPE[item.stufftype])
                qtreeitem.setText(2, item.stuffkind)
                qtreeitem.setText(3, item.formula)
                qtreeitem.setText(4, item.presexpression)
                qtreeitem.setText(5, item.pracexpression)
                qtreeitem.setText(6, item.drawexpression)
                # 领料精度
                qtreeitem.setText(7, str(item.precision))
                # 损耗限度
                qtreeitem.setText(8, str(item.loss))
                # 标记该物料是否已经发够料
                qtreeitem.setText(9, '0')
                stuffkind_list.append(item.stuffkind)

            self.treeWidget_formula.hideColumns(0, 4, 5, 6, 7, 8, 9)
            self.treeWidget_formula.resizeColumns(300, 1, 2, 3)
        # 如果当前配方不为空,则获取对应的库存
        if len(stuffkind_list):
            self.get_stuffrep_gt_zero(stuffkind_list)
class Waterfall(QWidget, waterfall.Ui_Waterfall):
    
    plot_settings_signal = QtCore.pyqtSignal(list) #send list of plotting params
    updated_rectangles_signal = QtCore.pyqtSignal(list) #send list of updated artists for redrawing

    def __init__(self, parent):
        super(Waterfall,self).__init__(parent)
        self.setupUi(self)
        
        self.get_settings()
        self.send_settings()

        #Button functions
        self.btn_apply_general_settings.clicked.connect(self.send_settings)
        self.btn_apply_keys_and_colors_settings.clicked.connect(self.send_settings)
        self.patient_tree = self.create_patient_tree()
        self.data_viewer_container.addWidget(self.patient_tree)
        self.btn_color_test.clicked.connect(self.get_color)
        

    def get_color(self):
        self.color = QColorDialog.getColor() #returns a color object
        print(color)

    def get_settings(self):
        try:
            with shelve.open('WaterfallSettings') as shelfFile: 
                self.keys_and_colors = shelfFile['keys_and_colors']
                shelfFile.close()
        except:
            #set and use default settings
            self.keys_and_colors = {
                                    'CR':'#03945D',
                                    'PR':'#B1EE97',
                                    'PD':'#FF6F69',
                                    'SD':'#707070'}
            with shelve.open('WaterfallSettings') as shelfFile:
                shelfFile['keys_and_colors'] = self.keys_and_colors
                shelfFile.close()
        
    def on_waterfall_data_signal(self,signal):
        self.waterfall_data = signal['waterfall_data'] #pandas dataframe
        
    def on_generated_rectangles_signal(self,signal):
        self.rectangles_received = signal[0]
        self.add_items() #display in table
        self.btn_apply_general_settings.setEnabled(True)
        self.btn_finalize_plot.setEnabled(True)
        self.btn_apply_keys_and_colors_settings.setEnabled(True)

    def send_settings(self):
        '''
        Emit both general plot settings, and color labeling settings. These are the settings to be used when the plot is created.
        '''
        self.general_settings = [
                                        self.plot_title.text(),
                                        self.x_label.text(),
                                        self.y_label.text(),
                                        [self.twenty_percent_line.isChecked(),
                                        self.thirty_percent_line.isChecked(),
                                        self.zero_percent_line.isChecked()],
                                        [self.display_responses_as_text.isChecked(),
                                        self.display_responses_as_color.isChecked(),
                                        self.display_no_responses.isChecked()],
                                        self.include_table.isChecked(),
                                        self.show_cancer_type.isChecked()
                                    ]
        self.plot_settings_signal.emit(self.general_settings)

    def create_patient_tree(self):
            '''
            Create QTreeWidget populated with a patient's data for the DataEntry dialog.
            Assumes that self.temp_patient is the patient of interest and that the variable belongs to the dialog.
            '''
            self.tree = QTreeWidget()
            self.root = self.tree.invisibleRootItem()
            self.headers = [
                            'Patient #',
                            'Best response %',
                            'Response',
                            'Cancer',
                            'Color key',
                            ]
            self.headers_item = QTreeWidgetItem(self.headers)
            self.tree.setColumnCount(len(self.headers))
            self.tree.setHeaderItem(self.headers_item)
            self.root.setExpanded(True)
            self.tree.header().setSectionResizeMode(QHeaderView.ResizeToContents)
            self.tree.header().setStretchLastSection(False)
            return self.tree

    def add_items(self):
        '''
        Populate viewing tree
        '''
        self.tree.clear() #clear prior to entering items, prevent aggregation
        i=0
        for rect in self.rectangles_received:
            #populate editable tree with rect data
            self.rect_item = QTreeWidgetItem(self.root)
            self.rect_params = [
                                self.waterfall_data['Patient number'][i], 
                                rect.get_height(),
                                self.waterfall_data['Overall response'][i],
                                self.waterfall_data['Cancer'][i]
                                ]
            for col in range(0,4):
                self.rect_item.setText(col,str(self.rect_params[col]))
                self.rect_item.setTextAlignment(col,4)
            self.tree.setItemWidget(self.rect_item, 4, CustomCombo(self,self.keys_and_colors,self.waterfall_data['Overall response'][i]))
            self.rect_item.setFlags(self.rect_item.flags() | QtCore.Qt.ItemIsEditable)
            i+=1
        if ~self.display_no_responses and ~self.dis
        for child_item in self.tree.children():
        
    def on_updated_tree_item(self):
        #update the rectangle which was edited
        pass

class WaterfallPlotter(QWidget):

    generated_rectangles_signal = QtCore.pyqtSignal(list) #send list of rects for data display in tree

    def __init__(self,parent):
        super(WaterfallPlotter,self).__init__(parent)

        self.get_settings()
        self.settings_update = False

        self.figure = plt.figure()
        self.canvas = FigureCanvas(self.figure)

        self.toolbar = NavigationToolbar(self.canvas,self)

        self.btn_plot = QPushButton('Default Plot')
        self.btn_plot.clicked.connect(self.default_plot)

        self.layout = QVBoxLayout()
        self.layout.addWidget(self.toolbar)
        self.layout.addWidget(self.canvas)
        self.layout.addWidget(self.btn_plot)
        self.setLayout(self.layout)
        
    
    def on_waterfall_data_signal(self,signal):
        self.waterfall_data = signal['waterfall_data'] #pandas dataframe
        self.btn_plot.setEnabled(True)

    def get_settings(self):
        try:
            with shelve.open('WaterfallSettings') as shelfFile: 
                self.keys_and_colors = shelfFile['keys_and_colors']
                shelfFile.close()
        except:
            #set and use default settings
            self.keys_and_colors = {
                                    'CR':'#03945D',
                                    'PR':'#B1EE97',
                                    'PD':'#FF6F69',
                                    'SD':'#707070'}
            with shelve.open('WaterfallSettings') as shelfFile:
                shelfFile['keys_and_colors'] = self.keys_and_colors
                shelfFile.close()

    def on_general_settings_signal(self,signal):
        self.gen_settings = signal
        self.settings_update = True
        self.default_plot()
    
    def get_bar_colors(self,responses):
        return [self.keys_and_colors[x] for x in responses]

    def default_plot(self):
        '''
        Plot waterfall data
        '''            
        self.figure.clear()
        self.rect_locations = np.arange(len(self.waterfall_data['Best response percent change']))
        self.ax = self.figure.add_subplot(111)
        self.bar_colors = self.get_bar_colors(self.waterfall_data['Overall response'])

        if self.settings_update == False:
            self.ax.tick_params(
                            axis='x',          # changes apply to the x-axis
                            which='both',      # both major and minor ticks are affected
                            bottom='on',      # ticks along the bottom edge are off
                            top='on',         # ticks along the top edge are off
                            labelbottom='on'
                            ) # labels along the bottom edge are off
            self.ax.axhline(y=20, linestyle='--', c='k', alpha=0.5, lw=2.0, label='twenty_percent')
            self.ax.axhline(y=-30, linestyle='--', c='k', alpha=0.5, lw=2.0, label='thirty_percent')
            self.ax.axhline(y=0, c='k', alpha=1, lw=2.0, label='zero_percent')
            self.ax.grid(color = 'k', axis = 'y', alpha=0.25)
            self.rects = self.ax.bar(self.rect_locations, self.waterfall_data['Best response percent change'], color=self.bar_colors)

        else:
            #settings were updated, we received them and stored in variable self.gen_settings
            self.ax.set_title(self.gen_settings[0])
            self.ax.set_xlabel(self.gen_settings[1])
            self.ax.set_ylabel(self.gen_settings[2])
            if self.gen_settings[3][0]:
                self.ax.axhline(y=20, linestyle='--', c='k', alpha=0.5, lw=2.0, label='twenty_percent')
            if self.gen_settings[3][1]:
                self.ax.axhline(y=-30, linestyle='--', c='k', alpha=0.5, lw=2.0, label='thirty_percent')
            if self.gen_settings[3][2]:
                self.ax.axhline(y=0, c='k', alpha=1, lw=2.0, label='zero_percent')

            if self.gen_settings[4][0] and ~self.gen_settings[6]:
                #show responses as labels, default color bars
                #legend depends on user specified keys
                self.rects = self.ax.bar(self.rect_locations, self.waterfall_data['Best response percent change'])
                self.add_labels(self.ax, self.rects, self.waterfall_data, 1)
            elif self.gen_settings[4][1]:
                #color bars with response type
                self.rects = self.ax.bar(self.rect_locations, self.waterfall_data['Best response percent change'], color=self.bar_colors)
                self.patches = []
                for key in self.keys_and_colors.keys():
                    self.patches.append(mpatches.Patch(color = self.keys_and_colors[key],label=key))
                self.ax.legend(handles=self.patches)
            else:
                self.rects = self.ax.bar(self.rect_locations, self.waterfall_data['Best response percent change'])
            
            if self.gen_settings[5]:
                self.plot_table()
            
            if self.gen_settings[6] and ~self.gen_settings[4][0]:
                self.add_labels(self.ax, self.rects, self.waterfall_data, 0)

        self.ax.grid(color = 'k', axis = 'y', alpha=0.25)
        self.canvas.draw()
        self.generated_rectangles_signal.emit([self.rects])
            
    def plot_table(self):
        rows = ['%s' % x for x in self.waterfall_data.keys()]
        rows = rows[4:] #skip first three, they are the 4 standard headers, rest are table rows
        columns = self.waterfall_data['Patient number'] #patient numbers
        cell_text = []
        for row in rows:
            cell_text_temp = []
            for col in range(len(columns)):
                cell_text_temp.append(self.waterfall_data[row][col])
            cell_text.append(cell_text_temp)
        the_table = self.ax.table(cellText=cell_text, rowLabels=rows, colLabels=columns, loc='bottom', cellLoc='center', colLoc='center')
        plt.subplots_adjust(bottom=0.15,left=0.5)
        self.ax.set_xlim(-0.5,len(columns)-0.5)
        self.ax.tick_params(
                        axis='x',          # changes apply to the x-axis
                        which='both',      # both major and minor ticks are affected
                        bottom='off',      # ticks along the bottom edge are off
                        top='off',         # ticks along the top edge are off
                        labelbottom='off'
                        ) # labels along the bottom edge are off
    
    def update_plot(self):
        '''
        TODO
        '''
        pass
                    
    def add_labels(self, ax, rects, waterfall_data, label_type):
        '''
        Add labels above/below bars. label_type == 1 --> display responses; == 0 --> display cancer type
        '''
        i = 0
        if label_type:
            for rect in rects:
                height = rect.get_height()
                if height >= 0:
                    valign = 'bottom'
                else:
                    valign = 'top'
                    
                ax.text(rect.get_x() + rect.get_width()/2., height,
                        '%s' % waterfall_data['Overall response'][i], ha='center', va=valign)
                i+=1
        else:
            for rect in rects:
                height = rect.get_height()
                if height >= 0:
                    valign = 'top'
                    hgt = -1
                else:
                    valign = 'bottom'
                    hgt = 1

                ax.text(rect.get_x() + rect.get_width()/2., hgt,
                        '%s' % waterfall_data['Cancer'][i], ha='center', va=valign, rotation='vertical')
                i+=1   
 def get_checkitem(self, itemtype, tree):
     tree.clear()
     condition = {'stuffid': self.autoid, 'itemtype': itemtype}
     res = self.LC.get_data(4, False, *VALUES_TUPLE_CI, **condition). \
         order_by('seqid')
     if not len(res):
         return
     for item in res:
         qtreeitem = QTreeWidgetItem(tree)
         qtreeitem.setText(0, str(item['autoid']))
         qtreeitem.setText(1, str(item['seqid']))
         qtreeitem.setText(2, item['kind'])
         qtreeitem.setText(3, item['itemname'])
         qtreeitem.setText(4, item['referencevalue'])
         qtreeitem.setText(5, RESTYPE[item['restype']])
         qtreeitem.setText(6, PUTINTYPE[item['putintype']])
     for i in range(1, 7):
         tree.resizeColumnToContents(i)
Exemple #38
0
    def on_core_threads(self, data):
        if not data:
            return
        self.window().threads_tree_widget.clear()
        for thread_info in data["threads"]:
            thread_item = QTreeWidgetItem(self.window().threads_tree_widget)
            thread_item.setText(0, "%d" % thread_info["thread_id"])
            thread_item.setText(1, thread_info["thread_name"])
            self.window().threads_tree_widget.addTopLevelItem(thread_item)

            for frame in thread_info["frames"]:
                frame_item = QTreeWidgetItem()
                frame_item.setText(2, frame)
                thread_item.addChild(frame_item)
    def add_payment_to_list(self, payment):
        if self.wallets:
            payment["transferred"]["amount"] = prec_div(
                payment["transferred"]["amount"],
                self.wallets[payment["transferred"]["type"]]["precision"])

            payment_time = datetime.datetime.fromtimestamp(
                int(payment["timestamp"])).strftime('%Y-%m-%d %H:%M:%S')
            item = QTreeWidgetItem(self.window().market_payments_list)
            item.setText(
                0, "%g %s" % (payment['transferred']["amount"],
                              payment['transferred']["type"]))
            item.setText(1, payment['address_from'])
            item.setText(2, payment['address_to'])
            item.setText(3, payment_time)
            item.setText(4, "%s" % ('yes' if payment['success'] else 'no'))

            self.window().market_payments_list.addTopLevelItem(item)
    def update(self, network: Network):
        self.clear()
        self.addChild = self.addTopLevelItem
        chains = network.get_blockchains()
        n_chains = len(chains)
        for chain_id, interfaces in chains.items():
            b = blockchain.blockchains.get(chain_id)
            if b is None: continue
            name = b.get_name()
            if n_chains > 1:
                x = QTreeWidgetItem(
                    [name + '@%d' % b.get_max_forkpoint(),
                     '%d' % b.height()])
                x.setData(0, Qt.UserRole, 1)
                x.setData(1, Qt.UserRole, b.get_id())
            else:
                x = self
            for i in interfaces:
                star = ' *' if i == network.interface else ''
                item = QTreeWidgetItem([i.host + star, '%d' % i.tip])
                item.setData(0, Qt.UserRole, 0)
                item.setData(1, Qt.UserRole, i.server)
                x.addChild(item)
            if n_chains > 1:
                self.addTopLevelItem(x)
                x.setExpanded(True)

        h = self.header()
        h.setStretchLastSection(False)
        h.setSectionResizeMode(0, QHeaderView.Stretch)
        h.setSectionResizeMode(1, QHeaderView.ResizeToContents)

        super().update()
 def get_formula(self):
     if self.autoid is None:
         return
     self.treeWidget_formula.clear()
     condition = {'prodid': self.autoid, 'prodtype': 0}
     res = self.PC.get_data(6, False, *VALUES_TUPLE_FL, **condition)
     if not len(res):
         return
     for item in res:
         qtreeitem = QTreeWidgetItem(self.treeWidget_formula)
         qtreeitem.setText(0, str(item['autoid']))
         qtreeitem.setText(1, STUFFTYPE[item['stufftype']])
         qtreeitem.setText(2, item['stuffkind'])
         qtreeitem.setText(3, item['formula'])
         qtreeitem.setText(4, item['presexpression'])
         qtreeitem.setText(5, item['presunit'])
         qtreeitem.setText(6, item['pracexpression'])
         qtreeitem.setText(7, item['pracunit'])
         qtreeitem.setText(8, item['drawexpression'])
         qtreeitem.setText(9, item['drawunit'])
         qtreeitem.setText(10, str(item['precision']))
         qtreeitem.setText(11, str(item['loss']) + "%")
     for i in range(1, 12):
         self.treeWidget_formula.resizeColumnToContents(i)
Exemple #42
0
    def parameter_updater(self, item: QTreeWidgetItem, col=None, save=True):
        """Handles updating the options for a parameter."""
        if 'Custom' != self.tab1.profile_dropdown.currentText():
            self.tab1.profile_dropdown.addItem('Custom')
            self.tab1.profile_dropdown.setCurrentText('Custom')
            self.settings.user_options['current_profile'] = ''

        if item.data(0, LEVEL_SLOT) == 0:
            if item.data(0, DATA_SLOT) in self.settings.need_parameters:
                result = self.alert_message('Warning!', 'This parameter needs an option!', 'There are no options!\n'
                                                                                           'Would you make one?', True)
                if result == QMessageBox.Yes:
                    success = self.add_option(item)

                    if not success:
                        item.treeWidget().blockSignals(True)
                        item.setCheckState(0, Qt.Unchecked)
                        item.treeWidget().blockSignals(False)
                        item.treeWidget().check_dependency(item)
                else:
                    item.treeWidget().blockSignals(True)
                    item.setCheckState(0, Qt.Unchecked)
                    item.treeWidget().blockSignals(False)
                    item.treeWidget().check_dependency(item)

            if item.checkState(0) == Qt.Checked:
                self.settings[item.data(0, DATA_SLOT)]['state'] = True
                if item.data(0, DATA_SLOT) == 'Download location':
                    for i in range(item.childCount()):
                        self.parameter_updater(item.child(i), save=False)

            else:
                self.settings[item.data(0, DATA_SLOT)]['state'] = False
                if item.data(0, DATA_SLOT) == 'Download location':
                    self.tab2.download_lineedit.setText(path_shortener(self.local_dl_path))
                    self.tab2.download_lineedit.setToolTip(self.local_dl_path)

        elif item.data(0, LEVEL_SLOT) == 1:
            # Settings['Settings'][Name of setting]['active option']] = index of child
            self.settings[item.parent().data(0, DATA_SLOT)]['active option'] = item.data(0, INDEX_SLOT)
            if item.parent().data(0, DATA_SLOT) == 'Download location':
                if item.checkState(0) == Qt.Checked:
                    self.tab2.download_lineedit.setText(item.data(0, DISPLAY_NAME_SLOT))
                    self.tab2.download_lineedit.setToolTip(item.data(0, DATA_SLOT))

        if save:
            self.file_handler.save_settings(self.settings.settings_data)
Exemple #43
0
    def addItem(self,strings,category,parent=None,WhatsThis=''):
        if category not in self.settings:
            print("unknown categorie" +str(category))
            return False
        if parent is None:
            parent=self.invisibleRootItem()
            fl=self.settings[category][1] | Qt.ItemIsUserCheckable #Qt.ItemIsTristate
        else:
            fl=self.settings[category][1]| Qt.ItemIsUserCheckable



        item = QTreeWidgetItem(parent)

        item.setText(0, strings)
        item.setCheckState(0, Qt.Unchecked)
        item.setData(0,Qt.ToolTipRole,category)
        item.setExpanded(True)
        item.setFlags(item.flags()| fl)


        return item
class Waterfall(QWidget, waterfall.Ui_Waterfall):
    
    plot_settings_signal = QtCore.pyqtSignal(list) #send list of plotting params
    updated_rectangles_signal = QtCore.pyqtSignal(list) #send list of updated artists for redrawing

    def __init__(self, parent):
        super(Waterfall,self).__init__(parent)
        self.setupUi(self)
        
        self.get_settings()
        self.send_settings()

        #Button functions
        self.btn_apply_general_settings.clicked.connect(self.send_settings)
        self.btn_apply_keys_and_colors_settings.clicked.connect(self.send_settings)
        self.patient_tree = self.create_patient_tree()
        self.data_viewer_container.addWidget(self.patient_tree)
        self.btn_color_test.clicked.connect(self.get_color)
        

    def get_color(self):
        self.color = QColorDialog.getColor() #returns a color object
        print(color)

    def get_settings(self):
        try:
            with shelve.open('WaterfallSettings') as shelfFile: 
                self.keys_and_colors = shelfFile['keys_and_colors']
                shelfFile.close()
        except:
            #set and use default settings
            self.keys_and_colors = {
                                    'CR':'#03945D',
                                    'PR':'#B1EE97',
                                    'PD':'#FF6F69',
                                    'SD':'#707070'}
            with shelve.open('WaterfallSettings') as shelfFile:
                shelfFile['keys_and_colors'] = self.keys_and_colors
                shelfFile.close()
        
    def on_waterfall_data_signal(self,signal):
        self.waterfall_data = signal['waterfall_data'] #pandas dataframe
        
    def on_generated_rectangles_signal(self,signal):
        self.rectangles_received = signal[0]
        self.add_items() #display in table
        self.btn_apply_general_settings.setEnabled(True)
        self.btn_finalize_plot.setEnabled(True)
        self.btn_apply_keys_and_colors_settings.setEnabled(True)

    def send_settings(self):
        '''
        Emit both general plot settings, and color labeling settings. These are the settings to be used when the plot is created.
        '''
        self.general_settings = [
                                        self.plot_title.text(),
                                        self.x_label.text(),
                                        self.y_label.text(),
                                        [self.twenty_percent_line.isChecked(),
                                        self.thirty_percent_line.isChecked(),
                                        self.zero_percent_line.isChecked()],
                                        [self.display_responses_as_text.isChecked(),
                                        self.display_responses_as_color.isChecked(),
                                        self.display_no_responses.isChecked()],
                                        self.include_table.isChecked(),
                                        self.show_cancer_type.isChecked()
                                    ]
        self.plot_settings_signal.emit(self.general_settings)

    def create_patient_tree(self):
            '''
            Create QTreeWidget populated with a patient's data for the DataEntry dialog.
            Assumes that self.temp_patient is the patient of interest and that the variable belongs to the dialog.
            '''
            self.tree = QTreeWidget()
            self.root = self.tree.invisibleRootItem()
            self.headers = [
                            'Patient #',
                            'Best response %',
                            'Response',
                            'Cancer',
                            'Color key',
                            ]
            self.headers_item = QTreeWidgetItem(self.headers)
            self.tree.setColumnCount(len(self.headers))
            self.tree.setHeaderItem(self.headers_item)
            self.root.setExpanded(True)
            self.tree.header().setSectionResizeMode(QHeaderView.ResizeToContents)
            self.tree.header().setStretchLastSection(False)
            return self.tree

    def add_items(self):
        '''
        Populate viewing tree
        '''
        self.tree.clear() #clear prior to entering items, prevent aggregation
        i=0
        for rect in self.rectangles_received:
            #populate editable tree with rect data
            self.rect_item = QTreeWidgetItem(self.root)
            self.rect_params = [
                                self.waterfall_data['Patient number'][i], 
                                rect.get_height(),
                                self.waterfall_data['Overall response'][i],
                                self.waterfall_data['Cancer'][i]
                                ]
            for col in range(0,4):
                self.rect_item.setText(col,str(self.rect_params[col]))
                self.rect_item.setTextAlignment(col,4)
            self.tree.setItemWidget(self.rect_item, 4, CustomCombo(self,self.keys_and_colors,self.waterfall_data['Overall response'][i]))
            self.rect_item.setFlags(self.rect_item.flags() | QtCore.Qt.ItemIsEditable)
            i+=1
        
    def on_updated_tree_item(self):
        #update the rectangle which was edited
        pass
Exemple #45
0
class QueryTreeViewModel(QAbstractItemModel):
    """
    Model for rendering social tenure relationship nodes in a tree view.
    @link: https://github.com/qgis/QGIS/blob/b315fbce8d23cc348a486bdcb0305667bbe9d8fc/python/plugins/db_manager/db_model.py#L292
    """
    def __init__(self, parent=None):
        QAbstractItemModel.__init__(self, parent)
        self.rootItem = QTreeWidgetItem(parent)

        self.addTestData()  # only for tests purpose
        self.addTestData()

    def addTestData(self):
        #item2 = QTreeWidgetItem(self.rootItem)
        #item2 = QTreeWidgetItem(['hola'])
        item = QTreeWidgetItem()
        icon_name = 'domains'
        icon = QIcon(
            ":/Asistente-LADM_COL/resources/images/{}.png".format(icon_name))
        item.setText(0, 'Jejeje')
        item.setData(0, Qt.DecorationRole, icon)
        #item2.setData(1, Qt.UserRole, 1)
        item.setData(0, Qt.DisplayRole, "Porque")
        item.setData(1, Qt.DisplayRole, "Porque")
        item.setData(3, Qt.DisplayRole, "Porque")
        item.setData(0, Qt.ForegroundRole, QBrush(Qt.lightGray))
        font = QFont()
        font.setBold(True)
        item.setData(0, Qt.FontRole, font)

        self.rootItem.addChild(item)

    def columnCount(self, parent):
        return 1

    def rowCount(self, parent):
        parentItem = parent.internalPointer() if parent.isValid(
        ) else self.rootItem
        return parentItem.childCount()

    def index(self, row, column, parent):
        if not self.hasIndex(row, column, parent):
            return QModelIndex()

        parentItem = parent.internalPointer() if parent.isValid(
        ) else self.rootItem
        childItem = parentItem.child(row)
        if childItem:
            return self.createIndex(row, column, childItem)
        return QModelIndex()

    def parent(self, index):
        if not index.isValid():
            return QModelIndex()

        childItem = index.internalPointer()
        parentItem = childItem.parent()

        if parentItem == self.rootItem:
            return QModelIndex()

        return self.createIndex(parentItem.row(), 0, parentItem)

    def data(self, index, role):
        return None

    def updateResults(self, colnames, results):
        print('colnames:', colnames)
        for item in results:
            print('item:', item)
            for colname, index in colnames.items():
                if colname != PARCEL_RIGHT_FIELD:
                    print('-- colname:', colname, ', value:', item[index])

            for derecho in item[colnames[PARCEL_RIGHT_FIELD]]:
                print('------ derecho', derecho)
                for colname, value in derecho.items():
                    print('-------- colname:', colname, ', value:', value)
Exemple #46
0
    def add_option(self, item: QTreeWidgetItem):
        """
        Check if parameter has a possible option parameter, and lets the user add on if one exist.
        """
        if item.data(0, DATA_SLOT) == 'Download location':
            self.alert_message('Error!', 'Please use the browse button\nto select download location!', None)
            return

        if item.data(0, LEVEL_SLOT) == 2:
            self.alert_message('Error!', 'Custom option does not take a command!', None)
            return

        # TODO: Standardise setting an parameter to checked, and updating to expanded state.
        elif '{}' in self.settings[item.data(0, DATA_SLOT)]['command']:

            item.treeWidget().blockSignals(True)
            option = self.design_option_dialog(item.text(0), item.toolTip(0))

            if option:
                if option in self.settings[item.data(0, DATA_SLOT)]['options']:
                    self.alert_message('Error', 'That option already exists!', '')
                    item.treeWidget().blockSignals(False)
                    return True

                new_option = ParameterTree.make_option(option.strip(),
                                                       item,
                                                       True,
                                                       1,
                                                       None,
                                                       None,
                                                       0)

                move = item.takeChild(item.indexOfChild(new_option))
                item.insertChild(0, move)

                self.settings.add_parameter_option(item.data(0, DATA_SLOT), option)

                for i in range(len(self.settings[item.data(0, DATA_SLOT)]['options'])):
                    child = item.child(i)
                    child.setData(0, INDEX_SLOT, i)
                    if i == 0:
                        child.setCheckState(0, Qt.Checked)
                        child.setFlags(child.flags() ^ Qt.ItemIsUserCheckable)
                    else:
                        child.setCheckState(0, Qt.Unchecked)
                        child.setFlags(child.flags() | Qt.ItemIsUserCheckable)

                item.setCheckState(0, Qt.Checked)
                item.setExpanded(True)
                item.treeWidget().update_size()
                try:
                    self.settings.need_parameters.remove(item.data(0, DATA_SLOT))
                except ValueError:
                    pass

                self.file_handler.save_settings(self.settings.settings_data)

                item.treeWidget().blockSignals(False)
                return True
            else:
                item.treeWidget().blockSignals(False)
                return False
        else:
            self.alert_message('Error!', 'The specified option does not take arguments!', None)
            return False
Exemple #47
0
    def on_core_open_files(self, data):
        if not data:
            return
        core_item = QTreeWidgetItem(self.window().open_files_tree_widget)
        core_item.setText(0, "Core (%d)" % len(data["open_files"]))
        self.window().open_files_tree_widget.addTopLevelItem(core_item)

        for open_file in data["open_files"]:
            item = QTreeWidgetItem()
            item.setText(0, open_file["path"])
            item.setText(1, "%d" % open_file["fd"])
            core_item.addChild(item)
Exemple #48
0
 def buildTree(self):
     self.DetailView.clear()
     for title in self.packetDict.keys():
         tree_item = QTreeWidgetItem(self.DetailView)
         tree_item.setText(0, title)
         tree_item.setExpanded(True)
         detail_dic = self.packetDict[title]
         for i in detail_dic.keys():
             leaf = QTreeWidgetItem(tree_item, [i, str(detail_dic[i])])
             leaf.setToolTip(1, str(detail_dic[i]))
             tree_item.addChild(leaf)
         self.DetailView.addTopLevelItem(tree_item)
Exemple #49
0
    def load_open_files_tab(self):
        # Fill the open files (GUI) tree widget
        my_process = psutil.Process()
        self.window().open_files_tree_widget.clear()
        gui_item = QTreeWidgetItem(self.window().open_files_tree_widget)

        try:
            open_files = my_process.open_files()
            gui_item.setText(0, "GUI (%d)" % len(open_files))
            self.window().open_files_tree_widget.addTopLevelItem(gui_item)

            for open_file in open_files:
                item = QTreeWidgetItem()
                item.setText(0, open_file.path)
                item.setText(1, "%d" % open_file.fd)
                gui_item.addChild(item)
        except psutil.AccessDenied as exc:
            gui_item.setText(0, f"Unable to get open files for GUI ({exc})")

        TriblerNetworkRequest("debug/open_files", self.on_core_open_files)
Exemple #50
0
    def on_ipv8_community_detail_stats(self, data):
        if not data:
            return

        self.window().ipv8_communities_details_widget.setHidden(False)
        self.window().ipv8_communities_details_widget.clear()
        for overlay in data["statistics"]:
            self.window().ipv8_communities_details_widget.setColumnWidth(
                0, 250)

            for key, stats in overlay.items():
                header_item = QTreeWidgetItem(
                    self.window().ipv8_communities_details_widget)
                header_item.setFirstColumnSpanned(True)
                header_item.setBackground(0, QtGui.QColor('#CCCCCC'))
                header_item.setText(0, key)
                self.window().ipv8_communities_details_widget.addTopLevelItem(
                    header_item)

                for request_id, stat in stats.items():
                    stat_item = QTreeWidgetItem(
                        self.window().ipv8_communities_details_widget)
                    stat_item.setText(0, request_id)
                    stat_item.setText(
                        1, f"{stat['bytes_up'] / (1024.0 * 1024.0):.3f}")
                    stat_item.setText(
                        2, f"{stat['bytes_down'] / (1024.0 * 1024.0):.3f}")
                    stat_item.setText(3, f"{stat['num_up']}")
                    stat_item.setText(4, f"{stat['num_down']}")
                    self.window(
                    ).ipv8_communities_details_widget.addTopLevelItem(
                        stat_item)
Exemple #51
0
    def on_ipv8_community_stats(self, data):
        if not data:
            return

        for overlay in data["overlays"]:
            item = None
            item_exists = False

            # Check if this item is already rendered
            for ind in range(
                    self.window().communities_tree_widget.topLevelItemCount()):
                existing_item = self.window(
                ).communities_tree_widget.topLevelItem(ind)
                if existing_item.data(0, Qt.UserRole)["id"] == overlay["id"]:
                    item = existing_item
                    item_exists = True
                    break

            if not item:
                # Create a new one
                item = QTreeWidgetItem(self.window().communities_tree_widget)

            item.setData(0, Qt.UserRole, overlay)
            item.setText(0, overlay["overlay_name"])
            item.setText(1, overlay["id"][:10])
            item.setText(2, overlay["my_peer"][-12:])
            peer_count = len(overlay["peers"])
            item.setText(3, f"{peer_count}")
            item.setForeground(
                3, self._colored_peer_count(peer_count, overlay["max_peers"]))

            if "statistics" in overlay and overlay["statistics"]:
                statistics = overlay["statistics"]
                item.setText(
                    4, f"{statistics['bytes_up'] / (1024.0 * 1024.0):.3f}")
                item.setText(
                    5, f"{statistics['bytes_down'] / (1024.0 * 1024.0):.3f}")
                item.setText(6, f"{statistics['num_up']}")
                item.setText(7, f"{statistics['num_down']}")
                item.setText(8, f"{statistics['diff_time']:.3f}")
            else:
                item.setText(4, "N/A")
                item.setText(5, "N/A")
                item.setText(6, "N/A")
                item.setText(7, "N/A")
                item.setText(8, "N/A")

            if not item_exists:
                self.window().communities_tree_widget.addTopLevelItem(item)
            map(self.window().communities_tree_widget.resizeColumnToContents,
                range(10))

        # Reload the window with peers
        selected_items = self.window().communities_tree_widget.selectedItems()
        if len(selected_items) > 0:
            self.update_community_peers(selected_items[0])
    def treeWidget_drawstuff_add_item(self, items: dict):
        try:
            self.stuff_list_additem(items)
            for item in items:
                qtreeitem = QTreeWidgetItem(self.treeWidget_drawstuff)
                qtreeitem.setText(0, str(item['autoid']))
                qtreeitem.setText(1, str(item['stuffkind']))
                qtreeitem.setText(2, item['stuffid'] + ' ' + item['stuffname'])
                qtreeitem.setText(3, item['spec'])
                qtreeitem.setText(4, item['package'])

                qtreeitem.setText(5, str(item['oripresamount']))
                qtreeitem.setText(6, item['basicunit'])

                qtreeitem.setText(7, str(item['newpracamount']))
                qtreeitem.setText(8, item['basicunit'])

                qtreeitem.setText(9, str(item['drawamount']))
                qtreeitem.setText(10, item['basicunit'])

                qtreeitem.setText(11, item['batchno'])
                qtreeitem.setText(12, item['mbatchno'])

                qtreeitem.setText(13, str(item['content']) + item['cunit'])
                qtreeitem.setText(14, str(item['water']) + '%')
                qtreeitem.setText(15, str(item['rdensity']))
                qtreeitem.setText(16, str(item['impurity']))
                qtreeitem.setText(17, str(item['loss']))

                qtreeitem.setText(18, item['supid'] + ' ' + item['supname'])
                qtreeitem.setText(19, item['producer'])

                qtreeitem.setText(20, str(item['presamount']))
                qtreeitem.setText(21, str(item['pracamount']))
                qtreeitem.setText(22, str(item['precision']))

                self.treeWidget_drawstuff.hideColumns(0, 1, 20, 21, 22)
                columns_list = [i for i in range(2, 20)]
                self.treeWidget_drawstuff.resizeColumns(200, *columns_list)
        except KeyError:
            pass
Exemple #53
0
    def show(self, mls):
        analysis_map = {
            "Domain Transition Analysis": DomainTransitionAnalysisTab,
            "Information Flow Analysis": InfoFlowAnalysisTab
        }
        components_map = {
            "Booleans": BoolQueryTab,
            "Commons": CommonQueryTab,
            "Roles": RoleQueryTab,
            "Object Classes": ObjClassQueryTab,
            "Types": TypeQueryTab,
            "Type Attributes": TypeAttributeQueryTab,
            "Users": UserQueryTab
        }
        rule_map = {
            "Constraints": ConstraintQueryTab,
            "RBAC Rules": RBACRuleQueryTab,
            "TE Rules": TERuleQueryTab
        }
        labeling_map = {
            "Fs_use_* Statements": FSUseQueryTab,
            "Genfscon Statements": GenfsconQueryTab,
            "Initial SID Statements": InitialSIDQueryTab,
            "Netifcon Statements": NetifconQueryTab,
            "Nodecon Statements": NodeconQueryTab,
            "Portcon Statements": PortconQueryTab
        }
        general_choices = {"Summary": SummaryTab}
        other_choices = {"Bounds": BoundsQueryTab, "Defaults": DefaultQueryTab}
        analysis_choices = {
            "Components": components_map,
            "Rules": rule_map,
            "Analyses": analysis_map,
            "Labeling": labeling_map,
            "General": general_choices,
            "Other": other_choices
        }

        if mls:
            rule_map["MLS Rules"] = MLSRuleQueryTab
            components_map["Categories"] = CategoryQueryTab
            components_map["Sensitivities"] = SensitivityQueryTab

        # populate the item list:
        self.analysisTypes.clear()
        for groupname, group in analysis_choices.items():
            groupitem = QTreeWidgetItem(self.analysisTypes)
            groupitem.setText(0, groupname)
            groupitem._tab_class = None
            for entryname, cls in group.items():
                item = QTreeWidgetItem(groupitem)
                item.setText(0, entryname)
                item._tab_class = cls
                groupitem.addChild(item)

        self.analysisTypes.expandAll()
        self.analysisTypes.sortByColumn(0, Qt.AscendingOrder)
        super(ChooseAnalysis, self).show()
Exemple #54
0
 def treeWidgetItemOlustur(self, bolum, kullanim, boyut, format, islev,
                           bolumno):
     item = QTreeWidgetItem()
     item.setText(0, str(bolum))
     item.setText(1, str(kullanim))
     item.setText(2, str(boyut) + " GB ")
     item.setText(3, str(format))
     # item.setText(4, str(islev))
     item.setText(4, str(bolumno))
     return item
Exemple #55
0
 def create_and_add_widget_item(self, key, value, widget):
     item = QTreeWidgetItem(widget)
     item.setText(0, key)
     item.setText(1, f"{value}")
     widget.addTopLevelItem(item)
Exemple #56
0
 def _addOrphanedRoot(self):
     if self.orphRoot is None:
         newItem = QTreeWidgetItem([""] * 4)
         newItem.setText(self.C_NAME, "Orphaned Files")
         newItem.setText(self.C_COUNT, "")
         newItem.setText(self.C_FLAGS, "")
         newItem.setText(self.C_HANDLE, "")
         self.addTopLevelItem(newItem)
         self.orphRoot = newItem
         newItem.setExpanded(True)
         newItem.setIcon(self.C_NAME, self.theTheme.getIcon("orphan"))
     return
Exemple #57
0
    def on_channels_peers(self, data):
        widget = self.window().channels_peers_tree_widget
        widget.clear()
        if not data:
            return

        for c in data["channels_list"]:
            channel_item = QTreeWidgetItem()
            channel_item.setText(0, str(c["channel_name"]))
            channel_item.setText(1, str(c["channel_pk"]))
            channel_item.setText(2, str(c["channel_id"]))
            channel_item.setData(3, Qt.DisplayRole,
                                 len(c["peers"]))  #  Peers count
            for p in c["peers"]:
                peer_item = QTreeWidgetItem()
                peer_item.setText(1, str(p[0]))  # Peer mid
                peer_item.setData(4, Qt.DisplayRole, p[1])  # Peer age
                channel_item.addChild(peer_item)
            widget.addTopLevelItem(channel_item)
Exemple #58
0
    def _addTreeItem(self, nwItem):

        tHandle = nwItem.itemHandle
        pHandle = nwItem.parHandle
        newItem = QTreeWidgetItem([""] * 4)

        newItem.setText(self.C_NAME, "")
        newItem.setText(self.C_COUNT, "0")
        newItem.setText(self.C_FLAGS, "")
        newItem.setText(self.C_HANDLE, tHandle)

        # newItem.setForeground(self.C_COUNT,QColor(*self.theParent.theTheme.treeWCount))
        newItem.setTextAlignment(self.C_COUNT, Qt.AlignRight)
        newItem.setFont(self.C_FLAGS, self.fontFlags)

        self.theMap[tHandle] = newItem
        if pHandle is None:
            if nwItem.itemType == nwItemType.ROOT:
                self.addTopLevelItem(newItem)
                self.theParent.mainMenu.setAvailableRoot()
            elif nwItem.itemType == nwItemType.TRASH:
                self.addTopLevelItem(newItem)
            else:
                self._addOrphanedRoot()
                self.orphRoot.addChild(newItem)
        else:
            self.theMap[pHandle].addChild(newItem)
            self.propagateCount(tHandle, nwItem.wordCount)

        self.setTreeItemValues(tHandle)
        newItem.setExpanded(nwItem.isExpanded)

        if nwItem.itemType == nwItemType.ROOT:
            newItem.setIcon(self.C_NAME, self.theTheme.getIcon("root"))
        elif nwItem.itemType == nwItemType.FOLDER:
            newItem.setIcon(self.C_NAME, self.theTheme.getIcon("folder"))
        elif nwItem.itemType == nwItemType.FILE:
            newItem.setIcon(self.C_NAME, self.theTheme.getIcon("document"))
        elif nwItem.itemType == nwItemType.TRASH:
            newItem.setIcon(self.C_NAME, self.theTheme.getIcon("trash"))

        return newItem
 def attachDummy(self):
     """
     Public method to attach a dummy sub item to allow for lazy population.
     """
     QTreeWidgetItem(self, ["DUMMY"])
Exemple #60
0
class Waterfall(QWidget, waterfall.Ui_Waterfall):

    general_settings_signal = QtCore.pyqtSignal(
        list)  #send list of plotting params
    updated_rectangles_signal = QtCore.pyqtSignal(
        list)  #send list of updated artists for redrawing

    def __init__(self, parent):
        super(Waterfall, self).__init__(parent)
        self.setupUi(self)

        self.test = {'a': 'red', 'b': 'green', 'c': 'blue'}
        #Button functions
        self.btn_apply_general_settings.clicked.connect(self.send_settings)
        self.patient_tree = self.create_patient_tree()
        self.data_viewer_container.addWidget(self.patient_tree)

    def on_waterfall_data_signal(self, signal):
        self.waterfall_data = signal['waterfall_data']  #pandas dataframe

    def on_generated_rectangles_signal(self, signal):
        self.rectangles_received = signal[0]
        self.add_items()  #display in table
        #print(self.rectangles_received)

    def send_settings(self, signal):
        self.list_general_settings = [
            self.plot_title.text(),
            self.x_label.text(),
            self.y_label.text(),
            self.twenty_percent_line.isChecked(),
            self.thirty_percent_line.isChecked(),
            self.zero_percent_line.isChecked(),
            self.display_responses_as_text.isChecked()
        ]
        self.general_settings_signal.emit(self.list_general_settings)

    def create_patient_tree(self):
        '''
            Create QTreeWidget populated with a patient's data for the DataEntry dialog.
            Assumes that self.temp_patient is the patient of interest and that the variable belongs to the dialog.
            '''
        self.tree = QTreeWidget()
        self.root = self.tree.invisibleRootItem()
        self.headers = [
            'Patient #',
            'Best response %',
            'Overall response',
            'Cancer',
            'Color coding key',
        ]
        self.headers_item = QTreeWidgetItem(self.headers)
        self.tree.setColumnCount(len(self.headers))
        self.tree.setHeaderItem(self.headers_item)
        self.root.setExpanded(True)
        self.tree.header().setSectionResizeMode(QHeaderView.ResizeToContents)
        self.tree.header().setStretchLastSection(False)
        return self.tree

    def add_items(self):
        '''
        Populate viewing tree
        '''
        self.tree.clear()  #clear prior to entering items, prevent aggregation
        i = 0
        for rect in self.rectangles_received:
            #populate editable tree with rect data
            self.rect_item = QTreeWidgetItem(self.root)
            self.rect_params = [
                self.waterfall_data['Patient number'][i],
                rect.get_height(), self.waterfall_data['Overall response'][i],
                self.waterfall_data['Cancer'][i]
            ]
            for col in range(0, 4):
                self.rect_item.setText(col, str(self.rect_params[col]))
                self.rect_item.setTextAlignment(col, 4)
            self.tree.setItemWidget(self.rect_item, 4,
                                    CustomCombo(self, self.test))
            self.rect_item.setFlags(self.rect_item.flags()
                                    | QtCore.Qt.ItemIsEditable)
            i += 1

    def on_updated_tree_item(self):
        #update the rectangle which was edited
        pass