示例#1
0
        def create_table_item(column, itemname, invalid_value_count, log_size,
                              callable, *args):
            item = QStandardItem()
            item.setEditable(False)
            #format if there is invalid data entries
            if invalid_value_count == -1:
                item.setData(DEEP_RED, Qt.BackgroundRole)
                item.setToolTip(
                    "All of the values in the log are marked invalid, none of them are filtered."
                )
            elif invalid_value_count > 0:
                saturation = 10 + (170 * (invalid_value_count /
                                          (log_size + invalid_value_count)))
                item.setData(QColor.fromHsv(0, saturation, 255),
                             Qt.BackgroundRole)
                aux_verb = "is" if invalid_value_count == 1 else "are"
                item.setToolTip(
                    f"{invalid_value_count}/{log_size+invalid_value_count} of the values in the log"
                    f" {aux_verb} marked invalid, and {aux_verb} filtered.")
            try:
                item.setText(callable(*args))
            except Exception as exc:
                logger.warning("Error setting column {} for log {}: {}".format(
                    column, itemname, str(exc)))

            return item
示例#2
0
    def show_results(self):
        header_labels_set = False
        self.show_results_event.clear()
        t0 = time.monotonic()
        counter = 0

        while not self._new_entries.empty():
            counter += 1
            entry = self._new_entries.get()
            row = []
            try:
                row_data = self.apply_search_result_row(entry)
            except SkipRow:
                continue
            if not header_labels_set:
                # Set header labels just once.
                self.search_results_model.setHorizontalHeaderLabels(list(row_data))
                header_labels_set = True
            for value in row_data.values():
                item = QStandardItem()
                item.setData(value, Qt.DisplayRole)
                row.append(item)
            self.search_results_model.appendRow(row)
        if counter:
            duration = time.monotonic() - t0
            log.debug("Displayed %d new results (%.3f s).", counter, duration)
        self.show_results_event.set()
示例#3
0
文件: models.py 项目: nmearl/specviz
    def add_model(self, model):
        """
        Adds a model to the internal Qt model.

        Parameters
        ----------
        model : :class:`astropy.modeling.FittableModel`
            The model instance to add.

        Returns
        -------
        :class:`qtpy.QtCore.QModelIndex`
            The index in the Qt model where the new model been added.
        """
        model_name = model.name or model.__class__.name

        model_count = len([self.item(idx) for idx in range(self.rowCount())
                           if model_name in self.item(idx).text()])

        model_name = model_name + "_" + str(model_count) \
            if model_count > 0 else model_name

        model_item = QStandardItem(model_name)
        model_item.setData(model, Qt.UserRole + 1)

        for para_name in model.param_names:
            # Retrieve the parameter object from the model
            parameter = getattr(model, para_name)

            # Store the name value
            param_name = QStandardItem(parameter.name)
            param_name.setData(parameter.name, Qt.UserRole + 1)
            param_name.setEditable(False)

            # Store the data value of the parameter
            param_value = QStandardItem("{:.5g}".format(parameter.value))
            param_value.setData(parameter.value, Qt.UserRole + 1)

            # Store the unit information
            # param_unit = QStandardItem("{}".format(parameter.unit))
            param_unit = QStandardItem("Plot Units")
            param_unit.setData(parameter.unit, Qt.UserRole + 1)
            param_unit.setEditable(False)

            # Store the fixed state of the unit
            param_fixed = QStandardItem()
            param_fixed.setData(parameter.fixed, Qt.UserRole + 1)
            param_fixed.setCheckable(True)
            param_fixed.setEditable(False)

            model_item.appendRow([param_name, param_value, param_unit, param_fixed])

        self.appendRow([model_item, None, None, None])

        # Add this model to the model equation string. By default, all models
        # are simply added together
        self._equation += " + {}".format(model_name) \
            if len(self._equation) > 0 else "{}".format(model_name)

        return model_item.index()
示例#4
0
    def loadServos(self):
        model = QStandardItemModel()

        devs = il.devices(il.NET_PROT.EUSB)
        for dev in devs:
            try:
                net = il.Network(il.NET_PROT.EUSB, dev)
            except il.exceptions.ILCreationError:
                continue

            found = net.servos()
            for servo_id in found:
                try:
                    servo = il.Servo(net, servo_id)
                except il.exceptions.ILCreationError:
                    continue

                item = QStandardItem('0x{:02x} ({})'.format(servo_id, dev))
                item.setData(servo, Qt.UserRole)

                image = QImage(join(_RESOURCES, 'images', 'triton-core.png'))
                item.setData(QPixmap.fromImage(image), Qt.DecorationRole)

                model.appendRow([item])

        self.cboxServos.setModel(model)
