def resizeEvent(self, event): """Override Qt method""" w = self.width() width_start = 20 width_end = width_start if self._advanced_mode: action_cols = [const.COL_ACTION] else: action_cols = [const.COL_UPGRADE, const.COL_INSTALL, const.COL_REMOVE, const.COL_DOWNGRADE] self.setColumnWidth(const.COL_START, width_start) self.setColumnWidth(const.COL_PACKAGE_TYPE, self.WIDTH_TYPE) self.setColumnWidth(const.COL_NAME, self.WIDTH_NAME) self.setColumnWidth(const.COL_VERSION, self.WIDTH_VERSION) w_new = w - (width_start + self.WIDTH_ACTIONS + self.WIDTH_TYPE + self.WIDTH_NAME + self.WIDTH_VERSION + (len(action_cols))*self.WIDTH_ACTIONS + width_end) self.setColumnWidth(const.COL_DESCRIPTION, w_new) self.setColumnWidth(const.COL_END, width_end) for col in action_cols: self.setColumnWidth(col, self.WIDTH_ACTIONS) QTableView.resizeEvent(self, event) self.resize_rows()
class _DatumTableWidget(_DatumWidget): def __init__(self, clasz, controller, datum=None, parent=None): _DatumWidget.__init__(self, clasz, controller, datum, parent) def _init_ui(self): # Widgets self._table = QTableView() header = self._table.horizontalHeader() mode = QHeaderView.Stretch if os.environ[qtpy.QT_API] in qtpy.PYQT5_API: header.setSectionResizeMode(mode) else: header.setResizeMode(mode) # Layouts layout = _DatumWidget._init_ui(self) layout.addWidget(self._table) return layout def _create_model(self, datum): raise NotImplementedError def setDatum(self, datum): _DatumWidget.setDatum(self, datum) if datum is not None: model = self._create_model(datum) else: model = None self._table.setModel(model)
def keyPressEvent(self, event): """ Override Qt method. """ index = self.currentIndex() key = event.key() if key in [Qt.Key_Enter, Qt.Key_Return]: # self.action_pressed(index) self.setCurrentIndex(self.proxy_model.index(index.row(), const.COL_ACTION)) self.pressed_here = True elif key in [Qt.Key_Tab]: new_row = index.row() + 1 if not self.proxy_model or new_row == self.proxy_model.rowCount(): self.sig_next_focus.emit() else: new_index = self.proxy_model.index(new_row, 0) self.setCurrentIndex(new_index) elif key in [Qt.Key_Backtab]: new_row = index.row() - 1 if new_row < 0: self.sig_previous_focus.emit() else: new_index = self.proxy_model.index(new_row, 0) self.setCurrentIndex(new_index) else: QTableView.keyPressEvent(self, event) self.update_visible_rows()
def __init__(self, parent, data): QTableView.__init__(self, parent) self.model = DependenciesTableModel(self, data) self.setModel(self.model) self.delegate = DependenciesDelegate(self) self.setItemDelegate(self.delegate) self.setup_table()
def __init__(self, parent, model): QTableView.__init__(self, parent) self.setModel(model) self.frozen_table_view = FrozenTableView(self) self.frozen_table_view.update_geometry() self.setHorizontalScrollMode(1) self.setVerticalScrollMode(1) self.horizontalHeader().sectionResized.connect(self.update_section_width) self.verticalHeader().sectionResized.connect(self.update_section_height) self.frozen_table_view.verticalScrollBar().valueChanged.connect( self.verticalScrollBar().setValue) self.sort_old = [None] self.header_class = self.horizontalHeader() self.header_class.sectionClicked.connect(self.sortByColumn) self.menu = self.setup_menu() config_shortcut(self.copy, context='variable_explorer', name='copy', parent=self) self.horizontalScrollBar().valueChanged.connect( lambda val: self.load_more_data(val, columns=True)) self.verticalScrollBar().valueChanged.connect( lambda val: self.load_more_data(val, rows=True)) self.verticalScrollBar().valueChanged.connect( self.frozen_table_view.verticalScrollBar().setValue)
def __init__(self, parent): QTableView.__init__(self, parent) self._model = None # Setting up actions self.date_dayfirst_action = create_action(self, "dayfirst", triggered=ft_partial(self.parse_to_type, atype="date", dayfirst=True)) self.date_monthfirst_action = create_action(self, "monthfirst", triggered=ft_partial(self.parse_to_type, atype="date", dayfirst=False)) self.perc_action = create_action(self, "perc", triggered=ft_partial(self.parse_to_type, atype="perc")) self.acc_action = create_action(self, "account", triggered=ft_partial(self.parse_to_type, atype="account")) self.str_action = create_action(self, "unicode", triggered=ft_partial(self.parse_to_type, atype="unicode")) self.int_action = create_action(self, "int", triggered=ft_partial(self.parse_to_type, atype="int")) self.float_action = create_action(self, "float", triggered=ft_partial(self.parse_to_type, atype="float")) # Setting up menus self.date_menu = QMenu() self.date_menu.setTitle("Date") add_actions( self.date_menu, (self.date_dayfirst_action, self.date_monthfirst_action)) self.parse_menu = QMenu(self) self.parse_menu.addMenu(self.date_menu) add_actions( self.parse_menu, (self.perc_action, self.acc_action)) self.parse_menu.setTitle("String to") self.opt_menu = QMenu(self) self.opt_menu.addMenu(self.parse_menu) add_actions( self.opt_menu, (self.str_action, self.int_action, self.float_action))
def keyPressEvent(self, event): """Override Qt method""" QTableView.keyPressEvent(self, event) if event.key() in [Qt.Key_Enter, Qt.Key_Return]: index = self.currentIndex() self.action_pressed(index) self.pressed_here = True
def __init__(self, parent=None): QTableView.__init__(self, parent) self._parent = parent self.finder = None self.source_model = ShortcutsModel(self) self.proxy_model = CustomSortFilterProxy(self) self.last_regex = '' self.proxy_model.setSourceModel(self.source_model) self.proxy_model.setDynamicSortFilter(True) self.proxy_model.setFilterKeyColumn(NAME) self.proxy_model.setFilterCaseSensitivity(Qt.CaseInsensitive) self.setModel(self.proxy_model) self.hideColumn(SEARCH_SCORE) self.setItemDelegateForColumn(NAME, HTMLDelegate(self, margin=9)) self.setSelectionBehavior(QAbstractItemView.SelectRows) self.setSelectionMode(QAbstractItemView.SingleSelection) self.setSortingEnabled(True) self.setEditTriggers(QAbstractItemView.AllEditTriggers) self.selectionModel().selectionChanged.connect(self.selection) self.verticalHeader().hide() self.load_shortcuts()
def resizeEvent(self, event): """Update the frozen column dimensions. Updates takes place when the enclosing window of this table reports a dimension change """ QTableView.resizeEvent(self, event) self.frozen_table_view.update_geometry()
def __init__(self, parent, data): QTableView.__init__(self, parent) self.model = BreakpointTableModel(self, data) self.setModel(self.model) self.delegate = BreakpointDelegate(self) self.setItemDelegate(self.delegate) self.setup_table()
def scrollTo(self, index, hint): """Scroll the table. It is necessary to ensure that the item at index is visible. The view will try to position the item according to the given hint. This method does not takes effect only if the frozen column is scrolled. """ if index.column() > 1: QTableView.scrollTo(self, index, hint)
def mousePressEvent(self, event): """Override Qt method""" QTableView.mousePressEvent(self, event) self.current_index = self.currentIndex() if event.button() == Qt.LeftButton: pos = QPoint(event.x(), event.y()) index = self.indexAt(pos) self.action_pressed(index) elif event.button() == Qt.RightButton: self.context_menu_requested(event)
def resizeEvent(self, event): """Override Qt method""" w = self.width() self.setColumnWidth(const.NAME, self.WIDTH_NAME) self.setColumnWidth(const.VERSION, self.WIDTH_VERSION) w_new = w - (self.WIDTH_NAME + self.WIDTH_VERSION + (len(const.ACTION_COLUMNS) + 1) * self.WIDTH_ACTIONS) self.setColumnWidth(const.DESCRIPTION, w_new) for col in const.ACTION_COLUMNS: self.setColumnWidth(col, self.WIDTH_ACTIONS) QTableView.resizeEvent(self, event) self.resize_rows()
def __init__(self, parent, model): QTableView.__init__(self, parent) self.setModel(model) self.sort_old = [None] self.header_class = self.horizontalHeader() self.header_class.sectionClicked.connect(self.sortByColumn) self.menu = self.setup_menu() new_shortcut(QKeySequence.Copy, self, self.copy) self.horizontalScrollBar().valueChanged.connect( lambda val: self.load_more_data(val, columns=True)) self.verticalScrollBar().valueChanged.connect( lambda val: self.load_more_data(val, rows=True))
def __init__(self, parent): QTableView.__init__(self, parent) self._parent = parent self.delete_queue = [] self.source_model = LSPServersModel(self) self.setModel(self.source_model) self.setItemDelegateForColumn(CMD, ItemDelegate(self)) self.setSelectionBehavior(QAbstractItemView.SelectRows) self.setSelectionMode(QAbstractItemView.SingleSelection) self.setSortingEnabled(True) self.setEditTriggers(QAbstractItemView.AllEditTriggers) self.selectionModel().selectionChanged.connect(self.selection) self.verticalHeader().hide() self.load_servers()
def __init__(self, parent, model, dtype, shape): QTableView.__init__(self, parent) self.setModel(model) self.setItemDelegate(ArrayDelegate(dtype, self)) total_width = 0 for k in range(shape[1]): total_width += self.columnWidth(k) self.viewport().resize(min(total_width, 1024), self.height()) self.shape = shape self.menu = self.setup_menu() fixed_shortcut(QKeySequence.Copy, self, self.copy) self.horizontalScrollBar().valueChanged.connect(lambda val: self.load_more_data(val, columns=True)) self.verticalScrollBar().valueChanged.connect(lambda val: self.load_more_data(val, rows=True))
def mousePressEvent(self, event): """Override Qt method""" QTableView.mousePressEvent(self, event) self.current_index = self.currentIndex() column = self.current_index.column() if event.button() == Qt.LeftButton and column == const.COL_ACTION: pos = QPoint(event.x(), event.y()) index = self.indexAt(pos) self.action_pressed(index) self.context_menu_requested(event) elif event.button() == Qt.RightButton: self.context_menu_requested(event, right_click=True) self.update_visible_rows()
def keyReleaseEvent(self, event): """Override Qt method""" QTableView.keyReleaseEvent(self, event) key = event.key() index = self.currentIndex() if key in [Qt.Key_Enter, Qt.Key_Return] and self.pressed_here: self.context_menu_requested(event) # self.action_released() elif key in [Qt.Key_Menu]: self.setCurrentIndex(self.proxy_model.index(index.row(), const.COL_ACTION)) self.context_menu_requested(event, right_click=True) self.pressed_here = False self.update_visible_rows()
def __init__(self, parent, text_color=None): QTableView.__init__(self, parent) self._parent = parent self.delete_queue = [] self.source_model = LSPServersModel(self, text_color=text_color) self.setModel(self.source_model) self.setItemDelegateForColumn(CMD, ItemDelegate(self)) self.setSelectionBehavior(QAbstractItemView.SelectRows) self.setSelectionMode(QAbstractItemView.SingleSelection) self.setSortingEnabled(True) self.setEditTriggers(QAbstractItemView.AllEditTriggers) self.selectionModel().selectionChanged.connect(self.selection) self.verticalHeader().hide() self.load_servers()
def create_table_index(self): """Create the QTableView that will hold the index model.""" self.table_index = QTableView() self.table_index.horizontalHeader().hide() self.table_index.setEditTriggers(QTableWidget.NoEditTriggers) self.table_index.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff) self.table_index.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff) self.table_index.setVerticalScrollMode(QTableView.ScrollPerPixel) self.table_index.setVerticalScrollBar(self.vscroll) self.table_index.setFrameStyle(QFrame.Plain) self.table_index.verticalHeader().sectionResized.connect( self._row_resized) # self.table_index.setItemDelegate(QItemDelegate()) self.layout.addWidget(self.table_index, 1, 0) self.table_index.setContentsMargins(0, 0, 0, 0)
def __init__(self, parent, model): QTableView.__init__(self, parent) self.setModel(model) self.sort_old = [None] self.header_class = self.horizontalHeader() self.header_class.sectionClicked.connect(self.sortByColumn) self.menu = self.setup_menu() config_shortcut(self.copy, context='variable_explorer', name='copy', parent=self) self.horizontalScrollBar().valueChanged.connect( lambda val: self.load_more_data(val, columns=True)) self.verticalScrollBar().valueChanged.connect( lambda val: self.load_more_data(val, rows=True))
def __init__(self, parent, model, dtype, shape): QTableView.__init__(self, parent) self.setModel(model) self.setItemDelegate(QuantityArrayDelegate(dtype, self)) total_width = 0 for k in range(shape[1]): total_width += self.columnWidth(k) self.viewport().resize(min(total_width, 1024), self.height()) self.shape = shape self.menu = self.setup_menu() # config_shortcut(self.copy, context='variable_explorer', name='copy', parent=self) self.horizontalScrollBar().valueChanged.connect(lambda val: self.load_more_data(val, columns=True)) self.verticalScrollBar().valueChanged.connect(lambda val: self.load_more_data(val, rows=True))
def create_table_level(self): """Create the QTableView that will hold the level model.""" self.table_level = QTableView() self.table_level.setEditTriggers(QTableWidget.NoEditTriggers) self.table_level.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff) self.table_level.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff) self.table_level.setFrameStyle(QFrame.Plain) self.table_level.horizontalHeader().sectionResized.connect( self._index_resized) self.table_level.verticalHeader().sectionResized.connect( self._header_resized) # self.table_level.setItemDelegate(QItemDelegate()) self.layout.addWidget(self.table_level, 0, 0) self.table_level.setContentsMargins(0, 0, 0, 0) self.table_level.horizontalHeader().sectionClicked.connect( self.sortByIndex)
def _init_ui(self): # Widgets model = self._CompositionModel() self._table = QTableView() self._table.setModel(model) self._table.setItemDelegate(self._CompositionDelegate(self)) self._table.horizontalHeader().setStretchLastSection(True) self._toolbar = QToolBar() action_add = self._toolbar.addAction(getIcon("list-add"), "Add layer") action_remove = self._toolbar.addAction(getIcon("list-remove"), "Remove layer") # Layouts layout = _CompositionWidget._init_ui(self) layout.addRow(self._table) layout.addRow(self._toolbar) # Signals action_add.triggered.connect(self._on_add) action_remove.triggered.connect(self._on_remove) model.dataChanged.connect(self.edited) model.rowsInserted.connect(self.edited) model.rowsRemoved.connect(self.edited) return layout
def __init__(self, parent, model, dtype, shape): QTableView.__init__(self, parent) self.setModel(model) self.setItemDelegate(ArrayDelegate(dtype, self)) total_width = 0 for k in range(shape[1]): total_width += self.columnWidth(k) self.viewport().resize(min(total_width, 1024), self.height()) self.shape = shape self.menu = self.setup_menu() fixed_shortcut(QKeySequence.Copy, self, self.copy) self.horizontalScrollBar().valueChanged.connect( lambda val: self.load_more_data(val, columns=True)) self.verticalScrollBar().valueChanged.connect( lambda val: self.load_more_data(val, rows=True))
def setup_ui(self): self.vertical_layout = QVBoxLayout(self) self.table_view = QTableView(self) self.table_view.setEditTriggers(QAbstractItemView.DoubleClicked) self.table_view.setProperty("showDropIndicator", False) self.table_view.setDragDropOverwriteMode(False) self.table_view.setSelectionMode(QAbstractItemView.SingleSelection) self.table_view.setSelectionBehavior(QAbstractItemView.SelectRows) self.table_view.setSortingEnabled(False) self.table_view.horizontalHeader().setStretchLastSection(True) self.table_view.verticalHeader().setVisible(False) self.table_view.setColumnWidth(0, 160) self.table_view.setColumnWidth(1, 160) self.table_view.setColumnWidth(2, 160) self.vertical_layout.addWidget(self.table_view) self.add_remove_layout = QHBoxLayout() spacer = QSpacerItem(40, 20, QSizePolicy.Expanding, QSizePolicy.Minimum) self.add_remove_layout.addItem(spacer) self.add_button = QPushButton("Add Curve", self) self.add_remove_layout.addWidget(self.add_button) self.remove_button = QPushButton("Remove Curve", self) self.add_remove_layout.addWidget(self.remove_button) self.vertical_layout.addLayout(self.add_remove_layout) self.button_box = QDialogButtonBox(self) self.button_box.setOrientation(Qt.Horizontal) self.button_box.addButton("Done", QDialogButtonBox.AcceptRole) self.vertical_layout.addWidget(self.button_box) self.button_box.accepted.connect(self.saveChanges) self.button_box.rejected.connect(self.reject) self.setWindowTitle("Waveform Curve Editor")
def mousePressEvent(self, event): """Override Qt method.""" QTableView.mousePressEvent(self, event) pos = QPoint(event.x(), event.y()) index = self.indexAt(pos) model = self.source_model if self.proxy_model is None or self.source_model is None: return model_index = self.proxy_model.mapToSource(index) row = model_index.row() if row == -1: return column = model_index.column() row_data = self.source_model.row(row) remove_actions = self.source_model.count_remove_actions() # install_actions = self.source_model.count_install_actions() action = row_data[C.COL_ACTION] status = row_data[C.COL_STATUS] right_click = event.button() == Qt.RightButton left_click = event.button() == Qt.LeftButton if column == C.COL_ACTION: if right_click or (left_click and status != C.NOT_INSTALLED): self.context_menu_requested(event) elif left_click and status == C.NOT_INSTALLED: # 1-click install/uncheck if not installed if action == C.ACTION_NONE and not remove_actions: self.set_action_status(model_index, C.ACTION_INSTALL) elif status: self.set_action_status(model_index, C.ACTION_NONE) elif (column == C.COL_VERSION and model.is_upgradable(model_index) and left_click): # 1-click update name = row_data[C.COL_NAME] versions = model.get_package_versions(name) self.set_action_status(model_index, C.ACTION_UPGRADE, versions[-1]) self.update_visible_rows()
def setupUI(self): mainLayout = QVBoxLayout() title = QLabel(config.thisTranslation["bibleCollections"]) mainLayout.addWidget(title) self.collectionsLayout = QVBoxLayout() self.collectionsList = QListWidget() self.collectionsList.setMaximumHeight(90) self.collectionsLayout.addWidget(self.collectionsList) mainLayout.addLayout(self.collectionsLayout) self.showListOfCollections() buttonsLayout = QHBoxLayout() addButton = QPushButton(config.thisTranslation["add"]) addButton.clicked.connect(self.addNewCollection) buttonsLayout.addWidget(addButton) removeButton = QPushButton(config.thisTranslation["remove"]) removeButton.clicked.connect(self.removeCollection) buttonsLayout.addWidget(removeButton) renameButton = QPushButton(config.thisTranslation["rename"]) renameButton.clicked.connect(self.renameCollection) buttonsLayout.addWidget(renameButton) buttonsLayout.addStretch() mainLayout.addLayout(buttonsLayout) self.biblesTable = QTableView() self.biblesTable.setEnabled(False) self.biblesTable.setEditTriggers(QAbstractItemView.NoEditTriggers) self.biblesTable.setSortingEnabled(True) self.dataViewModel = QStandardItemModel(self.biblesTable) self.biblesTable.setModel(self.dataViewModel) self.loadBibleSelection() self.dataViewModel.itemChanged.connect(self.bibleSelectionChanged) mainLayout.addWidget(self.biblesTable) buttonLayout = QHBoxLayout() button = QPushButton(config.thisTranslation["close"]) button.clicked.connect(self.reloadControlPanel) button.clicked.connect(self.close) buttonLayout.addWidget(button) mainLayout.addLayout(buttonLayout) self.setLayout(mainLayout)
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)
def keyPressEvent(self, event): """Override Qt method.""" index = self.currentIndex() key = event.key() rows = self.verticalHeader().count() if MAC: if key == Qt.Key_Home: self.scrollToTop() self.setCurrentIndex(self.model().index(0, 0)) elif key == Qt.Key_End: self.scrollToBottom() self.setCurrentIndex(self.model().index(rows - 1, 0)) elif key == Qt.Key_Up: previous = index.row() - 1 if index.row() - 1 > 0 else 0 self.setCurrentIndex(self.model().index(previous, 0)) elif key == Qt.Key_Down: next_ = index.row() + 1 if index.row() + 1 < rows else rows - 1 self.setCurrentIndex(self.model().index(next_, 0)) if key in [Qt.Key_Enter, Qt.Key_Return]: # self.action_pressed(index) self.setCurrentIndex( self.proxy_model.index(index.row(), C.COL_ACTION)) self.pressed_here = True elif key in [Qt.Key_Tab]: new_row = index.row() + 1 if not self.proxy_model or new_row == self.proxy_model.rowCount(): self.sig_next_focus.emit() else: new_index = self.proxy_model.index(new_row, 0) self.setCurrentIndex(new_index) elif key in [Qt.Key_Backtab]: new_row = index.row() - 1 if new_row < 0: self.sig_previous_focus.emit() else: new_index = self.proxy_model.index(new_row, 0) self.setCurrentIndex(new_index) else: QTableView.keyPressEvent(self, event) self.update_visible_rows()
def moveCursor(self, cursorAction, modifiers): current = QTableView.moveCursor(self, cursorAction, modifiers) x = self.visualRect(current).topLeft().x() frozen_width = self.frozenTableView.columnWidth( 0) + self.frozenTableView.columnWidth(1) if cursorAction == self.MoveLeft and current.column( ) > 1 and x < frozen_width: new_value = self.horizontalScrollBar().value() + x - frozen_width self.horizontalScrollBar().setValue(new_value) return current
class DataFrameWidget(QWidget): ''' a simple widget for using DataFrames in a gui ''' def __init__(self, dataFrame, parent=None): super(DataFrameWidget, self).__init__(parent) self.dataModel = DataFrameModel() self.dataTable = QTableView() self.dataTable.setModel(self.dataModel) layout = QVBoxLayout() layout.addWidget(self.dataTable) self.setLayout(layout) # Set DataFrame self.setDataFrame(dataFrame) def setDataFrame(self, dataFrame): self.dataModel.setDataFrame(dataFrame) self.dataModel.signalUpdate() self.dataTable.resizeColumnsToContents()
def __init__(self, parent, model, hpos, vpos): QTableView.__init__(self, parent) # set model self.setModel(model) # set position if not (hpos == LEFT or hpos == RIGHT): raise TypeError("Value of hpos must be {} or {}".format( LEFT, RIGHT)) self.hpos = hpos if not (vpos == TOP or vpos == BOTTOM): raise TypeError("Value of vpos must be {} or {}".format( TOP, BOTTOM)) self.vpos = vpos # set selection mode self.setSelectionMode(QTableView.ContiguousSelection) # prepare headers + cells size self.horizontalHeader().setFrameStyle(QFrame.NoFrame) self.verticalHeader().setFrameStyle(QFrame.NoFrame) self.set_default_size() # hide horizontal/vertical headers if hpos == RIGHT: self.verticalHeader().hide() if vpos == BOTTOM: self.horizontalHeader().hide() # to fetch more rows/columns when required self.horizontalScrollBar().valueChanged.connect( self.on_horizontal_scroll_changed) self.verticalScrollBar().valueChanged.connect( self.on_vertical_scroll_changed) # Hide scrollbars self.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff) self.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff) # update geometry if not (hpos == RIGHT and vpos == BOTTOM): self.model().modelReset.connect(self.updateGeometry) self.horizontalHeader().sectionResized.connect(self.updateGeometry) self.verticalHeader().sectionResized.connect(self.updateGeometry)
def setupUI(self): mainLayout = QVBoxLayout() title = QLabel(config.thisTranslation["liveFilter"]) mainLayout.addWidget(title) self.filtersTable = QTableView() self.filtersTable.setEnabled(True) self.filtersTable.setEditTriggers(QAbstractItemView.NoEditTriggers) self.filtersTable.setSortingEnabled(True) self.dataViewModel = QStandardItemModel(self.filtersTable) self.filtersTable.setModel(self.dataViewModel) self.dataViewModel.itemChanged.connect(self.filterSelectionChanged) self.selectionModel = self.filtersTable.selectionModel() self.selectionModel.selectionChanged.connect(self.handleSelection) mainLayout.addWidget(self.filtersTable) self.reloadFilters() buttonsLayout = QHBoxLayout() addButton = QPushButton(config.thisTranslation["add"]) addButton.clicked.connect(self.addNewFilter) buttonsLayout.addWidget(addButton) removeButton = QPushButton(config.thisTranslation["remove"]) removeButton.clicked.connect(self.removeFilter) buttonsLayout.addWidget(removeButton) editButton = QPushButton(config.thisTranslation["edit"]) editButton.clicked.connect(self.editFilter) buttonsLayout.addWidget(editButton) importButton = QPushButton(config.thisTranslation["import"]) importButton.clicked.connect(self.importFile) buttonsLayout.addWidget(importButton) buttonsLayout.addStretch() mainLayout.addLayout(buttonsLayout) buttons = QDialogButtonBox.Ok self.buttonBox = QDialogButtonBox(buttons) self.buttonBox.accepted.connect(self.accept) self.buttonBox.accepted.connect(self.close) self.buttonBox.rejected.connect(self.reject) mainLayout.addWidget(self.buttonBox) self.setLayout(mainLayout)
def __init__(self, parent, data): if PYQT5: super().__init__(parent, class_parent=parent) else: QTableView.__init__(self, parent) SpyderWidgetMixin.__init__(self, class_parent=parent) # Widgets self.model = BreakpointTableModel(self, data) self.delegate = BreakpointDelegate(self) # Setup self.setSortingEnabled(False) self.setSelectionBehavior(self.SelectRows) self.setSelectionMode(self.SingleSelection) self.setModel(self.model) self.setItemDelegate(self.delegate) self.adjust_columns() self.columnAt(0) self.horizontalHeader().setStretchLastSection(True)
def _build_left_dock(self): # QTreeView for the project view w_project_tree = QDockWidget("Project tree", self) w_project_tree.setFloating(False) self._docks['project tree'] = w_project_tree self.addDockWidget(Qt.LeftDockWidgetArea, w_project_tree) # Add the treeview treeview = QTreeView(w_project_tree) treedelegate = TreeDelegate() treeview.setItemDelegate(treedelegate) pm = ProjectModel() self._models["project"] = pm treeview.setModel(pm) treeview.expandAll() treeview.resizeColumnToContents(0) treeview.resizeColumnToContents(1) w_project_tree.setWidget(treeview) treeview.clicked.connect(self.treeItemClicked) # Formatting Editor w_properties = QDockWidget("Properties editor", self) w_properties.setFloating(False) self._docks['properties'] = w_properties self.addDockWidget(Qt.LeftDockWidgetArea, w_properties) # Create Container widget container = QWidget(w_properties) # Create a verticallayout in which we put a treeview and a tableview v_layout = QVBoxLayout(w_properties) # Positions Properties to start with # the treeview will contain the widgets for the properties of the selected item in the tree treeview = QTreeView(w_properties) v_layout.addWidget(treeview) v_layout.setStretchFactor(treeview, 2) treedelegate = PropertiesTreeDelegate() treeview.setItemDelegate(treedelegate) pm = PropertiesTreeModel() self._models['properties'] = pm treeview.setModel(pm) treeview.expandAll() # The tableview will only contain editable x,y shown as rows tableview = QTableView(w_properties) v_layout.addWidget(tableview) v_layout.setStretchFactor(tableview, 1) container.setLayout(v_layout) w_properties.setWidget(container) # Formatting Editor w_formatting = QDockWidget("Formatting editor", self) w_formatting.setFloating(False) self._docks['formatting'] = w_formatting self.addDockWidget(Qt.LeftDockWidgetArea, w_formatting)
def setupUI(self, initialVerse=""): from qtpy.QtGui import QStandardItemModel from qtpy.QtWidgets import (QPushButton, QLabel, QTableView, QHBoxLayout, QVBoxLayout, QLineEdit) #from qtpy.QtWidgets import QAbstractItemView mainLayout = QVBoxLayout() mainLayout.addWidget(QLabel(self.translation[0])) layout = QHBoxLayout() layout.addWidget(QLabel(self.translation[1])) self.searchEntry = QLineEdit() # Set initial entry self.searchEntry.setText(initialVerse if initialVerse else "John 3:16") self.searchEntry.returnPressed.connect(self.resetItems) layout.addWidget(self.searchEntry) mainLayout.addLayout(layout) self.dataView = QTableView() # Allow editing so that users can select text and copy #self.dataView.setEditTriggers(QAbstractItemView.NoEditTriggers) self.dataView.setSortingEnabled(True) self.dataViewModel = QStandardItemModel(self.dataView) self.dataView.setModel(self.dataViewModel) self.resetItems() mainLayout.addWidget(self.dataView) buttonLayout = QHBoxLayout() button = QPushButton(self.translation[4]) button.clicked.connect(self.close) buttonLayout.addWidget(button) button = QPushButton(self.translation[3]) button.clicked.connect(self.exportSpreadsheet) buttonLayout.addWidget(button) mainLayout.addLayout(buttonLayout) self.setLayout(mainLayout)
def __init__(self, viewer: 'napari.viewer.Viewer'): super(QtPropertiesTable, self).__init__() self.viewer = viewer # create the table widget self.table = QTableView() # Create a combobox for selecting layers self.layer_combo_box = QComboBox(self) self.selected_layer = None self.layer_combo_box.currentIndexChanged.connect( self.on_layer_selection) self.initialize_layer_combobox() self.viewer.layers.events.inserted.connect(self.on_add_layer) self.viewer.layers.events.removed.connect(self.on_remove_layer) self.vbox_layout = QVBoxLayout() self.vbox_layout.addWidget(self.layer_combo_box) self.vbox_layout.addWidget(self.table) self.setLayout(self.vbox_layout)
def keyPressEvent(self, event): """Reimplement Qt method""" # comparing with the keysequence and not with event directly as we # did before because that only seems to work for shortcut # defined using QKeySequence.StandardKey, which is not the case for # Ctrl + E keyseq = QKeySequence(event.modifiers() | event.key()) if keyseq == QKeySequence.Copy: self.copy() elif keyseq == QKeySequence.Paste: self.paste() elif keyseq == QKeySequence.Print: self.parent().plot() elif keyseq == "Ctrl+E": self.to_excel() # allow to start editing cells by pressing Enter elif event.key() == Qt.Key_Return and not self.model().readonly: index = self.currentIndex() if self.itemDelegate(index).editor_count == 0: self.edit(index) else: QTableView.keyPressEvent(self, event)
class DisplayShortcutsWindow(QDialog): def __init__(self, name, shortcuts): super(DisplayShortcutsWindow, self).__init__() self.name = name self.setWindowTitle(name) self.setMinimumWidth(360) self.setMinimumHeight(500) self.layout = QVBoxLayout() self.filterEntry = QLineEdit() self.filterEntry.textChanged.connect(self.filterChanged) self.layout.addWidget(self.filterEntry) self.table = QTableView() self.model = DisplayShortcutsModel(self, shortcuts) self.table.setModel(self.model) self.table.resizeColumnsToContents() self.table.setSortingEnabled(True) if self.name not in ShortcutUtil.data.keys(): self.table.doubleClicked.connect(self.clickedRow) self.layout.addWidget(self.table) if name in ShortcutUtil.data.keys(): buttons = QDialogButtonBox.Ok else: buttons = QDialogButtonBox.Ok | QDialogButtonBox.Cancel self.buttonBox = QDialogButtonBox(buttons) self.buttonBox.accepted.connect(self.saveShortcut) self.buttonBox.accepted.connect(self.accept) self.buttonBox.rejected.connect(self.reject) self.buttonBox.rejected.connect(self.canceled) self.layout.addWidget(self.buttonBox) self.setLayout(self.layout) def clickedRow(self, index): row = self.model.getRow(index.row()) (action, key) = row newKey, ok = QInputDialog.getText(self, 'Shortcut', action, QLineEdit.Normal, key) if ok: self.model.list[index.row()] = (action, newKey) for item in self.model.fullList: if item[0] == action: item[1] = newKey def saveShortcut(self): if self.name not in ShortcutUtil.data.keys(): ShortcutUtil.createShortcutFile(self.name, self.model.fullList) def canceled(self): if self.name not in ShortcutUtil.data.keys(): ShortcutUtil.loadShortcutFile(self.name) def filterChanged(self, text): self.model.filter(text)
def __init__(self, parent): """Constructor.""" QTableView.__init__(self, parent) self.parent = parent self.setModel(parent.model()) self.setFocusPolicy(Qt.NoFocus) self.verticalHeader().hide() if PYQT5: self.horizontalHeader().setSectionResizeMode(QHeaderView.Fixed) else: self.horizontalHeader().setResizeMode(QHeaderView.Fixed) parent.viewport().stackUnder(self) self.setSelectionModel(parent.selectionModel()) for col in range(1, parent.model().columnCount()): self.setColumnHidden(col, True) self.setColumnWidth(0, parent.columnWidth(0)) self.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff) self.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff) self.show() self.setVerticalScrollMode(1)
def __init__(self, parent): """Constructor.""" QTableView.__init__(self, parent) self.parent = parent self.setModel(parent.model()) self.setFocusPolicy(Qt.NoFocus) self.verticalHeader().hide() try: self.horizontalHeader().setSectionResizeMode(QHeaderView.Fixed) except: # support for qtpy<1.2.0 self.horizontalHeader().setResizeMode(QHeaderView.Fixed) parent.viewport().stackUnder(self) self.setSelectionModel(parent.selectionModel()) for col in range(1, parent.model().columnCount()): self.setColumnHidden(col, True) self.setColumnWidth(0, parent.columnWidth(0)) self.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff) self.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff) self.show() self.setVerticalScrollMode(1)
def _init_ui(self): # Widgets self._table = QTableView() header = self._table.horizontalHeader() mode = QHeaderView.Stretch if os.environ[qtpy.QT_API] in qtpy.PYQT5_API: header.setSectionResizeMode(mode) else: header.setResizeMode(mode) # Layouts layout = _DatumWidget._init_ui(self) layout.addWidget(self._table) return layout
def moveCursor(self, cursor_action, modifiers): """Update the table position. Updates the position along with the frozen column when the cursor (selector) changes its position """ current = QTableView.moveCursor(self, cursor_action, modifiers) col_width = (self.frozen_table_view.columnWidth(0) + self.frozen_table_view.columnWidth(1)) topleft_x = self.visualRect(current).topLeft().x() overflow = self.MoveLeft and current.column() > 1 overflow = overflow and topleft_x < col_width if cursor_action == overflow: new_value = (self.horizontalScrollBar().value() + topleft_x - col_width) self.horizontalScrollBar().setValue(new_value) return current
def _init_ui(self): # Widgets self._table = QTableView() self._table.setModel(self._SpecimenPositionModel()) self._table.setItemDelegate(self._SpecimenPositionDelegate(self)) self._table.horizontalHeader().setStretchLastSection(True) self._toolbar = QToolBar() action_add = self._toolbar.addAction(getIcon("list-add"), "Add layer") action_remove = self._toolbar.addAction(getIcon("list-remove"), "Remove layer") # Layouts layout = ParameterWidget._init_ui(self) layout.addRow(self._table) layout.addRow(self._toolbar) # Signals action_add.triggered.connect(self._on_add) action_remove.triggered.connect(self._on_remove) return layout
class ConfigFlagsWindow(QDialog): def __init__(self, parent): super().__init__() self.parent = parent # set title self.setWindowTitle(config.thisTranslation["menu_config_flags"]) self.setMinimumSize(830, 500) # set variables self.setupVariables() # setup interface self.setupUI() def setupVariables(self): self.isUpdating = False 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) def getOptions(self): options = [ ("showControlPanelOnStartup", config.showControlPanelOnStartup, self.showControlPanelOnStartupChanged, False, config.thisTranslation["showControlPanelOnStartup"]), ("preferControlPanelForCommandLineEntry", config.preferControlPanelForCommandLineEntry, self.preferControlPanelForCommandLineEntryChanged, False, config.thisTranslation["preferControlPanelForCommandLineEntry"]), ("closeControlPanelAfterRunningCommand", config.closeControlPanelAfterRunningCommand, self.closeControlPanelAfterRunningCommandChanged, True, config.thisTranslation["closeControlPanelAfterRunningCommand"]), ("restrictControlPanelWidth", config.restrictControlPanelWidth, self.restrictControlPanelWidthChanged, False, config.thisTranslation["restrictControlPanelWidth"]), ("clearCommandEntry", config.clearCommandEntry, self.clearCommandEntryChanged, False, config.thisTranslation["clearCommandEntry"]), ("openBibleWindowContentOnNextTab", config.openBibleWindowContentOnNextTab, self.openBibleWindowContentOnNextTabChanged, False, config.thisTranslation["openBibleWindowContentOnNextTab"]), ("openStudyWindowContentOnNextTab", config.openStudyWindowContentOnNextTab, self.openStudyWindowContentOnNextTabChanged, True, config.thisTranslation["openStudyWindowContentOnNextTab"]), ("populateTabsOnStartup", config.populateTabsOnStartup, self.populateTabsOnStartupChanged, False, config.thisTranslation["populateTabsOnStartup"]), ("qtMaterial", config.qtMaterial, self.qtMaterialChanged, False, config.thisTranslation["qtMaterial"]), ("addBreakAfterTheFirstToolBar", config.addBreakAfterTheFirstToolBar, self.addBreakAfterTheFirstToolBarChanged, True, config.thisTranslation["addBreakAfterTheFirstToolBar"]), ("addBreakBeforeTheLastToolBar", config.addBreakBeforeTheLastToolBar, self.addBreakBeforeTheLastToolBarChanged, False, config.thisTranslation["addBreakBeforeTheLastToolBar"]), ("parserStandarisation", (config.parserStandarisation == "YES"), self.parserStandarisationChanged, False, config.thisTranslation["parserStandarisation"]), ("useLiteVerseParsing", config.useLiteVerseParsing, self.useLiteVerseParsingChanged, False, config.thisTranslation["useLiteVerseParsing"]), ("parseEnglishBooksOnly", config.parseEnglishBooksOnly, self.parseEnglishBooksOnlyChanged, False, config.thisTranslation["parseEnglishBooksOnly"]), ("parseWordDocument", config.parseWordDocument, self.parseWordDocumentChanged, True, config.thisTranslation["parseWordDocument"]), ("convertChapterVerseDotSeparator", config.convertChapterVerseDotSeparator, self.convertChapterVerseDotSeparatorChanged, True, config.thisTranslation["convertChapterVerseDotSeparator"]), ("parseBookChapterWithoutSpace", config.parseBookChapterWithoutSpace, self.parseBookChapterWithoutSpaceChanged, True, config.thisTranslation["parseBookChapterWithoutSpace"]), ("parseBooklessReferences", config.parseBooklessReferences, self.parseBooklessReferencesChanged, True, config.thisTranslation["parseBooklessReferences"]), ("searchBibleIfCommandNotFound", config.searchBibleIfCommandNotFound, self.searchBibleIfCommandNotFoundChanged, True, config.thisTranslation["searchBibleIfCommandNotFound"]), ("regexSearchBibleIfCommandNotFound", config.regexSearchBibleIfCommandNotFound, self.regexSearchBibleIfCommandNotFoundChanged, False, config.thisTranslation["regexSearchBibleIfCommandNotFound"]), ("preferHtmlMenu", config.preferHtmlMenu, self.preferHtmlMenuChanged, False, config.thisTranslation["preferHtmlMenu"]), ("showVerseNumbersInRange", config.showVerseNumbersInRange, self.showVerseNumbersInRangeChanged, True, config.thisTranslation["showVerseNumbersInRange"]), ("addFavouriteToMultiRef", config.addFavouriteToMultiRef, self.addFavouriteToMultiRefChanged, False, config.thisTranslation["addFavouriteToMultiRef"]), ("enableVerseHighlighting", config.enableVerseHighlighting, self.enableVerseHighlightingChanged, True, config.thisTranslation["enableVerseHighlighting"]), ("regexCaseSensitive", config.regexCaseSensitive, self.regexCaseSensitiveChanged, False, config.thisTranslation["regexCaseSensitive"]), ("alwaysDisplayStaticMaps", config.alwaysDisplayStaticMaps, self.alwaysDisplayStaticMapsChanged, False, config.thisTranslation["alwaysDisplayStaticMaps"]), ("exportEmbeddedImages", config.exportEmbeddedImages, self.exportEmbeddedImagesChanged, True, config.thisTranslation["exportEmbeddedImages"]), ("clickToOpenImage", config.clickToOpenImage, self.clickToOpenImageChanged, True, config.thisTranslation["clickToOpenImage"]), ("showNoteIndicatorOnBibleChapter", config.showNoteIndicatorOnBibleChapter, self.parent.enableNoteIndicatorButtonClicked, True, config.thisTranslation["showNoteIndicatorOnBibleChapter"]), ("openBibleNoteAfterSave", config.openBibleNoteAfterSave, self.openBibleNoteAfterSaveChanged, False, config.thisTranslation["openBibleNoteAfterSave"]), ("openBibleNoteAfterEditorClosed", config.openBibleNoteAfterEditorClosed, self.openBibleNoteAfterEditorClosedChanged, False, config.thisTranslation["openBibleNoteAfterEditorClosed"]), ("hideNoteEditorStyleToolbar", config.hideNoteEditorStyleToolbar, self.hideNoteEditorStyleToolbarChanged, False, config.thisTranslation["hideNoteEditorStyleToolbar"]), ("hideNoteEditorTextUtility", config.hideNoteEditorTextUtility, self.hideNoteEditorTextUtilityChanged, True, config.thisTranslation["hideNoteEditorTextUtility"]), ("overwriteNoteFont", config.overwriteNoteFont, self.overwriteNoteFontChanged, True, config.thisTranslation["overwriteNoteFont"]), ("overwriteNoteFontSize", config.overwriteNoteFontSize, self.overwriteNoteFontSizeChanged, True, config.thisTranslation["overwriteNoteFontSize"]), ("overwriteBookFont", config.overwriteBookFont, self.overwriteBookFontChanged, True, config.thisTranslation["overwriteBookFont"]), ("overwriteBookFontSize", config.overwriteBookFontSize, self.overwriteBookFontSizeChanged, True, config.thisTranslation["overwriteBookFontSize"]), ("openBookInNewWindow", config.openBookInNewWindow, self.openBookInNewWindowChanged, False, config.thisTranslation["openBookInNewWindow"]), ("openPdfViewerInNewWindow", config.openPdfViewerInNewWindow, self.openPdfViewerInNewWindowChanged, False, config.thisTranslation["openPdfViewerInNewWindow"]), ("virtualKeyboard", config.virtualKeyboard, self.virtualKeyboardChanged, False, config.thisTranslation["virtualKeyboard"]), ("useWebbrowser", config.useWebbrowser, self.useWebbrowserChanged, True, config.thisTranslation["useWebbrowser"]), ("removeHighlightOnExit", config.removeHighlightOnExit, self.removeHighlightOnExitChanged, False, config.thisTranslation["removeHighlightOnExit"]), ("disableModulesUpdateCheck", config.disableModulesUpdateCheck, self.disableModulesUpdateCheckChanged, True, config.thisTranslation["disableModulesUpdateCheck"]), ("updateWithGitPull", config.updateWithGitPull, self.updateWithGitPullChanged, False, config.thisTranslation["updateWithGitPull"]), ("enableGist", config.enableGist, self.enableGistChanged, False, config.thisTranslation["enableGist"]), ("enableMacros", config.enableMacros, self.enableMacrosChanged, False, config.thisTranslation["enableMacros"]), ("enablePlugins", config.enablePlugins, self.enablePluginsChanged, True, config.thisTranslation["enablePlugins"]), ("hideBlankVerseCompare", config.hideBlankVerseCompare, self.hideBlankVerseCompareChanged, False, config.thisTranslation["hideBlankVerseCompare"]), ("enforceCompareParallel", config.enforceCompareParallel, self.parent.enforceCompareParallelButtonClicked, False, config.thisTranslation["enforceCompareParallel"]), ("enableMenuUnderline", config.enableMenuUnderline, self.enableMenuUnderlineChanged, True, config.thisTranslation["enableMenuUnderline"]), ("openBibleInMainViewOnly", config.openBibleInMainViewOnly, self.parent.enableStudyBibleButtonClicked, False, config.thisTranslation["openBibleInMainViewOnly"]), ("addOHGBiToMorphologySearch", config.addOHGBiToMorphologySearch, self.addOHGBiToMorphologySearchChanged, True, config.thisTranslation["addOHGBiToMorphologySearch"]), ("includeStrictDocTypeInNote", config.includeStrictDocTypeInNote, self.includeStrictDocTypeInNoteChanged, False, config.thisTranslation["includeStrictDocTypeInNote"]), ("parseTextConvertNotesToBook", config.parseTextConvertNotesToBook, self.parseTextConvertNotesToBookChanged, False, config.thisTranslation["parseTextConvertNotesToBook"]), ("parseTextConvertHTMLToBook", config.parseTextConvertHTMLToBook, self.parseTextConvertHTMLToBookChanged, False, config.thisTranslation["parseTextConvertHTMLToBook"]), ("displayCmdOutput", config.displayCmdOutput, self.displayCmdOutputChanged, False, config.thisTranslation["displayCmdOutput"]), ("disableLoadLastOpenFilesOnStartup", config.disableLoadLastOpenFilesOnStartup, self.disableLoadLastOpenFilesOnStartupChanged, False, config.thisTranslation["disableLoadLastOpenFilesOnStartup"]), ("disableOpenPopupWindowOnStartup", config.disableOpenPopupWindowOnStartup, self.disableOpenPopupWindowOnStartupChanged, True, config.thisTranslation["disableOpenPopupWindowOnStartup"]), ("showMiniKeyboardInMiniControl", config.showMiniKeyboardInMiniControl, self.showMiniKeyboardInMiniControlChanged, False, config.thisTranslation["showMiniKeyboardInMiniControl"]), ] if config.isTtsInstalled: options += [ ("useLangDetectOnTts", config.useLangDetectOnTts, self.useLangDetectOnTtsChanged, False, config.thisTranslation["useLangDetectOnTts"]), ("ttsEnglishAlwaysUS", config.ttsEnglishAlwaysUS, self.ttsEnglishAlwaysUSChanged, False, config.thisTranslation["ttsEnglishAlwaysUS"]), ("ttsEnglishAlwaysUK", config.ttsEnglishAlwaysUK, self.ttsEnglishAlwaysUKChanged, False, config.thisTranslation["ttsEnglishAlwaysUK"]), ("ttsChineseAlwaysMandarin", config.ttsChineseAlwaysMandarin, self.ttsChineseAlwaysMandarinChanged, False, config.thisTranslation["ttsChineseAlwaysMandarin"]), ("ttsChineseAlwaysCantonese", config.ttsChineseAlwaysCantonese, self.ttsChineseAlwaysCantoneseChanged, False, config.thisTranslation["ttsChineseAlwaysCantonese"]), ] if platform.system() == "Linux": options += [ ("linuxStartFullScreen", config.linuxStartFullScreen, self.linuxStartFullScreenChanged, False, config.thisTranslation["linuxStartFullScreen"]), ("fcitx", config.fcitx, self.fcitxChanged, False, config.thisTranslation["fcitx"]), ("ibus", config.ibus, self.ibusChanged, False, config.thisTranslation["ibus"]), ("espeak", config.espeak, self.espeakChanged, False, config.thisTranslation["espeak"]), ] if config.developer: options += [ ("forceGenerateHtml", config.forceGenerateHtml, self.forceGenerateHtmlChanged, False, config.thisTranslation["forceGenerateHtml"]), ("enableLogging", config.enableLogging, self.enableLoggingChanged, False, config.thisTranslation["enableLogging"]), ("logCommands", config.logCommands, self.logCommandsChanged, False, config.thisTranslation["logCommands"]), ] data = {} for flag, configValue, action, default, tooltip in options: data[flag] = [configValue, default, tooltip, action] return data def restoreAllDefaults(self): for key, value in self.data.items(): code = "config.{0} = {1}".format(key, value[1]) exec(code) self.resetItems() self.displayMessage(config.thisTranslation["message_restart"]) def itemChanged(self, standardItem): flag = standardItem.text() if flag in self.data and not self.isUpdating: self.data[flag][-1]() def resetItems(self): self.isUpdating = True # Empty the model before reset self.dataViewModel.clear() # Reset self.data = self.getOptions() filterEntry = self.filterEntry.text().lower() rowCount = 0 for flag, value in self.data.items(): configValue, default, tooltip, *_ = value if filterEntry == "" or (filterEntry != "" and (filterEntry in flag.lower() or filterEntry in tooltip.lower())): # 1st column item = QStandardItem(flag) item.setToolTip(tooltip) item.setCheckable(True) item.setCheckState(Qt.CheckState.Checked if configValue else Qt.CheckState.Unchecked) self.dataViewModel.setItem(rowCount, 0, item) # 2nd column item = QStandardItem(str(default)) self.dataViewModel.setItem(rowCount, 1, item) # 3rd column tooltip = tooltip.replace("\n", " ") item = QStandardItem(tooltip) item.setToolTip(tooltip) self.dataViewModel.setItem(rowCount, 2, item) # add row count rowCount += 1 self.dataViewModel.setHorizontalHeaderLabels([ config.thisTranslation["flag"], config.thisTranslation["default"], config.thisTranslation["description"] ]) self.dataView.resizeColumnsToContents() self.isUpdating = False def displayMessage(self, message="", title="UniqueBible"): QMessageBox.information(self, title, message) def openWiki(self, event): wikiLink = "https://github.com/eliranwong/UniqueBible/wiki/Config-file-reference" webbrowser.open(wikiLink) def ibusChanged(self): config.ibus = not config.ibus if config.fcitx and config.ibus: config.fcitx = not config.fcitx if config.virtualKeyboard and config.ibus: config.virtualKeyboard = not config.virtualKeyboard self.displayMessage(config.thisTranslation["message_restart"]) def fcitxChanged(self): config.fcitx = not config.fcitx if config.fcitx and config.ibus: config.ibus = not config.ibus if config.fcitx and config.virtualKeyboard: config.virtualKeyboard = not config.virtualKeyboard self.displayMessage(config.thisTranslation["message_restart"]) def virtualKeyboardChanged(self): config.virtualKeyboard = not config.virtualKeyboard if config.fcitx and config.virtualKeyboard: config.fcitx = not config.fcitx if config.virtualKeyboard and config.ibus: config.ibus = not config.ibus self.displayMessage(config.thisTranslation["message_restart"]) def parseWordDocumentChanged(self): config.parseWordDocument = not config.parseWordDocument def useLangDetectOnTtsChanged(self): config.useLangDetectOnTts = not config.useLangDetectOnTts def ttsEnglishAlwaysUSChanged(self): config.ttsEnglishAlwaysUS = not config.ttsEnglishAlwaysUS if config.ttsEnglishAlwaysUK and config.ttsEnglishAlwaysUS: config.ttsEnglishAlwaysUK = not config.ttsEnglishAlwaysUK def ttsEnglishAlwaysUKChanged(self): config.ttsEnglishAlwaysUK = not config.ttsEnglishAlwaysUK if config.ttsEnglishAlwaysUK and config.ttsEnglishAlwaysUS: config.ttsEnglishAlwaysUS = not config.ttsEnglishAlwaysUS def ttsChineseAlwaysMandarinChanged(self): config.ttsChineseAlwaysMandarin = not config.ttsChineseAlwaysMandarin if config.ttsChineseAlwaysMandarin and config.ttsChineseAlwaysCantonese: config.ttsChineseAlwaysCantonese = not config.ttsChineseAlwaysCantonese def ttsChineseAlwaysCantoneseChanged(self): config.ttsChineseAlwaysCantonese = not config.ttsChineseAlwaysCantonese if config.ttsChineseAlwaysMandarin and config.ttsChineseAlwaysCantonese: config.ttsChineseAlwaysMandarin = not config.ttsChineseAlwaysMandarin def showVerseNumbersInRangeChanged(self): config.showVerseNumbersInRange = not config.showVerseNumbersInRange #def customPythonOnStartupChanged(self): # config.customPythonOnStartup = not config.customPythonOnStartup def openBibleWindowContentOnNextTabChanged(self): config.openBibleWindowContentOnNextTab = not config.openBibleWindowContentOnNextTab self.newTabException = False def showControlPanelOnStartupChanged(self): config.showControlPanelOnStartup = not config.showControlPanelOnStartup self.displayMessage(config.thisTranslation["message_restart"]) def preferControlPanelForCommandLineEntryChanged(self): config.preferControlPanelForCommandLineEntry = not config.preferControlPanelForCommandLineEntry self.displayMessage(config.thisTranslation["message_restart"]) def closeControlPanelAfterRunningCommandChanged(self): config.closeControlPanelAfterRunningCommand = not config.closeControlPanelAfterRunningCommand def restrictControlPanelWidthChanged(self): config.restrictControlPanelWidth = not config.restrictControlPanelWidth self.parent.reloadControlPanel(False) def regexCaseSensitiveChanged(self): config.regexCaseSensitive = not config.regexCaseSensitive def openStudyWindowContentOnNextTabChanged(self): config.openStudyWindowContentOnNextTab = not config.openStudyWindowContentOnNextTab self.newTabException = False def addFavouriteToMultiRefChanged(self): config.addFavouriteToMultiRef = not config.addFavouriteToMultiRef def addOHGBiToMorphologySearchChanged(self): config.addOHGBiToMorphologySearch = not config.addOHGBiToMorphologySearch def exportEmbeddedImagesChanged(self): config.exportEmbeddedImages = not config.exportEmbeddedImages def clickToOpenImageChanged(self): config.clickToOpenImage = not config.clickToOpenImage def openBibleNoteAfterEditorClosedChanged(self): config.openBibleNoteAfterEditorClosed = not config.openBibleNoteAfterEditorClosed def preferHtmlMenuChanged(self): config.preferHtmlMenu = not config.preferHtmlMenu def hideNoteEditorStyleToolbarChanged(self): config.hideNoteEditorStyleToolbar = not config.hideNoteEditorStyleToolbar def hideNoteEditorTextUtilityChanged(self): config.hideNoteEditorTextUtility = not config.hideNoteEditorTextUtility def populateTabsOnStartupChanged(self): config.populateTabsOnStartup = not config.populateTabsOnStartup def openBookInNewWindowChanged(self): config.openBookInNewWindow = not config.openBookInNewWindow def convertChapterVerseDotSeparatorChanged(self): config.convertChapterVerseDotSeparator = not config.convertChapterVerseDotSeparator def updateWithGitPullChanged(self): config.updateWithGitPull = not config.updateWithGitPull if config.updateWithGitPull and not os.path.isdir(".git"): config.updateWithGitPull = False def parseBookChapterWithoutSpaceChanged(self): config.parseBookChapterWithoutSpace = not config.parseBookChapterWithoutSpace def parseBooklessReferencesChanged(self): config.parseBooklessReferences = not config.parseBooklessReferences def openPdfViewerInNewWindowChanged(self): config.openPdfViewerInNewWindow = not config.openPdfViewerInNewWindow def searchBibleIfCommandNotFoundChanged(self): config.searchBibleIfCommandNotFound = not config.searchBibleIfCommandNotFound def regexSearchBibleIfCommandNotFoundChanged(self): config.regexSearchBibleIfCommandNotFound = not config.regexSearchBibleIfCommandNotFound if config.regexSearchBibleIfCommandNotFound and not config.searchBibleIfCommandNotFound: config.searchBibleIfCommandNotFound = True def overwriteNoteFontChanged(self): config.overwriteNoteFont = not config.overwriteNoteFont def overwriteNoteFontSizeChanged(self): config.overwriteNoteFontSize = not config.overwriteNoteFontSize def overwriteBookFontChanged(self): config.overwriteBookFont = not config.overwriteBookFont def useWebbrowserChanged(self): config.useWebbrowser = not config.useWebbrowser def removeHighlightOnExitChanged(self): config.removeHighlightOnExit = not config.removeHighlightOnExit def overwriteBookFontSizeChanged(self): config.overwriteBookFontSize = not config.overwriteBookFontSize def alwaysDisplayStaticMapsChanged(self): config.alwaysDisplayStaticMaps = not config.alwaysDisplayStaticMaps def openBibleNoteAfterSaveChanged(self): config.openBibleNoteAfterSave = not config.openBibleNoteAfterSave def addBreakAfterTheFirstToolBarChanged(self): config.addBreakAfterTheFirstToolBar = not config.addBreakAfterTheFirstToolBar self.displayMessage(config.thisTranslation["message_restart"]) def addBreakBeforeTheLastToolBarChanged(self): config.addBreakBeforeTheLastToolBar = not config.addBreakBeforeTheLastToolBar self.displayMessage(config.thisTranslation["message_restart"]) def disableModulesUpdateCheckChanged(self): config.disableModulesUpdateCheck = not config.disableModulesUpdateCheck def forceGenerateHtmlChanged(self): config.forceGenerateHtml = not config.forceGenerateHtml def parserStandarisationChanged(self): if config.parserStandarisation == "YES": config.parserStandarisation = "NO" else: config.parserStandarisation = "YES" def linuxStartFullScreenChanged(self): config.linuxStartFullScreen = not config.linuxStartFullScreen self.displayMessage(config.thisTranslation["message_restart"]) def espeakChanged(self): config.espeak = not config.espeak self.displayMessage(config.thisTranslation["message_restart"]) def enableLoggingChanged(self): config.enableLogging = not config.enableLogging self.displayMessage(config.thisTranslation["message_restart"]) def logCommandsChanged(self): config.logCommands = not config.logCommands def enableVerseHighlightingChanged(self): config.enableVerseHighlighting = not config.enableVerseHighlighting self.displayMessage(config.thisTranslation["message_restart"]) def useLiteVerseParsingChanged(self): config.useLiteVerseParsing = not config.useLiteVerseParsing def parseEnglishBooksOnlyChanged(self): config.parseEnglishBooksOnly = not config.parseEnglishBooksOnly def enableMacrosChanged(self): config.enableMacros = not config.enableMacros self.displayMessage(config.thisTranslation["message_restart"]) def enablePluginsChanged(self): config.enablePlugins = not config.enablePlugins self.parent.setMenuLayout(config.menuLayout) def clearCommandEntryChanged(self): config.clearCommandEntry = not config.clearCommandEntry def qtMaterialChanged(self): if not config.qtMaterial: self.parent.enableQtMaterial(True) else: self.parent.enableQtMaterial(False) def enableGistChanged(self): if not config.enableGist and config.isPygithubInstalled: config.enableGist = True self.displayMessage(config.thisTranslation["message_restart"]) elif config.enableGist: config.enableGist = not config.enableGist self.displayMessage(config.thisTranslation["message_restart"]) else: self.displayMessage(config.thisTranslation["message_noSupport"]) def hideBlankVerseCompareChanged(self): config.hideBlankVerseCompare = not config.hideBlankVerseCompare def enableMenuUnderlineChanged(self): config.enableMenuUnderline = not config.enableMenuUnderline if config.enableMenuUnderline: config.menuUnderline = "&" else: config.menuUnderline = "" self.parent.setMenuLayout(config.menuLayout) def includeStrictDocTypeInNoteChanged(self): config.includeStrictDocTypeInNote = not config.includeStrictDocTypeInNote def parseTextConvertNotesToBookChanged(self): config.parseTextConvertNotesToBook = not config.parseTextConvertNotesToBook def parseTextConvertHTMLToBookChanged(self): config.parseTextConvertHTMLToBook = not config.parseTextConvertHTMLToBook def displayCmdOutputChanged(self): config.displayCmdOutput = not config.displayCmdOutput def disableLoadLastOpenFilesOnStartupChanged(self): config.disableLoadLastOpenFilesOnStartup = not config.disableLoadLastOpenFilesOnStartup def disableOpenPopupWindowOnStartupChanged(self): config.disableOpenPopupWindowOnStartup = not config.disableOpenPopupWindowOnStartup def showMiniKeyboardInMiniControlChanged(self): config.showMiniKeyboardInMiniControl = not config.showMiniKeyboardInMiniControl
class SpecimenPositionListWidget(ParameterWidget): class _SpecimenPositionModel(QAbstractTableModel): def __init__(self): QAbstractTableModel.__init__(self) self.positions = [] def rowCount(self, *args, **kwargs): return len(self.positions) def columnCount(self, *args, **kwargs): return 5 def data(self, index, role): if not index.isValid() or not (0 <= index.row() < len(self.positions)): return None if role != Qt.DisplayRole: return None position = self.positions[index.row()] column = index.column() if column == 0: return str(position.x) if position.x is not None else '' elif column == 1: return str(position.y) if position.y is not None else '' elif column == 2: return str(position.z) if position.z is not None else '' elif column == 3: return str(position.r) if position.r is not None else '' elif column == 4: return str(position.t) if position.t is not None else '' def headerData(self, section , orientation, role): if role != Qt.DisplayRole: return None if orientation == Qt.Horizontal: if section == 0: return 'X' elif section == 1: return 'Y' elif section == 2: return 'Z' elif section == 3: return 'R' elif section == 4: return 'T' elif orientation == Qt.Vertical: return str(section + 1) def flags(self, index): if not index.isValid(): return Qt.ItemIsEnabled return Qt.ItemFlags(QAbstractTableModel.flags(self, index) | Qt.ItemIsEditable) def setData(self, index, value, role=Qt.EditRole): if not index.isValid() or \ not (0 <= index.row() < len(self.positions)): return False position = self.positions[index.row()] column = index.column() if column == 0: position.x = value elif column == 1: position.y = value elif column == 2: position.z = value elif column == 3: position.r = value elif column == 4: position.t = value return True def insertRows(self, row, count=1, parent=None): if count == 0: return False if parent is None: parent = QModelIndex() self.beginInsertRows(parent, row, row + count - 1) for i in range(count): self.positions.insert(row + i, SpecimenPosition()) self.endInsertRows() return True def removeRows(self, row, count=1, parent=None): if count == 0: return False if parent is None: parent = QModelIndex() self.beginRemoveRows(parent, row, row + count - 1) self.positions = self.positions[:row] + self.positions[row + count:] self.endRemoveRows() return True class _SpecimenPositionDelegate(QItemDelegate): def __init__(self, parent=None): QItemDelegate.__init__(self, parent) def createEditor(self, parent, option, index): column = index.column() if column == 0: return NumericalAttributeLineEdit(SpecimenPosition.x, parent) elif column == 1: return NumericalAttributeLineEdit(SpecimenPosition.y, parent) elif column == 2: return NumericalAttributeLineEdit(SpecimenPosition.y, parent) elif column == 3: return NumericalAttributeLineEdit(SpecimenPosition.y, parent) elif column == 4: return NumericalAttributeLineEdit(SpecimenPosition.y, parent) else: return QItemDelegate.createEditor(self, parent, option, index) def setEditorData(self, editor, index): text = index.model().data(index, Qt.DisplayRole) column = index.column() if column == 0: editor.setText(text) elif column == 1: editor.setText(text) elif column == 2: editor.setText(text) elif column == 3: editor.setText(text) elif column == 4: editor.setText(text) else: QItemDelegate.setEditorData(self, editor, index) def setModelData(self, editor, model, index): column = index.column() if column == 0: model.setData(index, editor.text()) elif column == 1: model.setData(index, editor.text()) elif column == 2: model.setData(index, editor.text()) elif column == 3: model.setData(index, editor.text()) elif column == 4: model.setData(index, editor.text()) else: return QItemDelegate.setModelData(self, editor, model, index) def __init__(self, parent=None): ParameterWidget.__init__(self, object, parent) def _init_ui(self): # Widgets self._table = QTableView() self._table.setModel(self._SpecimenPositionModel()) self._table.setItemDelegate(self._SpecimenPositionDelegate(self)) self._table.horizontalHeader().setStretchLastSection(True) self._toolbar = QToolBar() action_add = self._toolbar.addAction(getIcon("list-add"), "Add layer") action_remove = self._toolbar.addAction(getIcon("list-remove"), "Remove layer") # Layouts layout = ParameterWidget._init_ui(self) layout.addRow(self._table) layout.addRow(self._toolbar) # Signals action_add.triggered.connect(self._on_add) action_remove.triggered.connect(self._on_remove) return layout def _on_add(self): index = self._table.selectionModel().currentIndex() model = self._table.model() model.insertRows(index.row() + 1) def _on_remove(self): selection = self._table.selectionModel().selection().indexes() if len(selection) == 0: QMessageBox.warning(self, "Specimen position", "Select a position") return model = self._table.model() for row in sorted(map(methodcaller('row'), selection), reverse=True): model.removeRow(row) def parameter(self): positions = [] for position in self._table.model().positions: positions.append(SpecimenPosition(position.x, position.y, position.z, position.r, position.t)) return positions def setParameter(self, positions): model = self._table.model() model.positions = positions model.reset() def positions(self): return self.parameter() def setPositions(self, positions): self.setParameter(positions) def setReadOnly(self, state): ParameterWidget.setReadOnly(self, state) if state: trigger = QTableView.EditTrigger.NoEditTriggers else: trigger = QTableView.EditTrigger.AllEditTriggers self._table.setEditTriggers(trigger) self._toolbar.setEnabled(not state) def isReadOnly(self): return ParameterWidget.isReadOnly(self) and \ self._table.editTriggers() == QTableView.EditTrigger.NoEditTriggers and \ not self._toolbar.isEnabled()
class SampleLogsView(QSplitter): """Sample Logs View This contains a table of the logs, a plot of the currently selected logs, and the statistics of the selected log. """ def __init__(self, presenter, parent = None, name = '', isMD=False, noExp = 0): super(SampleLogsView, self).__init__(parent) self.presenter = presenter self.setWindowTitle("{} sample logs".format(name)) self.setWindowFlags(Qt.Window) # Create sample log table self.table = QTableView() self.table.setSelectionBehavior(QAbstractItemView.SelectRows) self.table.clicked.connect(self.presenter.clicked) self.table.doubleClicked.connect(self.presenter.doubleClicked) self.table.contextMenuEvent = self.tableMenu self.addWidget(self.table) frame_right = QFrame() layout_right = QVBoxLayout() #Add full_time and experimentinfo options layout_options = QHBoxLayout() if isMD: layout_options.addWidget(QLabel("Experiment Info #")) self.experimentInfo = QSpinBox() self.experimentInfo.setMaximum(noExp-1) self.experimentInfo.valueChanged.connect(self.presenter.changeExpInfo) layout_options.addWidget(self.experimentInfo) self.full_time = QCheckBox("Relative Time") self.full_time.setChecked(True) self.full_time.stateChanged.connect(self.presenter.plot_logs) layout_options.addWidget(self.full_time) layout_right.addLayout(layout_options) # Sample log plot self.fig = Figure() self.canvas = FigureCanvas(self.fig) self.canvas.setSizePolicy(QSizePolicy.Expanding,QSizePolicy.Expanding) self.canvas.mpl_connect('button_press_event', self.presenter.plot_clicked) self.ax = self.fig.add_subplot(111, projection='mantid') layout_right.addWidget(self.canvas) # Sample stats self.create_stats_widgets() layout_stats = QFormLayout() layout_stats.addRow('', QLabel("Log Statistics")) layout_stats.addRow('Min:', self.stats_widgets["minimum"]) layout_stats.addRow('Max:', self.stats_widgets["maximum"]) layout_stats.addRow('Mean:', self.stats_widgets["mean"]) layout_stats.addRow('Median:', self.stats_widgets["median"]) layout_stats.addRow('Std Dev:', self.stats_widgets["standard_deviation"]) layout_stats.addRow('Time Avg:', self.stats_widgets["time_mean"]) layout_stats.addRow('Time Std Dev:', self.stats_widgets["time_standard_deviation"]) layout_stats.addRow('Duration:', self.stats_widgets["duration"]) layout_right.addLayout(layout_stats) frame_right.setLayout(layout_right) self.addWidget(frame_right) self.setStretchFactor(0,1) self.resize(1200,800) self.show() def tableMenu(self, event): """Right click menu for table, can plot or print selected logs""" menu = QMenu(self) plotAction = menu.addAction("Plot selected") plotAction.triggered.connect(self.presenter.new_plot_logs) plotAction = menu.addAction("Print selected") plotAction.triggered.connect(self.presenter.print_selected_logs) menu.exec_(event.globalPos()) def set_model(self, model): """Set the model onto the table""" self.model = model self.table.setModel(self.model) self.table.resizeColumnsToContents() self.table.horizontalHeader().setSectionResizeMode(2, QHeaderView.Stretch) def plot_selected_logs(self, ws, exp, rows): """Update the plot with the selected rows""" self.ax.clear() self.create_ax_by_rows(self.ax, ws, exp, rows) self.fig.canvas.draw() def new_plot_selected_logs(self, ws, exp, rows): """Create a new plot, in a separate window for selected rows""" fig, ax = plt.subplots(subplot_kw={'projection': 'mantid'}) self.create_ax_by_rows(ax, ws, exp, rows) fig.show() def create_ax_by_rows(self, ax, ws, exp, rows): """Creates the plots for given rows onto axis ax""" for row in rows: log_text = self.get_row_log_name(row) ax.plot(ws, LogName=log_text, label=log_text, marker='.', FullTime=not self.full_time.isChecked(), ExperimentInfo=exp) ax.set_ylabel('') if ax.get_legend_handles_labels()[0]: ax.legend() def get_row_log_name(self, i): """Returns the log name of particular row""" return str(self.model.item(i, 0).text()) def get_exp(self): """Get set experiment info number""" return self.experimentInfo.value() def get_selected_row_indexes(self): """Return a list of selected row from table""" return [row.row() for row in self.table.selectionModel().selectedRows()] def set_selected_rows(self, rows): """Set seleceted rows in table""" mode = QItemSelectionModel.Select | QItemSelectionModel.Rows for row in rows: self.table.selectionModel().select(self.model.index(row, 0), mode) def create_stats_widgets(self): """Creates the statistics widgets""" self.stats_widgets = {"minimum": QLineEdit(), "maximum": QLineEdit(), "mean": QLineEdit(), "median": QLineEdit(), "standard_deviation": QLineEdit(), "time_mean": QLineEdit(), "time_standard_deviation": QLineEdit(), "duration": QLineEdit()} for widget in self.stats_widgets.values(): widget.setReadOnly(True) def set_statistics(self, stats): """Updates the statistics widgets from stats dictionary""" for param in self.stats_widgets.keys(): self.stats_widgets[param].setText('{:.6}'.format(getattr(stats, param))) def clear_statistics(self): """Clears the values in statistics widgets""" for widget in self.stats_widgets.values(): widget.clear()
def __init__(self, plotted_lines, *args, **kwargs): super().__init__(None, *args, **kwargs) self.plotted_lines = plotted_lines layout = QVBoxLayout() layout.setSizeConstraint(QLayout.SetMaximumSize) self.setLayout(layout) table_model = LineListTableModel(plotted_lines) if table_model.rowCount() > 0: table_view = QTableView() # disabling sorting will significantly speed up the # plot. This is because the table view must be re-built # every time a new set of markers is drawn on the plot # surface. Alternate approaches are worth examining. It # remains to be seen what would be the approach users # will favor. table_view.setSortingEnabled(False) proxy = SortModel(table_model.getName()) proxy.setSourceModel(table_model) table_view.setModel(proxy) table_view.setSortingEnabled(True) table_view.setSelectionMode(QAbstractItemView.NoSelection) table_view.horizontalHeader().setStretchLastSection(True) table_view.resizeColumnsToContents() layout.addWidget(table_view)
def _createLineListPane(linelist, table_model, caller): table_view = QTableView() # disabling sorting will significantly speed up the rendering, # in particular of large line lists. These lists are often jumbled # in wavelength, and consequently difficult to read and use, so # having a sorting option is useful indeed. It remains to be seen # what would be the approach users will favor. We might add a toggle # that users can set/reset depending on their preferences. table_view.setSortingEnabled(False) sort_proxy = SortModel(table_model.getName()) sort_proxy.setSourceModel(table_model) table_view.setModel(sort_proxy) table_view.setSortingEnabled(True) table_view.horizontalHeader().setStretchLastSection(True) # playing with these doesn't speed up the sorting, regardless of whatever # you may read on the net. # # table_view.horizontalHeader().setResizeMode(QHeaderView.Fixed) # table_view.verticalHeader().setResizeMode(QHeaderView.Fixed) # table_view.horizontalHeader().setStretchLastSection(False) # table_view.verticalHeader().setStretchLastSection(False) table_view.setSelectionMode(QAbstractItemView.ExtendedSelection) table_view.setSelectionBehavior(QAbstractItemView.SelectRows) table_view.resizeColumnsToContents() # this preserves the original sorting state of the list. Use zero # to sort by wavelength on load. Doesn't seem to affect performance # by much tough. sort_proxy.sort(-1, Qt.AscendingOrder) # table selections will change the total count of lines selected. pane = LineListPane(table_view, linelist, sort_proxy, caller) return pane, table_view
def keyPressEvent(self, event): """Reimplement Qt method""" if event == QKeySequence.Copy: self.copy() else: QTableView.keyPressEvent(self, event)
elif section == 4: return "Нулевой уровень" elif section == 5: return "Интервал варьирования" def rowCount(self, *args, **kwargs): return len(self._factors) def add_factor(self, factor): rows = self.rowCount() position = rows - 1 if self.rowCount() > 0 else rows self.beginInsertRows(QModelIndex(), position, position) self._factors.append(factor) self.endInsertRows() if __name__ == '__main__': import sys from qtpy.QtWidgets import QApplication, QTableView, QHeaderView factors = [Factor("die", 1, 2, 3432, 4)] app = QApplication([]) model = FactorsTableModel() tv = QTableView() tv.setModel(model) for f in factors: model.add_factor(f) tv.horizontalHeader().setSectionResizeMode(QHeaderView.ResizeToContents) tv.show() sys.exit(app.exec_())
def __init__(self, presenter, parent = None, name = '', isMD=False, noExp = 0): super(SampleLogsView, self).__init__(parent) self.presenter = presenter self.setWindowTitle("{} sample logs".format(name)) self.setWindowFlags(Qt.Window) # Create sample log table self.table = QTableView() self.table.setSelectionBehavior(QAbstractItemView.SelectRows) self.table.clicked.connect(self.presenter.clicked) self.table.doubleClicked.connect(self.presenter.doubleClicked) self.table.contextMenuEvent = self.tableMenu self.addWidget(self.table) frame_right = QFrame() layout_right = QVBoxLayout() #Add full_time and experimentinfo options layout_options = QHBoxLayout() if isMD: layout_options.addWidget(QLabel("Experiment Info #")) self.experimentInfo = QSpinBox() self.experimentInfo.setMaximum(noExp-1) self.experimentInfo.valueChanged.connect(self.presenter.changeExpInfo) layout_options.addWidget(self.experimentInfo) self.full_time = QCheckBox("Relative Time") self.full_time.setChecked(True) self.full_time.stateChanged.connect(self.presenter.plot_logs) layout_options.addWidget(self.full_time) layout_right.addLayout(layout_options) # Sample log plot self.fig = Figure() self.canvas = FigureCanvas(self.fig) self.canvas.setSizePolicy(QSizePolicy.Expanding,QSizePolicy.Expanding) self.canvas.mpl_connect('button_press_event', self.presenter.plot_clicked) self.ax = self.fig.add_subplot(111, projection='mantid') layout_right.addWidget(self.canvas) # Sample stats self.create_stats_widgets() layout_stats = QFormLayout() layout_stats.addRow('', QLabel("Log Statistics")) layout_stats.addRow('Min:', self.stats_widgets["minimum"]) layout_stats.addRow('Max:', self.stats_widgets["maximum"]) layout_stats.addRow('Mean:', self.stats_widgets["mean"]) layout_stats.addRow('Median:', self.stats_widgets["median"]) layout_stats.addRow('Std Dev:', self.stats_widgets["standard_deviation"]) layout_stats.addRow('Time Avg:', self.stats_widgets["time_mean"]) layout_stats.addRow('Time Std Dev:', self.stats_widgets["time_standard_deviation"]) layout_stats.addRow('Duration:', self.stats_widgets["duration"]) layout_right.addLayout(layout_stats) frame_right.setLayout(layout_right) self.addWidget(frame_right) self.setStretchFactor(0,1) self.resize(1200,800) self.show()
def setupUI(self): mainLayout = QVBoxLayout() filterLayout = QHBoxLayout() filterLayout.addWidget(QLabel(config.thisTranslation["menu5_search"])) self.filterEntry = QLineEdit() self.filterEntry.setClearButtonEnabled(True) self.filterEntry.textChanged.connect(self.resetItems) filterLayout.addWidget(self.filterEntry) mainLayout.addLayout(filterLayout) self.searchTypeBox = QGroupBox("") locationLayout = QHBoxLayout() self.localRadioButton = QRadioButton("Local") self.localRadioButton.setChecked(True) self.localRadioButton.toggled.connect( lambda: self.setLocation("local")) locationLayout.addWidget(self.localRadioButton) self.remoteRadioButton = QRadioButton("Remote") self.remoteRadioButton.toggled.connect( lambda: self.setLocation("remote")) locationLayout.addWidget(self.remoteRadioButton) self.searchTypeBox.setLayout(locationLayout) mainLayout.addWidget(self.searchTypeBox) typesLayout = QHBoxLayout() button = QPushButton("All") button.setStyleSheet(self.textButtonStyle) button.clicked.connect(lambda: self.selectAllTypes(True)) typesLayout.addWidget(button) button = QPushButton("None") button.setStyleSheet(self.textButtonStyle) button.clicked.connect(lambda: self.selectAllTypes(False)) typesLayout.addWidget(button) self.bookCheckbox = QCheckBox("BOOK") self.bookCheckbox.setChecked(True) self.bookCheckbox.stateChanged.connect(self.resetItems) typesLayout.addWidget(self.bookCheckbox) self.pdfCheckbox = QCheckBox("PDF") self.pdfCheckbox.setChecked(True) self.pdfCheckbox.stateChanged.connect(self.resetItems) typesLayout.addWidget(self.pdfCheckbox) self.docxCheckbox = QCheckBox("DOCX") self.docxCheckbox.setChecked(True) self.docxCheckbox.stateChanged.connect(self.resetItems) typesLayout.addWidget(self.docxCheckbox) self.devotionalCheckbox = QCheckBox("DEVOTIONAL") self.devotionalCheckbox.setChecked(True) self.devotionalCheckbox.stateChanged.connect(self.resetItems) typesLayout.addWidget(self.devotionalCheckbox) self.commCheckbox = QCheckBox("COMM") self.commCheckbox.setChecked(True) self.commCheckbox.stateChanged.connect(self.resetItems) typesLayout.addWidget(self.commCheckbox) self.mp3Checkbox = QCheckBox("MP3") self.mp3Checkbox.setChecked(True) self.mp3Checkbox.stateChanged.connect(self.resetItems) typesLayout.addWidget(self.mp3Checkbox) self.mp4Checkbox = QCheckBox("MP4") self.mp4Checkbox.setChecked(True) self.mp4Checkbox.stateChanged.connect(self.resetItems) typesLayout.addWidget(self.mp4Checkbox) mainLayout.addLayout(typesLayout) self.dataView = QTableView() self.dataView.clicked.connect(self.itemClicked) self.dataView.setEditTriggers(QAbstractItemView.NoEditTriggers) self.dataView.setSortingEnabled(True) self.dataViewModel = QStandardItemModel(self.dataView) self.dataView.setModel(self.dataViewModel) self.resetItems() mainLayout.addWidget(self.dataView) buttonLayout = QHBoxLayout() self.openButton = QPushButton(config.thisTranslation["open"]) self.openButton.setEnabled(True) self.openButton.setStyleSheet(self.textButtonStyle) self.openButton.clicked.connect(self.open) buttonLayout.addWidget(self.openButton) self.downloadButton = QPushButton(config.thisTranslation["download"]) self.downloadButton.setEnabled(False) self.downloadButton.clicked.connect(self.download) buttonLayout.addWidget(self.downloadButton) button = QPushButton(config.thisTranslation["close"]) button.setStyleSheet(self.textButtonStyle) button.clicked.connect(self.close) buttonLayout.addWidget(button) mainLayout.addLayout(buttonLayout) self.setLayout(mainLayout)
class BasePlotCurveEditorDialog(QDialog): """QDialog that is used in Qt Designer to edit the properties of the curves in a waveform plot. This dialog is shown when you double-click the plot, or when you right click it and choose 'edit curves'. This thing is mostly just a wrapper for a table view, with a couple buttons to add and remove curves, and a button to save the changes.""" TABLE_MODEL_CLASS = BasePlotCurvesModel def __init__(self, plot, parent=None): super(BasePlotCurveEditorDialog, self).__init__(parent) self.plot = plot self.setup_ui() self.table_model = self.TABLE_MODEL_CLASS(self.plot) self.table_view.setModel(self.table_model) self.table_model.plot = plot # self.table_view.resizeColumnsToContents() self.add_button.clicked.connect(self.addCurve) self.remove_button.clicked.connect(self.removeSelectedCurve) self.remove_button.setEnabled(False) self.table_view.selectionModel().selectionChanged.connect( self.handleSelectionChange) self.table_view.doubleClicked.connect(self.handleDoubleClick) self.resize(800, 300) def setup_ui(self): self.vertical_layout = QVBoxLayout(self) self.table_view = QTableView(self) self.table_view.setEditTriggers(QAbstractItemView.DoubleClicked) self.table_view.setProperty("showDropIndicator", False) self.table_view.setDragDropOverwriteMode(False) self.table_view.setSelectionMode(QAbstractItemView.SingleSelection) self.table_view.setSelectionBehavior(QAbstractItemView.SelectRows) self.table_view.setSortingEnabled(False) self.table_view.horizontalHeader().setStretchLastSection(True) self.table_view.verticalHeader().setVisible(False) self.table_view.setColumnWidth(0, 160) self.table_view.setColumnWidth(1, 160) self.table_view.setColumnWidth(2, 160) self.vertical_layout.addWidget(self.table_view) self.add_remove_layout = QHBoxLayout() spacer = QSpacerItem(40, 20, QSizePolicy.Expanding, QSizePolicy.Minimum) self.add_remove_layout.addItem(spacer) self.add_button = QPushButton("Add Curve", self) self.add_remove_layout.addWidget(self.add_button) self.remove_button = QPushButton("Remove Curve", self) self.add_remove_layout.addWidget(self.remove_button) self.vertical_layout.addLayout(self.add_remove_layout) self.button_box = QDialogButtonBox(self) self.button_box.setOrientation(Qt.Horizontal) self.button_box.addButton("Done", QDialogButtonBox.AcceptRole) self.vertical_layout.addWidget(self.button_box) self.button_box.accepted.connect(self.saveChanges) self.button_box.rejected.connect(self.reject) self.setWindowTitle("Waveform Curve Editor") def setup_delegate_columns(self, index=2): symbol_delegate = SymbolColumnDelegate(self) self.table_view.setItemDelegateForColumn(index+3, symbol_delegate) line_delegate = LineColumnDelegate(self) self.table_view.setItemDelegateForColumn(index+1, line_delegate) color_delegate = ColorColumnDelegate(self) self.table_view.setItemDelegateForColumn(index, color_delegate) @Slot() def addCurve(self): self.table_model.append() @Slot() def removeSelectedCurve(self): self.table_model.removeAtIndex(self.table_view.currentIndex()) @Slot(QItemSelection, QItemSelection) def handleSelectionChange(self, selected, deselected): self.remove_button.setEnabled( self.table_view.selectionModel().hasSelection()) @Slot(QModelIndex) def handleDoubleClick(self, index): if self.table_model.needsColorDialog(index): # The table model returns a QBrush for BackgroundRole, not a QColor init_color = self.table_model.data(index, Qt.BackgroundRole).color() color = QColorDialog.getColor(init_color, self) if color.isValid(): self.table_model.setData(index, color, role=Qt.EditRole) @Slot() def saveChanges(self): formWindow = QDesignerFormWindowInterface.findFormWindow(self.plot) if formWindow: formWindow.cursor().setProperty("curves", self.plot.curves) self.accept()
def keyReleaseEvent(self, event): """Override Qt method""" QTableView.keyReleaseEvent(self, event) if event.key() in [Qt.Key_Enter, Qt.Key_Return] and self.pressed_here: self.action_released() self.pressed_here = False