def setupUI(self):
        mainLayout = QVBoxLayout()

        title = QLabel(config.thisTranslation["menu_config_flags"])
        title.mouseReleaseEvent = self.openWiki
        mainLayout.addWidget(title)

        filterLayout = QHBoxLayout()
        filterLayout.addWidget(QLabel(config.thisTranslation["menu5_search"]))
        self.filterEntry = QLineEdit()
        self.filterEntry.textChanged.connect(self.resetItems)
        filterLayout.addWidget(self.filterEntry)
        mainLayout.addLayout(filterLayout)

        self.dataView = QTableView()
        self.dataView.setEditTriggers(QAbstractItemView.NoEditTriggers)
        self.dataView.setSortingEnabled(True)
        self.dataViewModel = QStandardItemModel(self.dataView)
        self.dataView.setModel(self.dataViewModel)
        self.resetItems()
        self.dataViewModel.itemChanged.connect(self.itemChanged)
        mainLayout.addWidget(self.dataView)

        buttonLayout = QHBoxLayout()
        button = QPushButton(config.thisTranslation["close"])
        button.clicked.connect(self.close)
        buttonLayout.addWidget(button)
        button = QPushButton(config.thisTranslation["restoreAllDefaults"])
        button.clicked.connect(self.restoreAllDefaults)
        buttonLayout.addWidget(button)
        mainLayout.addLayout(buttonLayout)

        self.setLayout(mainLayout)
Exemple #2
0
    def getItemModel(self):
        """Return a QModel made from the current workspace. This should be set
        onto a QTableView
        """
        def create_table_item(column, itemname, callable, *args):
            item = QStandardItem()
            item.setEditable(False)
            try:
                item.setText(callable(*args))
            except Exception as exc:
                logger.warning("Error setting column {} for log {}: {}".format(
                    column, itemname, str(exc)))

            return item

        model = QStandardItemModel()
        model.setHorizontalHeaderLabels(["Name", "Type", "Value", "Units"])
        model.setColumnCount(4)
        for key in self.get_log_names():
            log = self.run.getLogData(key)
            name = create_table_item("Name", key, lambda: log.name)
            log_type = create_table_item("Type", key, get_type, log)
            value = create_table_item("Value", key,
                                      lambda log: str(get_value(log)), log)
            unit = create_table_item("Units", key, lambda: log.units)
            model.appendRow((name, log_type, value, unit))

        model.sort(0)
        return model
Exemple #3
0
    def reset_gr_tree(self):
        """
        Clear the leaves of the tree only leaving the main node 'workspaces'
        Returns
        -------

        """
        # clear all
        if self.model() is not None:
            self.model().clear()

        # reset workspace data structures
        self._workspaceNameList = list()
        self._myHeaderList = list()
        self._leafDict.clear()

        # re-initialize the model
        self._myNumCols = 1
        model = QStandardItemModel()
        model.setColumnCount(self._myNumCols)
        self.setModel(model)

        self.init_setup(['G(R) Workspaces'])
        self.add_main_item('workspaces', append=True, as_current_index=False)
        self.add_main_item('SofQ', append=False, as_current_index=False)

        return
Exemple #4
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)
Exemple #5
0
    def __init__(self):
        super(ConfigDialog, self).__init__()

        self.needs_reload = True

        # Set size and position
        self.setGeometry(0, 0, 900, 550)
        frameGm = self.frameGeometry()
        screen = QApplication.desktop().screenNumber(
            QApplication.desktop().cursor().pos())
        centerPoint = QApplication.desktop().screenGeometry(screen).center()
        frameGm.moveCenter(centerPoint)
        self.move(frameGm.topLeft())

        self.contentsWidget = QListView()
        self.contentsWidget.setViewMode(QListView.IconMode)
        # self.contentsWidget.setIconSize(QSize(96, 84))
        self.contentsWidget.setMovement(QListView.Static)
        self.contentsWidget.setMaximumWidth(174)
        self.contentsWidget.setSpacing(12)
        self.contentsWidget.setSelectionMode(QAbstractItemView.SingleSelection)

        self.contentsModel = QStandardItemModel()
        self.contentsWidget.setModel(self.contentsModel)
        self.contentsWidget.selectionModel().currentChanged.connect(
            self.changePage)

        self.buttonboxWidget = QDialogButtonBox(
            QDialogButtonBox.Ok | QDialogButtonBox.Cancel
            | QDialogButtonBox.Apply  # | QDialogButtonBox.Help
        )
        self.buttonboxWidget.button(QDialogButtonBox.Ok).clicked.connect(
            self.ok)
        self.buttonboxWidget.button(QDialogButtonBox.Apply).clicked.connect(
            self.apply)
        self.buttonboxWidget.button(QDialogButtonBox.Cancel).clicked.connect(
            self.close)

        self.pagesWidget = QStackedWidget()

        horizontalLayout = QHBoxLayout()
        horizontalLayout.addWidget(self.contentsWidget)
        horizontalLayout.addWidget(self.pagesWidget, 1)

        mainLayout = QVBoxLayout()
        mainLayout.addLayout(horizontalLayout)
        # mainLayout.addStretch(1)
        mainLayout.addSpacing(12)
        mainLayout.addWidget(self.buttonboxWidget)

        self.setLayout(mainLayout)
        self.setWindowTitle("Config Dialog")

        # Set modality
        self.setModal(True)

        self.lastwidget = None

        # Restore Settings
        pluginmanager.attach(self.request_reload, Filters.COMPLETE)