示例#5
0
 def show_results(self):
     header_labels_set = False
     self.show_results_event.clear()
     t0 = time.monotonic()
     counter = 0
     for uid, entry in itertools.islice(self._results_catalog.items(), MAX_SEARCH_RESULTS):
         if uid in self._results:
             continue
         counter += 1
         self._results.append(uid)
         row = []
         try:
             row_data = self.apply_search_result_row(entry)
         except SkipRow:
             continue
         if not header_labels_set:
             # Set header labels just once.
             self.search_results_model.setHorizontalHeaderLabels(list(row_data))
             header_labels_set = True
         for value in row_data.values():
             item = QStandardItem()
             item.setData(value, Qt.DisplayRole)
             row.append(item)
         self.search_results_model.appendRow(row)
     if counter:
         duration = time.monotonic() - t0
         log.debug("Displayed %d new results (%.3f s).", counter, duration)
     self.show_results_event.set()
    def update_channels(self,
                        channels: List[Channel],
                        selected_channel: Channel = None):
        """
        Update / repopulate the list of selectable channels
        Inputs:
            channels: List of channel names
        """
        self._reset_combo_box(self._combo_channels)

        if channels is None or len(channels) == 0:
            self._combo_channels.setEnabled(False)
        else:
            model = QStandardItemModel()
            model.appendRow(QStandardItem(self._combo_channels.itemText(0)))

            for channel in channels:
                item = QStandardItem(channel.display_name)
                item.setData(channel, QtCore.Qt.UserRole)
                model.appendRow(item)

            self._combo_channels.setModel(model)

            if selected_channel is not None:
                # TODO relying on display name isn't the best as it will probably
                #      cause issues if channel names aren't unique
                # TODO refactor by making Channel derive from QStandardItem and do something like this:
                #      selected_index = model.indexFromItem(selected_channel)
                #      self.combo_channels.setCurrentIndex(selected_index)
                self._combo_channels.setCurrentText(
                    selected_channel.display_name)

            self._combo_channels.setEnabled(True)
示例#7
0
    def set_default(self, parameters):
        """Sets the default values from 'parameters' to the model

        Sets the data from 'parameters' to the model, overwriting any existing
        data in the model. This follows the ``mily.widget`` API.

        Parameters
        ----------
        parameters : [dicts]
            List of dicts with each dict being a row that maps the column
            header to its value.
        """
        model = self.model()
        # Empty the model.
        model.removeRows(0, model.rowCount())
        # Add the new data to the model.
        for row_params in parameters:
            row_data = []
            # for each column in the model check if a default is given
            for column in range(0, model.columnCount()):
                header_item = model.horizontalHeaderItem(column)
                header = header_item.text()
                item = QStandardItem()
                value = row_params.get(header, None)
                item.setData(value, Qt.DisplayRole)
                row_data.append(item)
            model.appendRow(row_data)
示例#8
0
    def __init__(self, parent):
        super(InfoFrame, self).__init__(parent)

        self.widget_layout = QVBoxLayout(self)
        self.setLayout(self.widget_layout)

        self.section_label = QLabel(self)
        self.section_label.setText("Informations")
        self.widget_layout.addWidget(self.section_label)

        self.label = QLabel(self)
        self.label.setText("Select information to collect after successfull connection. Keep in mind that the more "
                           "data you collect the more suspicious you are for antivirus software. You can "
                           "change these settings later.")
        self.label.setWordWrap(True)
        self.widget_layout.addWidget(self.label)

        self.list = QListView(self)
        self.model = QStandardItemModel(self.list)
        self.widget_layout.addWidget(self.list)
        self.list.setModel(self.model)

        self.item_string = {}
        infos = ConfigManager.get_infos()

        for info in infos:
            self.item_string[info] = {"name": " ".join(info.capitalize().split("_"))}

        for string in self.item_string:
            item = QStandardItem(self.item_string.get(string).get("name"))
            item.setFlags(Qt.ItemIsEnabled)
            item.setData(QVariant(Qt.Checked), Qt.CheckStateRole)
            self.model.appendRow(item)
