Esempio n. 1
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()
Esempio n. 2
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)
    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)
Esempio n. 4
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()
Esempio n. 5
0
 def commentaryListView(self):
     # https://doc.qt.io/archives/qtforpython-5.12/PySide2/QtCore/QStringListModel.html
     # https://gist.github.com/minoue/9f384cd36339429eb0bf
     # https://www.pythoncentral.io/pyside-pyqt-tutorial-qlistview-and-qstandarditemmodel/
     list = QListView()
     list.setEditTriggers(QAbstractItemView.NoEditTriggers)
     model = QStandardItemModel(list)
     for index, commentary in enumerate(self.parent.commentaryFullNameList):
         item = QStandardItem(commentary)
         item.setToolTip(self.parent.commentaryList[index])
         #item.setCheckable(True)
         #item.setCheckState(Qt.CheckState.Checked)
         #item.setCheckState(Qt.CheckState.Unchecked)
         #print(item.checkState() is Qt.CheckState.Checked)
         model.appendRow(item)
     #model = QStringListModel(self.parent.commentaryList)
     #model = QStringListModel(self.parent.commentaryFullNameList)
     list.setModel(model)
     if config.commentaryText in self.parent.commentaryList:
         list.setCurrentIndex(
             model.index(
                 self.parent.commentaryList.index(config.commentaryText),
                 0))
     list.selectionModel().selectionChanged.connect(self.commentarySelected)
     return list
Esempio n. 6
0
    def __init__(self):
        QDialog.__init__(self)

        # setup UI
        self.form = QFormLayout(self)
        self.editPosition = QLineEdit('')
        self.form.addRow(QLabel('Position'), self.editPosition)
        self.editVelocity = QLineEdit('')
        self.form.addRow(QLabel('Velocity'), self.editVelocity)

        # configure network (take first available servo)
        self._net, self._servo = il.lucky(il.NET_PROT.EUSB)

        # create data model
        model = QStandardItemModel()
        pos = QStandardItem()
        vel = QStandardItem()
        model.appendRow([pos, vel])

        # configure and start watcher
        self._watcher = RegisterWatcher(self._servo)
        self._watcher.add(POS_ACT, 500, pos)
        self._watcher.add(VEL_ACT, 100, vel)
        self._watcher.start(100)

        # map model fields to widgets
        self._mapper = QDataWidgetMapper()
        self._mapper.setModel(model)
        self._mapper.addMapping(self.editPosition, 0)
        self._mapper.addMapping(self.editVelocity, 1)
        self._mapper.toFirst()
Esempio n. 7
0
 def loadData(self):
     # get current map idx
     if not self.isMapOpen():
         return
     # pass the selected map data to plotwidget
     self.rawSpectra.setHeader(self.headers[self.selectMapidx], 'spectra')
     currentMapItem = self.headermodel.item(self.selectMapidx)
     rc2ind = self.rc2indList[self.selectMapidx]
     # get current map name
     mapName = currentMapItem.data(0)
     # get current selected pixels
     pixelCoord = currentMapItem.selectedPixels
     # get selected specIds
     spectraIds = []
     if currentMapItem.selectedPixels is None:  # select all
         spectraIds = list(range(len(rc2ind)))
     else:
         for i in range(len(pixelCoord)):
             row_col = tuple(pixelCoord[i])
             spectraIds.append(rc2ind[row_col])
         spectraIds = sorted(spectraIds)
     # add specitem model
     self.specItemModel.clear()
     for idx in spectraIds:
         item = QStandardItem(mapName + '# ' + str(idx))
         item.idx = idx
         self.specItemModel.appendRow(item)
Esempio n. 8
0
 def set_plot_list(self, plot_list):
     """
     Populate the plot list from the Presenter
     :param plot_list: the list of plot names (list of strings)
     """
     self.list_view.model().clear()
     for plot_name in plot_list:
         item = QStandardItem(plot_name)
         item.setEditable(False)
         self.list_view.model().appendRow(item)
Esempio n. 9
0
 def createIcons(self):
     self.contentsModel.clear()
     for pluginInfo in pluginmanager.getPluginsOfCategory("SettingsPlugin"):
         item = QStandardItem(pluginInfo.plugin_object.icon, pluginInfo.plugin_object.name())
         item.widget = pluginInfo.plugin_object.widget
         item.setTextAlignment(Qt.AlignHCenter)
         item.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEnabled)
         item.setSizeHint(QSize(136, 80))
         self.contentsModel.appendRow(item)