Exemple #6
0
    def data(self, index, role=Qt.DisplayRole):
        if role == Qt.DisplayRole or role == Qt.EditRole:
            key = self._columns[index.column()]
            tnum = sorted(self._tool_table)[index.row() + 1]
            return self._tool_table[tnum][key]

        elif role == Qt.TextAlignmentRole:
            col = self._columns[index.column()]
            if col == 'R':  # Remark
                return Qt.AlignVCenter | Qt.AlignLeft
            elif col in 'TPQ':  # Integers (Tool, Pocket, Orient)
                return Qt.AlignVCenter | Qt.AlignCenter
            else:  # All the other floats
                return Qt.AlignVCenter | Qt.AlignRight

        elif role == Qt.TextColorRole:
            tnum = sorted(self._tool_table)[index.row() + 1]
            if self.stat.tool_in_spindle == tnum:
                return QBrush(self.current_tool_color)
            else:
                return QStandardItemModel.data(self, index, role)

        elif role == Qt.BackgroundRole and self.current_tool_bg is not None:
            tnum = sorted(self._tool_table)[index.row() + 1]
            if self.stat.tool_in_spindle == tnum:
                return QBrush(self.current_tool_bg)
            else:
                return QStandardItemModel.data(self, index, role)

        return QStandardItemModel.data(self, index, role)
Exemple #7
0
    def reset_gr_tree(self):
        """
        Clear the leaves of the tree only leaving the main node 'workspaces'
        Returns
        -------

        """
        # clear all
        if self.model() is not None:
            self.model().clear()

        # reset workspace data structures
        self._workspaceNameList = list()
        self._myHeaderList = list()
        self._leafDict.clear()

        # re-initialize the model
        self._myNumCols = 1
        model = QStandardItemModel()
        model.setColumnCount(self._myNumCols)
        self.setModel(model)

        self.init_setup(['G(R) Workspaces'])
        self.add_main_item('workspaces', append=True, as_current_index=False)
        self.add_main_item('SofQ', append=False, as_current_index=False)

        return
    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()
Exemple #9
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)
 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
Exemple #11
0
    def make_left_navbar(self):
        """
            Creates the structures tree hierarchy widget and populates 
            it with structures names from the brainglobe-api's Atlas.hierarchy
            tree view.
        """
        # Create QTree widget
        treeView = QTreeView()
        treeView.setExpandsOnDoubleClick(False)
        treeView.setHeaderHidden(True)
        treeView.setStyleSheet(update_css(tree_css, self.palette))
        treeView.setWordWrap(False)

        treeModel = QStandardItemModel()
        rootNode = treeModel.invisibleRootItem()

        # Add element's hierarchy
        tree = self.scene.atlas.hierarchy
        items = {}
        for n, node in enumerate(tree.expand_tree()):
            # Get Node info
            node = tree.get_node(node)
            if node.tag in ["VS", "fiber tracts"]:
                continue

            # Get brainregion name
            name = self.scene.atlas._get_from_structure(
                node.identifier, "name"
            )

            # Create Item
            item = StandardItem(
                name,
                node.tag,
                tree.depth(node.identifier),
                self.palette["text"],
            )

            # Get/assign parents
            parent = tree.parent(node.identifier)
            if parent is not None:
                if parent.identifier not in items.keys():
                    continue
                else:
                    items[parent.identifier].appendRow(item)

            # Keep track of added nodes
            items[node.identifier] = item
            if n == 0:
                root = item

        # Finish up
        rootNode.appendRow(root)
        treeView.setModel(treeModel)
        treeView.expandToDepth(2)
        self.treeView = treeView

        return treeView