示例#9
0
 def _update_stations(self):
     self.model_stations.clear()
     for mt_obj in list(self._mt_obj_dict.values()):
         new_item = QStandardItem()
         new_item.setData(mt_obj.station, QtCore.Qt.DisplayRole)
         new_item.setData(mt_obj.fn, QtCore.Qt.ToolTipRole)
         self.model_stations.appendRow(new_item)
     self.model_stations.sort(0)
示例#10
0
    def appendCatalog(self, catalog: BlueskyRun):
        # give catalog to out catalog viewer
        self.split_widget.catalog_view.setCatalog(catalog, 'primary', 'img')

        display_name = f"scan:{catalog.metadata['start']['scan_id']}"
        item = QStandardItem()
        item.setData(display_name, Qt.DisplayRole)
        item.setData(catalog, Qt.UserRole)
        self.model.appendRow(item)
        # tell our model that the data has been updated, the two parameters are rox index and column index
        self.model.dataChanged.emit(item.index(), item.index())
示例#11
0
 def load_kpis(self, rootIndex, topology):
     kpis = QStandardItem('kpis')
     item = self.itemFromIndex(rootIndex)
     item.appendRow(kpis)
     for conn_key, conn in topology.connections.items():
         conn_item = QStandardItem(conn_key)
         kpis.appendRow(conn_item)
         for kpi_key, kpi in conn.kpis.items():
             kpi_item = QStandardItem(kpi_key)
             kpi_item.setData('kpi', self.TYPE_ROLE)
             kpi_item.setData(kpi, self.MODEL_ROLE)
             conn_item.appendRow(kpi_item)
示例#12
0
    def add_client(self, client: Client):
        self._clients.append(client)
        if isinstance(client.backend, JSONBackend):
            client_item = QStandardItem(client.backend.path)

        elif isinstance(client.backend, MongoBackend):
            client_item = QStandardItem(
                f"{client.backend._client.HOST}/{client.backend._collection.full_name}"
            )
        self.appendRow(client_item)
        for result in client.search():
            # add an OphydItem
            self.add_device(client_item, result.item)
        client_item.setData(client)
示例#13
0
    def __init__(self, parent, info, title="Channel Properties"):
        super().__init__(parent)
        self.setWindowTitle(title)

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

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

        self.view = QTableView()
        self.view.setModel(self.proxymodel)
        self.view.setItemDelegateForColumn(2, ComboBoxDelegate(self.view))
        self.view.setEditTriggers(QAbstractItemView.AllEditTriggers)
        self.view.verticalHeader().setVisible(False)
        self.view.horizontalHeader().setStretchLastSection(True)
        self.view.setShowGrid(False)
        self.view.setSelectionMode(QAbstractItemView.NoSelection)
        self.view.setSortingEnabled(True)
        self.view.sortByColumn(0, Qt.AscendingOrder)

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

        self.resize(475, 650)
        self.view.setColumnWidth(0, 70)
        self.view.setColumnWidth(1, 155)
        self.view.setColumnWidth(2, 90)
示例#14
0
    def add_model(self, model):
        model_name = model.__class__.name

        model_count = len([
            self.item(idx) for idx in range(self.rowCount())
            if model.__class__.name in self.item(idx).text()
        ])

        model_name = model_name + str(
            model_count) if model_count > 0 else model_name

        model_item = QStandardItem(model_name)
        model_item.setData(model, Qt.UserRole + 1)

        for para_name in model.param_names:
            # Retrieve the parameter object from the model
            parameter = getattr(model, para_name)

            # Store the name value
            param_name = QStandardItem(parameter.name)
            param_name.setData(parameter.name, Qt.UserRole + 1)
            param_name.setEditable(False)

            # Store the data value of the parameter
            param_value = QStandardItem("{:.5g}".format(parameter.value))
            param_value.setData(parameter.value, Qt.UserRole + 1)

            # Store the unit information
            # param_unit = QStandardItem("{}".format(parameter.unit))
            param_unit = QStandardItem("Plot Units")
            param_unit.setData(parameter.unit, Qt.UserRole + 1)
            param_unit.setEditable(False)

            # Store the fixed state of the unit
            param_fixed = QStandardItem()
            param_fixed.setData(parameter.fixed, Qt.UserRole + 1)
            param_fixed.setCheckable(True)
            param_fixed.setEditable(False)

            model_item.appendRow(
                [param_name, param_value, param_unit, param_fixed])

        self.appendRow([model_item, None, None, None])

        # Add this model to the model equation string. By default, all models
        # are simply added together
        self._equation += " + {}".format(model_name) \
            if len(self._equation) > 0 else "{}".format(model_name)

        return model_item.index()