Esempio n. 10
0
    def refresh(self):
        self.clear()

        if not self._proc_interface:
            logger.warning('cannot refresh without a procInterface')
            return

        eprocs = self._proc_interface.eprocs
        for device in eprocs.keys():
            device_item = QStandardItem(device)
            self.appendRow(device_item)
            for eproc in eprocs[device]:
                eproc_item = QStandardItem(eproc)
                device_item.appendRow(eproc_item)
Esempio n. 11
0
    def populate(self, names):
        """
        Add a list of names to be displayed as list items in the dialog

        Parameters
        ----------
        names : `list`
            The list of names to be populated in the dialog
        """
        for s in names:
            item = QStandardItem(s)
            item.setCheckable(True)
            item.setCheckState(Qt.Checked)
            self._model.appendRow(item)
Esempio n. 12
0
 def resetItems(self):
     from qtpy.QtGui import QStandardItem
     from qtpy.QtCore import Qt
     # Empty the model before reset
     self.readingListModel.clear()
     # Reset
     index = 0
     todayIndex = None
     filterEntry = self.filterEntry.text()
     for key, value in self.plan.items():
         checked, passages = value
         if not (self.hideCheckedItems and checked) and (
                 filterEntry == "" or
             (filterEntry != ""
              and filterEntry.lower() in passages.lower())):
             item = QStandardItem("{0}. {1}".format(key, passages))
             item.setToolTip("{0}{1}{2}".format(self.translation[8], key,
                                                self.translation[9]))
             if key == self.todayNo:
                 todayIndex = index
             item.setCheckable(True)
             item.setCheckState(Qt.CheckState.Checked if checked else Qt.
                                CheckState.Unchecked)
             self.readingListModel.appendRow(item)
             index += 1
     if todayIndex is not None:
         self.readingList.setCurrentIndex(
             self.readingListModel.index(todayIndex, 0))
Esempio n. 13
0
    def updatePlot(self, item: QStandardItem):
        self.clear()

        itemIndex = QPersistentModelIndex(item.index())
        if item.checkState():
            self.checkedItemIndexes.append(itemIndex)
        else:
            # TODO -- might need try for ValueError
            self.checkedItemIndexes.remove(itemIndex)

        g2 = list(self.results('norm-0-g2'))
        g2Err = list(self.results('norm-0-stderr'))
        lagSteps = list(self.results('tau'))
        fitCurve = list(self.results('g2avgFIT1'))
        roiList = list(self.results('dqlist'))

        for roi in range(len(self.checkedItemIndexes)):
            yData = g2[roi].squeeze()
            xData = lagSteps[roi].squeeze()

            color = [
                float(roi) / len(self.checkedItemIndexes) * 255,
                (1 - float(roi) / len(self.checkedItemIndexes)) * 255, 255
            ]
            self.plotOpts['pen'] = color
            err = g2Err[roi].squeeze()
            self.plot.addItem(
                pg.ErrorBarItem(x=np.log10(xData),
                                y=yData,
                                top=err,
                                bottom=err,
                                **self.plotOpts))

            curve = self.plot.plot(x=xData, y=yData, **self.plotOpts)
            opts = self.plotOpts.copy()
            opts['pen'] = pg.mkPen(self.plotOpts['pen'])  # type: QPen
            opts['pen'].setStyle(Qt.DashLine)
            name = roiList[roi]
            curveItem = CurveItemSample(curve, name=name)
            self._curveItems.append(curveItem)
            self.legend.addItem(curveItem, curveItem.name)
            if len(fitCurve[roi]) > 0:
                fit_curve = self.plot.plot(x=xData,
                                           y=fitCurve[roi].squeeze(),
                                           **opts)
                fitCurveItem = CurveItemSample(fit_curve, name=f'{name} (fit)')
                self._curveItems.append(fitCurveItem)
                self.legend.addItem(fitCurveItem, fitCurveItem.name)
            self.legend.show()
Esempio n. 14
0
    def insert_child_current_item(self, child_value):
        """
        Insert a child item to currently selected item
        Args:
            child_value:

        Returns:

        """
        current_index = self.currentIndex()
        assert (isinstance(current_index, QModelIndex))
        current_row = current_index.row()
        print('[DEV] Current Index of Row = %d ' % current_row)

        # Get model
        my_model = self.model()
        assert (isinstance(my_model, QStandardItemModel))
        current_item = my_model.itemFromIndex(current_index)

        assert (isinstance(current_item, QStandardItem))

        print('Add Child Value ', child_value)
        # child_item = QStandardItem(child_value)
        child_item = QStandardItem(str(child_value))
        current_item.insertRow(0, [child_item])

        return