Exemple #12
0
    def getItemModel(self, searched_key=''):
        """Return a QModel made from the current workspace. This should be set
        onto a QTableView. The searched_key allows for filtering log entries.
        """
        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

        model = QStandardItemModel()
        model.setHorizontalHeaderLabels(["Name", "Type", "Value", "Units"])
        model.setColumnCount(4)
        logs_to_highlight = self.get_logs_with_invalid_data()
        logs_to_hide = self.get_hidden_logs()
        for key in self.get_log_names():
            if key in logs_to_hide:
                continue
            if searched_key.casefold() not in key.casefold():
                continue
            invalid_value_count = 0
            if key in logs_to_highlight.keys():
                invalid_value_count = logs_to_highlight[key]
            log = self.run.getLogData(key)
            size = log.size() if hasattr(log, 'size') else 0
            name = create_table_item("Name", key, invalid_value_count, size,
                                     lambda: log.name)
            log_type = create_table_item("Type", key, invalid_value_count,
                                         size, get_type, log)
            value = create_table_item("Value", key, invalid_value_count, size,
                                      lambda log: get_value(log), log)
            unit = create_table_item("Units", key, invalid_value_count, size,
                                     lambda: log.units)
            model.appendRow((name, log_type, value, unit))

        model.sort(0)
        return model
Exemple #13
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
Exemple #14
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
Exemple #15
0
    def __init__(self,
                 parent,
                 help_text=None,
                 item_styles=ITEM_STYLES,
                 item_separator_styles=ITEM_SEPARATOR_STYLES):
        """Multi purpose switcher."""
        super(Switcher, self).__init__(parent)
        self._visible_rows = 0
        self._modes = {}
        self._mode_on = ''
        self._item_styles = item_styles
        self._item_separator_styles = item_separator_styles

        # Widgets
        self.edit = QLineEdit(self)
        self.list = QListView(self)
        self.model = QStandardItemModel(self.list)
        self.proxy = SwitcherProxyModel(self.list)
        self.filter = KeyPressFilter()

        # Widgets setup
        self.setWindowFlags(Qt.Popup | Qt.FramelessWindowHint)
        self.setWindowOpacity(0.95)
        #        self.setMinimumHeight(self._MIN_HEIGHT)
        self.setMaximumHeight(self._MAX_HEIGHT)
        self.edit.installEventFilter(self.filter)
        self.edit.setPlaceholderText(help_text if help_text else '')
        self.list.setMinimumWidth(self._MIN_WIDTH)
        self.list.setSpacing(-2)
        self.list.setItemDelegate(HTMLDelegate(self))
        self.list.setFocusPolicy(Qt.NoFocus)
        self.list.setSelectionBehavior(self.list.SelectItems)
        self.list.setSelectionMode(self.list.SingleSelection)
        self.list.setVerticalScrollMode(QAbstractItemView.ScrollPerItem)
        self.proxy.setSourceModel(self.model)
        self.list.setModel(self.proxy)

        # Layout
        layout = QVBoxLayout()
        layout.addWidget(self.edit)
        layout.addWidget(self.list)
        self.setLayout(layout)

        # Signals
        self.filter.sig_up_key_pressed.connect(self.previous_row)
        self.filter.sig_down_key_pressed.connect(self.next_row)
        self.filter.sig_enter_key_pressed.connect(self.enter)
        self.edit.textChanged.connect(self.setup)
        self.edit.textChanged.connect(self.sig_text_changed)
        self.edit.returnPressed.connect(self.enter)
        self.list.clicked.connect(self.enter)
        self.list.clicked.connect(self.edit.setFocus)
        self.list.selectionModel().currentChanged.connect(
            self.current_item_changed)
        self.edit.setFocus()