示例#15
0
def test_metadataview(qtbot, catalog):
    catalogmodel = QStandardItemModel()
    selectionmodel = QItemSelectionModel()
    selectionmodel.setModel(catalogmodel)

    item = QStandardItem()
    item.setData('test catalog', Qt.DisplayRole)
    item.setData(catalog, Qt.UserRole)
    catalogmodel.appendRow(item)
    catalogmodel.dataChanged.emit(item.index(), item.index())

    selectionmodel.setCurrentIndex(catalogmodel.indexFromItem(item), selectionmodel.SelectCurrent)

    w = MetadataView(catalogmodel, selectionmodel)
    w.show()
示例#16
0
    def _build_GUI(self, linelist, table_view):
        panel_layout = QVBoxLayout()
        panel_layout.setSizeConstraint(QLayout.SetMaximumSize)
        self.setLayout(panel_layout)

        # GUI cannot be completely defined in a .ui file.
        # It has to be built on-the-fly here.
        self.button_pane = QWidget()
        loadUi(
            os.path.join(os.path.dirname(__file__), "ui",
                         "linelists_panel_buttons.ui"), self.button_pane)
        self.button_pane.create_set_button.clicked.connect(self._createSet)
        self.button_pane.deselect_button.clicked.connect(
            table_view.clearSelection)

        # header with line list metadata.
        info = QTextBrowser()
        info.setMaximumHeight(100)
        info.setAutoFillBackground(True)
        info.setStyleSheet("background-color: rgb(230,230,230);")
        for comment in linelist.meta['comments']:
            info.append(comment)

        # populate color picker
        model = self.button_pane.combo_box_color.model()
        for cname in ID_COLORS:
            item = QStandardItem(cname)
            item.setForeground(ID_COLORS[cname])
            item.setData(QColor(ID_COLORS[cname]), role=Qt.UserRole)
            model.appendRow(item)

        # set validators
        validator = QDoubleValidator()
        validator.setRange(0.05, 0.95, decimals=2)
        self.button_pane.height_textbox.setValidator(validator)
        validator = QDoubleValidator()
        validator.setRange(-1.e5, 1.e10, decimals=4)
        self.button_pane.redshift_textbox.setValidator(validator)

        model = self.button_pane.combo_box_z_units.model()
        for uname in ['z', 'km/s']:
            item = QStandardItem(uname)
            model.appendRow(item)

        # put it all together
        panel_layout.addWidget(info)
        panel_layout.addWidget(table_view)
        panel_layout.addWidget(self.button_pane)
示例#17
0
    def show_results(self):
        header_labels_set = False
        self.show_results_event.clear()
        t0 = time.monotonic()
        counter = 0

        try:
            msg.showBusy()
            while not self._new_uids_queue.empty():
                counter += 1
                row = []
                new_uid = self._new_uids_queue.get()
                try:
                    entry = self.get_run_by_uid(new_uid)
                    row_data = self.apply_search_result_row(entry)
                except SkipRow as e:
                    msg.showMessage(str(msg))
                    msg.logError(e)
                    continue
                if not header_labels_set:
                    # Set header labels just once.
                    threads.invoke_in_main_thread(
                        self.search_results_model.setHorizontalHeaderLabels,
                        list(row_data))
                    header_labels_set = True
                for value in row_data.values():
                    item = QStandardItem()
                    item.setData(value, Qt.DisplayRole)
                    item.setData(new_uid, Qt.UserRole)
                    row.append(item)
                if QThread.currentThread().isInterruptionRequested():
                    self.show_results_event.set()
                    msg.logMessage("Interrupt requested")
                    return
                threads.invoke_in_main_thread(
                    self.search_results_model.appendRow, row)
            if counter:
                self.sig_update_header.emit()
                duration = time.monotonic() - t0
                msg.showMessage("Displayed {} new results {}.".format(
                    counter, duration))
            self.show_results_event.set()
        except Exception as e:
            msg.showMessage("Error displaying runs")
            msg.logError(e)
        finally:
            msg.hideBusy()