Esempio n. 15
0
def create_table_item(data: Any, editable: bool = False):
    """
    Factory function to create a relevant Qt-model item type
    for the given parameters. For non-editable items a QStandardItem
    can be used with just a string representation of the data. For
    editable items we must store the original data such that if editing
    fails it can be reset.
    :param data: Data to be stored in the item
    :param editable: Boolean indicating if the item can be edited
    """
    if editable:
        return RevertibleItem(data)
    else:
        item = QStandardItem(str(data))
        item.setFlags(item.flags() & ~Qt.ItemIsEditable)
        return item
Esempio n. 16
0
 def show_results(self):
     header_labels_set = False
     t0 = time.monotonic()
     counter = 0
     for uid, entry in itertools.islice(self._results_catalog.items(),
                                        MAX_SEARCH_RESULTS):
         if entry in self._results:
             continue
         counter += 1
         self._results.append(entry)
         row = []
         try:
             row_text = 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_text))
             header_labels_set = True
         for text in row_text.values():
             item = QStandardItem(text or '')
             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)
 def on_debug_message(self, message):
     msg = 'DEBUG - occurred at: [ {} ]\n{}'.format(
         NotificationsWidget._get_time(),
         NotificationsWidget._strip_new_line(message))
     notification_item = QStandardItem()
     notification_item.setText(msg)
     notification_item.setIcon(QIcon.fromTheme('dialog-question'))
     notification_item.setEditable(False)
     self.all_notification_model.appendRow(notification_item)
Esempio n. 18
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()
 def on_error_message(self, message):
     msg = 'ERROR - occurred at: [ {} ]\n{}'.format(
         NotificationsWidget._get_time(),
         NotificationsWidget._strip_new_line(message))
     LOG.debug('-----on_error_message called: {}'.format(message))
     notification_item = QStandardItem()
     notification_item.setText(msg)
     notification_item.setIcon(QIcon.fromTheme('dialog-error'))
     notification_item.setEditable(False)
     self.all_notification_model.appendRow(notification_item)
Esempio n. 20
0
    def list_subcatalogs(self):
        self._subcatalogs.clear()
        self.catalog_selection_model.clear()
        if not self.root_catalog:
            return

        for name in self.root_catalog:
            self._subcatalogs.append(name)
            self.catalog_selection_model.appendRow(QStandardItem(str(name)))
Esempio n. 21
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())
Esempio n. 22
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)
Esempio n. 23
0
    def on_debug_message(self, message):
        timestamp = time()
        dt_object = datetime.fromtimestamp(timestamp)

        current_time = str(dt_object)

        msg = 'DEBUG\nTIME {}\n  {}'.format(current_time, message)
        notification_item = QStandardItem()
        notification_item.setText(msg)
        notification_item.setIcon(QIcon.fromTheme('dialog-question'))
        notification_item.setEditable(False)
        self.all_notification_model.appendRow(notification_item)
Esempio n. 24
0
 def videoListView(self):
     list = QListView()
     list.setEditTriggers(QAbstractItemView.NoEditTriggers)
     model = QStandardItemModel(list)
     for file in self.videoList:
         item = QStandardItem(file)
         model.appendRow(item)
     list.setModel(model)
     list.selectionModel().selectionChanged.connect(self.playSelectedVideo)
     return list
Esempio n. 25
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()
Esempio n. 26
0
 def __call__(self, name, doc):
     if name == 'event_page':
         for event in unpack_event_page(doc):
             self.__call__('event', event)
     elif name == 'event':
         column = doc['seq_num'] - 1
         for row, val in enumerate(
                 val for _, val in sorted(doc['data'].items())):
             self.setItem(row, column, QStandardItem(str(val)))
         self.setVerticalHeaderLabels(doc['data'].keys())
Esempio n. 27
0
 def devotionsListView(self):
     list = QListView()
     list.setEditTriggers(QAbstractItemView.NoEditTriggers)
     model = QStandardItemModel(list)
     for devotional in self.devotionals:
         item = QStandardItem(devotional)
         model.appendRow(item)
     list.setModel(model)
     list.selectionModel().selectionChanged.connect(self.devotionalSelected)
     return list