Exemple #16
0
 def __init__(self, parent, batch_manager):
     super().__init__(parent)
     self.task_count = 0
     self.calculation_manager = batch_manager
     self.whole_progress = QProgressBar(self)
     self.whole_progress.setMinimum(0)
     self.whole_progress.setMaximum(1)
     self.whole_progress.setFormat("%v of %m")
     self.whole_progress.setTextVisible(True)
     self.part_progress = QProgressBar(self)
     self.part_progress.setMinimum(0)
     self.part_progress.setMaximum(1)
     self.part_progress.setFormat("%v of %m")
     self.whole_label = QLabel("All batch progress:", self)
     self.part_label = QLabel("Single batch progress:", self)
     self.cancel_remove_btn = QPushButton("Remove task")
     self.cancel_remove_btn.setDisabled(True)
     self.logs = ExceptionList(self)
     self.logs.setToolTip("Logs")
     self.task_view = QListView()
     self.task_que = QStandardItemModel(self)
     self.task_view.setModel(self.task_que)
     self.process_num_timer = QTimer()
     self.process_num_timer.setInterval(1000)
     self.process_num_timer.setSingleShot(True)
     self.process_num_timer.timeout.connect(self.change_number_of_workers)
     self.number_of_process = QSpinBox(self)
     self.number_of_process.setRange(1, multiprocessing.cpu_count())
     self.number_of_process.setValue(1)
     self.number_of_process.setToolTip(
         "Number of process used in batch calculation")
     self.number_of_process.valueChanged.connect(
         self.process_num_timer_start)
     self.progress_item_dict = {}
     layout = QGridLayout()
     layout.addWidget(self.whole_label, 0, 0, Qt.AlignRight)
     layout.addWidget(self.whole_progress, 0, 1, 1, 2)
     layout.addWidget(self.part_label, 1, 0, Qt.AlignRight)
     layout.addWidget(self.part_progress, 1, 1, 1, 2)
     lab = QLabel("Number of process:")
     lab.setToolTip("Number of process used in batch calculation")
     layout.addWidget(lab, 2, 0)
     layout.addWidget(self.number_of_process, 2, 1)
     layout.addWidget(self.logs, 3, 0, 2, 3)
     layout.addWidget(self.task_view, 0, 4, 4, 1)
     layout.addWidget(self.cancel_remove_btn, 4, 4, 1, 1)
     layout.setColumnMinimumWidth(2, 10)
     layout.setColumnStretch(2, 1)
     self.setLayout(layout)
     self.preview_timer = QTimer()
     self.preview_timer.setInterval(1000)
     self.preview_timer.timeout.connect(self.update_info)
     self.task_view.selectionModel().currentChanged.connect(
         self.task_selection_change)
     self.cancel_remove_btn.clicked.connect(self.task_cancel_remove)
Exemple #17
0
    def __init__(self):
        #Define workflows
        self.my_workflow = MyWorkflow()
        #self.my_workflow_editor = WorkflowEditor(self.my_workflow)
        # Define a GUILayout
        # GUILayouts must provide a center widget
        #self.container_widget = QWidget()
        self.split_widget = CatalogAndAnalysisSplitWidget()
        layout = QVBoxLayout()  # what kind of layout
        self.button = QPushButton("push this")
        #layout.addWidget(self.split_widget) # add things to the layout one by one
        #layout.addWidget(self.button)
        #self.container_widget.setLayout(layout) # apply layout to the basic widget
        bottom_widget = QLabel('bottom')
        left_widget = QLabel('left')
        leftbottom_widget = QLabel('left bottom')
        right_widget = QLabel('right')

        self.model = QStandardItemModel()
        self.selectionmodel = QItemSelectionModel(self.model)
        stream = 'primary'
        field = 'img'
        self.test_tab_view = TabView(self.model,
                                     self.selectionmodel,
                                     widgetcls=MyImageView,
                                     stream=stream,
                                     field=field)

        self.parameter_view = ParameterTree()
        for operation in self.my_workflow.operations:
            parameter_dict = operation.as_parameter()
            for list_parameter in parameter_dict:
                parameter = Parameter.create(**list_parameter)
                self.parameter_view.addParameters(parameter)
        stage_layout = GUILayout(
            center=self.split_widget,
            #left=left_widget,
            #right=right_widget,
            #leftbottom = leftbottom_widget,
            bottom=self.button,
        )
        second_stage_layout = GUILayout(center=self.test_tab_view,
                                        righttop=self.parameter_view)
        #workflow_stage = GUILayout(center=self.test_tab_view, righttop=self.my_workflow_editor)
        #self.button.clicked.connect(self.update_label)
        #self.button.clicked.connect(self.show_message)
        self.button.clicked.connect(self.run_workflow)
        self.stages = {
            'catalogviewer and fft': stage_layout,
            'Something Else': second_stage_layout,
            #'testing workflow editor': workflow_stage,
        }

        super(MyGUIPlugin, self).__init__()
    def __init__(self, parent=None):
        super().__init__(parent)
        self.source_model = QStandardItemModel(parent)
        self.source_model.setColumnCount(3)

        self.source_model.setHeaderData(0, Qt.Horizontal, self.tr("Directory"),
                                        Qt.DisplayRole)
        self.source_model.setHeaderData(1, Qt.Horizontal, self.tr("Name"),
                                        Qt.DisplayRole)
        self.source_model.setHeaderData(2, Qt.Horizontal, self.tr("Location"),
                                        Qt.DisplayRole)