示例#18
0
    def _build_GUI(self, linelist, table_view):
        panel_layout = QGridLayout()
        panel_layout.setSizeConstraint(QLayout.SetMaximumSize)
        self.setLayout(panel_layout)

        # GUI cannot be completely defined in a .ui file.
        # It has to be built on-the-fly here.
        self.button_pane = QWidget()
        loadUi(os.path.join(os.path.dirname(__file__), "ui", "linelists_panel_buttons.ui"), self.button_pane)

        # internal signals do not use Hub infrastructure.
        self.button_pane.create_set_button.clicked.connect(self._create_set)
        self.button_pane.deselect_button.clicked.connect(table_view.clearSelection)

        # header with line list metadata.
        info = QTextBrowser()
        info.setMaximumHeight(100)
        info.setAutoFillBackground(True)
        info.setStyleSheet("background-color: rgb(230,230,230);")
        for comment in linelist.meta['comments']:
            info.append(comment)

        # populate color picker
        model = self.button_pane.combo_box_color.model()
        for cname in ID_COLORS:
            item = QStandardItem(cname)
            item.setForeground(ID_COLORS[cname])
            item.setData(QColor(ID_COLORS[cname]), role=Qt.UserRole)
            model.appendRow(item)

        # set validators
        validator = QDoubleValidator()
        validator.setRange(0.05, 0.95, decimals=2)
        self.button_pane.height_textbox.setValidator(validator)
        validator = QDoubleValidator()
        validator.setRange(-1.e5, 1.e10, decimals=4)
        self.button_pane.redshift_textbox.setValidator(validator)

        model = self.button_pane.combo_box_z_units.model()
        for uname in ['z', 'km/s']:
            item = QStandardItem(uname)
            model.appendRow(item)

        # put it all together
        panel_layout.addWidget(info,0,0)
        panel_layout.addWidget(table_view,1,0)
        panel_layout.addWidget(self.button_pane,2,0)
示例#19
0
    def _addRow(self):
        """Inserts an empty row after the (last) currently selected row(s)."""

        indices = self.tableView.selectionModel().selectedIndexes()
        rows = [index.row() for index in indices]
        rows.sort(reverse=True)
        empty_row = []
        for column in range(self.tableView.model().columnCount()):
            item = QStandardItem()
            item.setData(None, Qt.DisplayRole)
            empty_row.append(item)
        if rows:  # add an empty row after the last selected row
            self.tableView.model().insertRow(rows[0] + 1, empty_row)
        else:  # If no rows selected add row at end of table
            end_row = self.tableView.model().rowCount()
            self.tableView.model().insertRow(end_row, empty_row)
        self._check_table_after_row_manipulation()
示例#20
0
    def __init__(self, parent, rows, selected=None, disabled=None):
        super().__init__(parent)
        self.setWindowTitle("Select XDF Stream")

        self.model = QStandardItemModel()
        self.model.setHorizontalHeaderLabels(
            ["ID", "Name", "Type", "Channels", "Format", "Sampling Rate"])

        for index, stream in enumerate(rows):
            items = []
            for item in stream:
                tmp = QStandardItem()
                tmp.setData(item, Qt.DisplayRole)
                items.append(tmp)
            for item in items:
                item.setEditable(False)
                if disabled is not None and index in disabled:
                    item.setFlags(Qt.NoItemFlags)
            self.model.appendRow(items)

        self.view = QTableView()
        self.view.setModel(self.model)
        self.view.verticalHeader().setVisible(False)
        self.view.horizontalHeader().setStretchLastSection(True)
        self.view.setShowGrid(False)
        self.view.setSelectionMode(QAbstractItemView.SingleSelection)
        self.view.setSelectionBehavior(QAbstractItemView.SelectRows)
        if selected is not None:
            self.view.selectRow(selected)
        self.view.setSortingEnabled(True)
        self.view.sortByColumn(0, Qt.AscendingOrder)

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

        self.resize(775, 650)
        self.view.setColumnWidth(0, 100)
        self.view.setColumnWidth(1, 200)
        self.view.setColumnWidth(2, 120)