Esempio n. 28
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)
Esempio n. 29
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)
Esempio n. 30
0
    def populate(self, item_list):
        """
        Creates all of the items from the item list and
        appends them to the model.

        item_list (list): list of strings to be displayed to the user
            this should be set with the setCleanItemsFunction.
        """
        self.setItemList(item_list)
        for i, item_name in enumerate(self.getItemList()):
            item = QStandardItem(item_name)
            self.model().setItem(i, 0, item)
            self.setExistsFlag(False)
Esempio n. 31
0
 def pdfListView(self):
     list = QListView()
     list.setEditTriggers(QAbstractItemView.NoEditTriggers)
     model = QStandardItemModel(list)
     for pdf in self.pdfList:
         item = QStandardItem(pdf)
         model.appendRow(item)
     list.setModel(model)
     if config.pdfText in self.parent.pdfList:
         list.setCurrentIndex(
             model.index(self.parent.pdfList.index(config.pdfText), 0))
     list.selectionModel().selectionChanged.connect(self.pdfSelected)
     return list
Esempio n. 32
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)
Esempio n. 33
0
 def getItemModel(self):
     """Return a QModel made from the current workspace. This should be set
     onto a QTableView
     """
     model = QStandardItemModel()
     model.setHorizontalHeaderLabels(["Name", "Type", "Value", "Units"])
     model.setColumnCount(4)
     for key in self.get_log_names():
         log = self.run.getLogData(key)
         name = QStandardItem()
         name.setText(log.name)
         name.setEditable(False)
         log_type = QStandardItem()
         log_type.setText(get_type(log))
         log_type.setEditable(False)
         value = QStandardItem()
         value.setText(str(get_value(log)))
         value.setEditable(False)
         unit = QStandardItem()
         unit.setText(log.units)
         unit.setEditable(False)
         model.appendRow((name, log_type, value, unit))
     model.sort(0)
     return model
Esempio n. 34
0
    def __init__(self, hub, *args, **kwargs):
        super().__init__(*args, **kwargs)

        self.hub = hub

        self.wave_range = (None, None)

        loadUi(os.path.join(os.path.dirname(__file__), "ui", "linelists_window.ui"), self)

        # QtDesigner can't add a combo box to a tool bar...
        self.line_list_selector = QComboBox()
        self.line_list_selector.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        self.line_list_selector.setMinimumWidth(230)
        self.line_list_selector.setToolTip("Select line list from internal library")
        self.main_toolbar.addWidget(self.line_list_selector)

        # QtDesigner creates tabbed widgets with 2 tabs, and doesn't allow
        # removing then in the designer itself. Remove in here then.
        while self.tab_widget.count() > 0:
            self.tab_widget.removeTab(0)

        # Local references for often used objects.
        self.plot_window = self.hub.plot_window

        # Request that line lists be read from wherever are they sources.
        if not hasattr(self, 'linelists'):
            self._request_linelists()

            # Populate line list selector with internal line lists
            model = self.line_list_selector.model()
            item = QStandardItem("Select line list")
            font = QFont("Monospace")
            font.setStyleHint(QFont.TypeWriter)
            font.setPointSize(12)
            item.setFont(font)
            model.appendRow(item)
            for description in linelist.descriptions():
                item = QStandardItem(str(description))
                item.setFont(font)
                model.appendRow(item)

        self.line_labels_plotter = LineLabelsPlotter(self)

        # Connect controls to appropriate signals.

        self.draw_button.clicked.connect(
            lambda:self.line_labels_plotter._plot_linelists(
            table_views=self._get_table_views(),
            panes=self._get_panes(),
            units=self.hub.plot_widget.spectral_axis_unit,
            caller=self.line_labels_plotter))

        self.erase_button.clicked.connect(lambda:self.erase_linelabels.emit(self.plot_window.plot_widget))
        self.dismiss_button.clicked.connect(self.dismiss_linelists_window.emit)

        self.actionOpen.triggered.connect(lambda:self._open_linelist_file(file_name=None))
        self.actionExport.triggered.connect(lambda:self._export_to_file(file_name=None))
        self.line_list_selector.currentIndexChanged.connect(self._lineList_selection_change)
        self.tab_widget.tabCloseRequested.connect(self._on_tab_close)

        self.hub.plot_window.window_removed.connect(self.dismiss_linelists_window.emit)
Esempio n. 35
0
    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()