Exemple #19
0
    def setupUI(self):
        from qtpy.QtGui import QStandardItemModel
        from qtpy.QtWidgets import (QPushButton, QLabel, QListView,
                                    QAbstractItemView, QHBoxLayout,
                                    QVBoxLayout, QLineEdit)

        mainLayout = QVBoxLayout()

        readingListLayout = QVBoxLayout()

        readingListLayout.addWidget(QLabel(self.translation[0]))
        readingListLayout.addWidget(
            QLabel("{0}{1}".format(self.translation[1], self.today)))

        filterLayout = QHBoxLayout()
        filterLayout.addWidget(QLabel(self.translation[2]))
        self.filterEntry = QLineEdit()
        self.filterEntry.textChanged.connect(self.resetItems)
        filterLayout.addWidget(self.filterEntry)
        readingListLayout.addLayout(filterLayout)

        self.readingList = QListView()
        self.readingList.setEditTriggers(QAbstractItemView.NoEditTriggers)
        self.readingListModel = QStandardItemModel(self.readingList)
        self.readingList.setModel(self.readingListModel)
        self.resetItems()
        self.readingListModel.itemChanged.connect(self.itemChanged)
        #print(self.readingList.currentIndex().row())
        #self.readingList.selectionModel().selectionChanged.connect(self.function)
        readingListLayout.addWidget(self.readingList)

        buttonsLayout = QHBoxLayout()

        button = QPushButton(self.translation[3])
        button.clicked.connect(self.openInTabs)
        buttonsLayout.addWidget(button)

        self.hideShowButton = QPushButton(self.translation[4])
        self.hideShowButton.clicked.connect(self.hideShowCheckedItems)
        buttonsLayout.addWidget(self.hideShowButton)

        button = QPushButton(self.translation[6])
        button.clicked.connect(self.resetAllItems)
        buttonsLayout.addWidget(button)

        button = QPushButton(self.translation[7])
        button.clicked.connect(self.saveProgress)
        buttonsLayout.addWidget(button)

        mainLayout.addLayout(readingListLayout)
        mainLayout.addLayout(buttonsLayout)

        self.setLayout(mainLayout)
Exemple #20
0
    def __init__(self, parent):
        QGroupBox.__init__(self, parent)
        self._mt_obj_dict = {}
        self.model_stations = QStandardItemModel()

        # setup ui
        self.ui = Ui_GroupBox_select_from_files()
        self.ui.setupUi(self)
        self.ui.listView_stations.setModel(self.model_stations)

        # connect signals
        self.ui.listView_stations.selectionModel().selectionChanged.connect(self._update_selection)
Exemple #21
0
def custom_tree_view(qtbot):
    # Setup item model

    model = QStandardItemModel()
    model.setColumnCount(len(nodes))

    # Setup CustomTreeView to test against
    main_window = MainWindow()
    custom_tree_view = CustomizedTreeView(main_window)
    custom_tree_view._myNumCols = len(nodes)
    custom_tree_view.setModel(model)

    return custom_tree_view
Exemple #22
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
Exemple #23
0
class ChannelPropertiesDialog(QDialog):
    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)