示例#21
0
    def loadServos(self):
        model = QStandardItemModel()

        net, servo = il.lucky(il.NET_PROT.ETH,
                              "../../resources/dictionaries/eve-net_1.7.1.xdf",
                              address_ip='192.168.2.22',
                              port_ip=1061,
                              protocol=2)

        if net is not None and servo is not None:
            item = QStandardItem('0x{:02x} ({})'.format(1, "Everest"))
            item.setData(servo, Qt.UserRole)

            image = QImage(join(_RESOURCES, 'images', 'eve-xcr.png'))
            item.setData(QPixmap.fromImage(image), Qt.DecorationRole)

            model.appendRow([item])

            self.cboxServos.setModel(model)
示例#22
0
    def _duplicateRow(self):
        """Duplicates the selected row(s) into the table after the row(s)."""

        # find the selected row(s)
        indices = self.tableView.selectionModel().selectedIndexes()
        rows = [index.row() for index in indices]
        rows.sort(reverse=True)

        if self._check_rows(rows):
            model = self.tableView.model()
            for row in rows:
                row_data = []
                for column in range(model.columnCount()):
                    value = model.item(row, column).data(Qt.DisplayRole)
                    item = QStandardItem()
                    item.setData(value, Qt.DisplayRole)
                    row_data.append(item)
                model.insertRow(row + 1, row_data)
        self._check_table_after_row_manipulation()
示例#23
0
    def load(self):
        self.clear()
        """Walk the tree starting from topology"""
        for el, val in presets.topology.items():
            item = QStandardItem(el)
            self.appendRow(item)
            nodes = QStandardItem('nodes')
            item.appendRow(nodes)
            # Walk the nodes
            for node_name, nvals in val['nodes'].items():
                n = QStandardItem(node_name)
                nodes.appendRow(n)
                for nval in nvals:
                    node_layout = QStandardItem('')
                    n.appendRow(node_layout)
                    p = nval.get('position')
                    if isinstance(p, dict):
                        p = 'dict..'
                    pos = QStandardItem(p)
                    pos.setData('position', self.TYPE_ROLE)
                    node_layout.appendRow([QStandardItem('position'), pos])

                    m = nval.get('motion')
                    if isinstance(m, dict):
                        m = 'dict..'
                    mot = QStandardItem(m)
                    mot.setData('motion', self.TYPE_ROLE)
                    node_layout.appendRow([QStandardItem('motion'), mot])

                    mdl = QStandardItem(nval.get('model'))
                    node_layout.appendRow([QStandardItem('model'), mdl])
            
            connections = QStandardItem('connections')
            item.appendRow(connections)
            # Walk the connections
            for conn in val['connections']:
                c = QStandardItem('')
                connections.appendRow(c)
                src = QStandardItem('Source:')
                src_val = QStandardItem(conn['source'])
                src_val.setData('combo', self.TYPE_ROLE)
                c.appendRow([src, src_val])

                snk = QStandardItem('Sink:')
                snk_val = QStandardItem(conn['sink'])
                snk_val.setData('combo', self.TYPE_ROLE)
                c.appendRow([snk, snk_val])

                mdl = QStandardItem('Model:')
                mdl_val = QStandardItem(conn['model'])
                c.appendRow([mdl, mdl_val])
示例#24
0
    def add_catalogs(self):
        config_file_to_broker = defaultdict(list)
        catalog_names = list(catalog)

        for name in catalog_names:
            broker = Broker.named(name)
            if getattr(broker, 'v2', None) is None:
                msg.logMessage(
                    f'The broker named {name} cannot be cast to a v2 Broker.',
                    msg.WARNING)
                continue
            # catalog_dir might be in the metadata; if not, let's try to find it
            if 'catalog_dir' in broker.v2.metadata:
                config_file = broker.v2.metadata["catalog_dir"]
            else:
                config_file = find_catalog(name)

            config_file_to_broker[config_file].append(broker)

        for config_file, brokers in config_file_to_broker.items():
            config_file_item = QStandardItem()
            config_file_item.setData(config_file, Qt.DisplayRole)
            self.appendRow(config_file_item)
            for broker in brokers:
                broker_item = QStandardItem()
                broker_item.setData(broker.name, Qt.DisplayRole)
                broker_item.setData(broker, self.broker_role)
                config_file_item.appendRow(broker_item)
示例#25
0
    def populatePortList(self, model, tv, ports):
        tv.setModel(model)
        root = model.invisibleRootItem()

        portsdict = {}
        for port in ports:
            if port.client not in portsdict:
                portsdict[port.client] = []
            portsdict[port.client].append(port)

        for client in humansorted(portsdict):
            clientitem = QStandardItem(client)

            for port in humansorted(portsdict[client],
                                    key=attrgetter("group", "order", "name")):
                portspec = (port.client, port.name)
                if port.pretty_name:
                    label = "%s (%s)" % (port.pretty_name, port.name)
                else:
                    label = port.name

                portitem = QStandardItem(label)
                portitem.setData(portspec)
                portitem.setCheckable(True)
                portitem.setUserTristate(False)
                # Check box toggling is done in the treeview clicked handler "on_port_clicked"
                portitem.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEnabled)

                portitem.setToolTip(self.makePortTooltip(port))

                if portspec in self.rec_sources:
                    portitem.setCheckState(2)

                clientitem.appendRow(portitem)

            root.appendRow(clientitem)

        tv.expandAll()
示例#26
0
 def addItem(self, text, data=None, toolTip=None):
     item = QStandardItem()
     item.setText(text)
     if data is None:
         item.setData(text)
     else:
         item.setData(data)
     if toolTip is not None:
         item.setToolTip(toolTip)
     item.setFlags(Qt.ItemIsEnabled | Qt.ItemIsUserCheckable)
     item.setData(Qt.Checked if text in self.checkItems else Qt.Unchecked, Qt.CheckStateRole)
     self.model().appendRow(item)
示例#27
0
    def add_catalogs(self):
        config_file_to_broker = defaultdict(list)
        catalog_names = list(catalog)

        for name in catalog_names:
            broker = Broker.named(name)
            config_file = broker.v2.metadata["catalog_dir"]
            config_file_to_broker[config_file].append(broker)

        for config_file, brokers in config_file_to_broker.items():
            config_file_item = QStandardItem()
            config_file_item.setData(config_file, Qt.DisplayRole)
            self.appendRow(config_file_item)
            for broker in brokers:
                broker_item = QStandardItem()
                broker_item.setData(broker.name, Qt.DisplayRole)
                broker_item.setData(broker, self.broker_role)
                config_file_item.appendRow(broker_item)
示例#28
0
 def append(self, thread):
     item = QStandardItem(repr(thread.method))
     item.setData(thread, role=self.ThreadRole)
     self.appendRow(item)
     self._threads.append(thread)
示例#29
0
from qtpy.QtCore import Qt, QVariant, QSortFilterProxyModel
from qtpy.QtGui import QStandardItemModel, QStandardItem
from qtpy.QtWidgets import QApplication, QTableView


class NumberSortModel(QSortFilterProxyModel):
    def lessThan(self, left, right):
        lvalue = float(left.data())
        rvalue = float(right.data())
        return lvalue < rvalue
    
    
if __name__ == "__main__":
    app = QApplication(sys.argv)
    model = QStandardItemModel(5, 5)
    random.seed()
    for i in range(5):
        for j in range(5):
            item = QStandardItem()
            item.setData(QVariant(str(random.randint(-500, 500)/10.0)), Qt.DisplayRole)
            model.setItem(i, j, item)
            
    proxy = NumberSortModel()
    proxy.setSourceModel(model)
    
    view = QTableView()
    view.setModel(proxy)
    view.setSortingEnabled(True)
    view.show()
    sys.exit(app.exec_())