Exemple #24
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()
Exemple #25
0
class StringListWidget(QListView):
    """Display list of strings."""
    def __init__(self, parent):
        super(StringListWidget, self).__init__(parent)
        self.model = QStandardItemModel(self)
        self.setModel(self.model)

    def setData(self, data: list):
        for entry in data:
            item = QStandardItem(str(entry))
            self.model.appendRow(item)

    def addData(self, data: str):
        item = QStandardItem(str(data))
        self.model.appendRow(item)
Exemple #26
0
    def __init__(self, parent, show_period=True, show_frequency=True, allow_range_select=True,
                 select_multiple=True):
        QGroupBox.__init__(self, parent)
        self._mt_objs = None
        self._unique_periods = None
        self._unique_frequencies = None
        self._periods = None
        self._frequencies = None
        self._allow_range = allow_range_select
        self._select_multiple = select_multiple
        self.ui = Ui_GroupBox_frequency_select()
        self.ui.setupUi(self)

        self.ui.label_place_holder.hide()
        self.model_selected = QStandardItemModel()
        self.ui.listView_selected.setModel(self.model_selected)
        self.frequency_delegate = FrequencySelection.FrequencyDelegate(self.ui.listView_selected)
        self.ui.listView_selected.setItemDelegate(self.frequency_delegate)

        self.histogram = FrequencySelection.Histogram(self, allow_range_select=self._allow_range)
        self.histogram.set_unit(self._units[0])
        self.histogram.set_tol(self.ui.doubleSpinBox_tolerance.value())
        self.histogram.frequency_selected.connect(self._frequency_selected)
        self.histogram.frequency_range_selected.connect(self._frequency_selected)
        self.ui.widget_histgram.layout().addWidget(self.histogram)

        self.ui.radioButton_period.setChecked(show_period)
        self.ui.radioButton_frequency.setChecked(show_frequency)
        self.ui.doubleSpinBox_tolerance.setHidden(not self._allow_range)
        self.ui.checkBox_existing_only.setChecked(not self._allow_range)
        self.ui.checkBox_existing_only.setHidden(not self._allow_range)
        self.ui.label_tolerance.setHidden(not self._allow_range)
        self.ui.radioButton_period.setHidden(not (show_period and show_frequency))
        self.ui.radioButton_frequency.setHidden(not (show_period and show_frequency))
        if self.ui.radioButton_frequency.isHidden():
            self.setTitle(self._type[1])
        elif self.ui.radioButton_period.isHidden():
            self.setTitle(self._type[0])

        self.ui.radioButton_frequency.toggled.connect(self._frequency_toggled)
        self.ui.checkBox_existing_only.toggled.connect(self.histogram.select_existing)
        self.ui.checkBox_existing_only.toggled.connect(self.model_selected.clear)
        self.ui.checkBox_show_existing.toggled.connect(self.histogram.show_existing)
        self.ui.checkBox_x_log_scale.toggled.connect(self.histogram.set_x_log_scale)
        self.ui.checkBox_y_log_scale.toggled.connect(self.histogram.set_y_log_scale)
        self.ui.pushButton_clear.clicked.connect(self._clear_all)
        self.ui.pushButton_delete.clicked.connect(self._delete_selected)
        self.ui.doubleSpinBox_tolerance.valueChanged.connect(self.histogram.set_tol)
Exemple #27
0
    def test_custom_eliding_delegate_respects_padding(self):
        padding = 3
        delegate = CustomTextElidingDelegate(padding)
        painter = mock.MagicMock(spec=QPainter)
        # we cannot mock the style & index as they are passed to a C++ type that expects real types
        style, model = QStyleOptionViewItem(), QStandardItemModel(1, 1)
        style.rect = QRect(0, 0, 99,
                           29)  # give a non-zero sized rectangle to paint in
        text = str(math.pi)
        model.setData(model.index(0, 0), text, Qt.DisplayRole)

        delegate.paint(painter, style, model.index(0, 0))

        painter.save.assert_called_once()
        painter.setPen.assert_not_called()
        painter.fillRect.assert_not_called()
        painter.drawText.assert_called_once()
        painter.restore.assert_called_once()

        # first call and second argument is the text that will be painted
        # the exact text depends on the font metric so we have a looser requirement
        # for matching
        drawn_text = painter.drawText.call_args[0][2]
        self.assertTrue(drawn_text.startswith("3.141592"))
        # Qt uses the 'horizontal ellipsis' unicode symbol for ellision.
        # To avoid confusion with it look like 3 separate '.' characters in code
        # we use the unicode codepoint directly
        self.assertTrue(drawn_text.endswith(b"\xe2\x80\xa6".decode("utf-8")))
 def __init__(self):
     self.model = QStandardItemModel()
     super(OneTimeView, self).__init__(self.model)
     plotItem = self._plot.getPlotItem()
     plotItem.setLabel('left', 'g<sub>2</sub>(&tau;)', 's')
     plotItem.setLabel('bottom', '&tau;', 's')
     plotItem.setLogMode(x=True)