示例#30
0
    def _build_GUI(self, linelist, table_view):
        panel_layout = QVBoxLayout()
        panel_layout.setSizeConstraint(QLayout.SetMaximumSize)
        self.setLayout(panel_layout)
        # header with line list metadata.
        info = QTextBrowser()
        info.setMaximumHeight(100)
        info.setAutoFillBackground(True)
        info.setStyleSheet("background-color: rgb(230,230,230);")
        for comment in linelist.meta['comments']:
            info.append(comment)

        # buttons and selectors dedicated to the specific list
        # displayed in this pane.
        button_pane = QWidget()
        hlayout = QGridLayout()

        # 'add set' button
        self.create_set_button = QPushButton(self)
        self.create_set_button.setObjectName("add_set_button")
        _translate = QCoreApplication.translate
        self.create_set_button.setText(_translate("MainWindow", "Create set"))
        self.create_set_button.setToolTip(
            "Create new line set from selected lines.")
        self.create_set_button.setSizePolicy(QSizePolicy.Minimum,
                                             QSizePolicy.Minimum)
        hlayout.addWidget(self.create_set_button, 1, 0)

        # the create_set button is enabled/disabled by logic elsewhere
        self.create_set_button.setEnabled(False)
        self.create_set_button.clicked.connect(lambda: self._createSet())

        # 'deselect all' button
        deselect_button = QPushButton(self)
        deselect_button.setObjectName("deselect_button")
        _translate = QCoreApplication.translate
        deselect_button.setText(_translate("MainWindow", "Deselect"))
        deselect_button.setToolTip("Un-select everything on this set.")
        deselect_button.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Minimum)
        hlayout.addWidget(deselect_button, 1, 1)
        deselect_button.clicked.connect(lambda: table_view.clearSelection())

        # color picker
        self.combo_box_color = QComboBox(self)
        self.combo_box_color.setObjectName("color_selector")
        self.combo_box_color.setToolTip(
            "Color for selected lines in this set.")
        model = self.combo_box_color.model()
        for cname in ID_COLORS:
            item = QStandardItem(cname)
            item.setForeground(ID_COLORS[cname])
            item.setData(QColor(ID_COLORS[cname]), role=Qt.UserRole)
            model.appendRow(item)
        hlayout.addWidget(self.combo_box_color, 1, 2)
        hlayout.addWidget(QLabel("Color"), 0, 2)

        # plotting height
        self.height_textbox = QLineEdit(str(DEFAULT_HEIGHT))
        validator = QDoubleValidator()
        validator.setRange(0.05, 0.95, decimals=2)
        self.height_textbox.setValidator(validator)
        self.height_textbox.setFixedWidth(50)
        self.height_textbox.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        self.height_textbox.setToolTip("Relative height to plot.")
        hlayout.addWidget(self.height_textbox, 1, 3)
        hlayout.addWidget(QLabel("Height"), 0, 3)

        # redshift
        self.redshift_textbox = QLineEdit(str(0.0))
        validator = QDoubleValidator()
        validator.setRange(-1.e5, 1.e10, decimals=4)
        self.redshift_textbox.setValidator(validator)
        self.redshift_textbox.setFixedWidth(70)
        self.redshift_textbox.setSizePolicy(QSizePolicy.Fixed,
                                            QSizePolicy.Fixed)
        self.redshift_textbox.setToolTip("Redshift lines by")
        hlayout.addWidget(self.redshift_textbox, 1, 4)
        hlayout.addWidget(QLabel("Redshift"), 0, 4)

        # redshift units
        self.combo_box_z_units = QComboBox(self)
        self.combo_box_z_units.setObjectName("redshift_units")
        self.combo_box_z_units.setToolTip("Redshift units.")
        model = self.combo_box_z_units.model()
        for uname in ['z', 'km/s']:
            item = QStandardItem(uname)
            model.appendRow(item)
        hlayout.addWidget(self.combo_box_z_units, 1, 5)

        # put it all together.
        spacerItem = QSpacerItem(40, 20, QSizePolicy.Expanding,
                                 QSizePolicy.Minimum)
        hlayout.addItem(spacerItem, 1, 6)
        button_pane.setLayout(hlayout)

        panel_layout.addWidget(info)
        panel_layout.addWidget(table_view)
        panel_layout.addWidget(button_pane)
示例#31
0
    app = QApplication([])

    window = QMainWindow()
    layout = QVBoxLayout()
    model = DerivedDataModel()

    from xicam.plugins.hints import PlotHint, ImageHint, CoPlotHint
    parentItem = QStandardItem("blah")
    parentItem.setCheckable(True)
    import numpy as np
    for i in range(3):
        hint = PlotHint(np.arange(10),
                        np.random.random((10, )),
                        name=f"1-Time")
        item = QStandardItem(hint.group)
        item.setData(hint, Qt.UserRole)
        item.setCheckable(True)
        parentItem.appendRow(item)
    hint = ImageHint(np.random.random((100, 100)),
                     xlabel="x",
                     ylabel="y",
                     name="2-Time")
    item = QStandardItem(hint.group)
    item.setData(hint, Qt.UserRole)
    item.setCheckable(True)
    parentItem.appendRow(item)
    model.appendRow(parentItem)

    workflowItem = QStandardItem("A Workflow Result")
    workflowItem.setCheckable(True)
    hints = []
示例#32
0
 def add_device(self, client_item: QStandardItem, device: Device):
     device_item = QStandardItem(device.name)
     device_item.setData(device, self.happiItemRole)
     client_item.appendRow(device_item)