Exemple #29
0
    def headerData(self, section, orientation, role=Qt.DisplayRole):
        if role == Qt.DisplayRole and orientation == Qt.Horizontal:
            return self._columns[section]
        elif role == Qt.DisplayRole and orientation == Qt.Vertical:
            return self._row_labels[section]

        return QStandardItemModel.headerData(self, section, orientation, role)
Exemple #30
0
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        loadUi(os.path.abspath(
            os.path.join(os.path.dirname(__file__),
                         "ui", "spectrum_selection.ui")), self)

        self.setWindowTitle('Spectrum Selection')

        self._model = QStandardItemModel(self.spectrumList)
        self.spectrumList.setModel(self._model)
        self._selected = False

        self.buttonBox.accepted.connect(self._confirm_selection)

        self.selectAllButton.clicked.connect(self._select_all)
        self.deselectAllButton.clicked.connect(self._deselect_all)
Exemple #31
0
    def data(self, index, role=Qt.DisplayRole):
        row, col = index.row(), index.column()

        #all_active_codes = [self.active_g_codes, self.active_m_codes]

        if role == Qt.DisplayRole or role == Qt.EditRole:
            if self.active_codes_only:
                a_code = self.active_g_codes[row]
            else:
                a_code = GM_CODES.keys()[row]

            if col == 0:
                return a_code
            elif col == 1:
                return GM_CODES[a_code]

        if self.active_codes_only:
            if role == Qt.TextColorRole:
                return QBrush(self.active_code_color)

            elif role == Qt.BackgroundRole and self.active_code_bg is not None:
                return QBrush(self.active_code_bg)
        else:
            if role == Qt.TextColorRole:
                if GM_CODES.keys()[row] in self.active_g_codes:
                    return QBrush(self.active_code_color)

            elif role == Qt.BackgroundRole and self.active_code_bg is not None:
                if GM_CODES.keys()[row] in self.active_g_codes:
                    return QBrush(self.active_code_bg)

        return QStandardItemModel.data(self, index, role)
Exemple #32
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
Exemple #33
0
class SpectrumSelection(QDialog):
    """
    A widget providing a simple dialog for selecting spectra to be loaded.

    The widget itself knows nothing about spectral data objects, but instead
    just presents a list of strings which represent the names of the available
    spectra, and returns a list of strings which represent the names of the
    spectra that were actually selected.
    """

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        loadUi(os.path.abspath(
            os.path.join(os.path.dirname(__file__),
                         "ui", "spectrum_selection.ui")), self)

        self.setWindowTitle('Spectrum Selection')

        self._model = QStandardItemModel(self.spectrumList)
        self.spectrumList.setModel(self._model)
        self._selected = False

        self.buttonBox.accepted.connect(self._confirm_selection)

        self.selectAllButton.clicked.connect(self._select_all)
        self.deselectAllButton.clicked.connect(self._deselect_all)

    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)

    def get_selected(self):
        """
        Get the list of names that were actually checked when the dialog closes

        This method will return an empty list in the following cases:
            * No items were selected when the dialog closes
            * The "Cancel" button was hit by the user instead of "Open"
            * This method is called before the dialog closes

        Returns
        -------
        names : `list`
            The list of names that were selected when the dialog closes
        """
        if not self._selected:
            return []

        selected = []
        for i in range(self._model.rowCount()):
            item = self._model.item(i)
            if item.checkState() == Qt.Checked:
                selected.append(item.text())
        return selected

    def _confirm_selection(self):
        self._selected = True

    def _select_all(self):
        for i in range(self._model.rowCount()):
            item = self._model.item(i)
            item.setCheckState(Qt.Checked)

    def _deselect_all(self):
        for i in range(self._model.rowCount()):
            item = self._model.item(i)
            item.setCheckState(Qt.Unchecked)