def __setupUi(self): layout = QVBoxLayout() # Scene with the link editor. self.scene = LinksEditScene() self.view = QGraphicsView(self.scene) self.view.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff) self.view.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff) self.view.setRenderHint(QPainter.Antialiasing) self.scene.editWidget.geometryChanged.connect(self.__onGeometryChanged) # Ok/Cancel/Clear All buttons. buttons = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel | QDialogButtonBox.Reset, Qt.Horizontal) clear_button = buttons.button(QDialogButtonBox.Reset) clear_button.setText(self.tr("Clear All")) buttons.accepted.connect(self.accept) buttons.rejected.connect(self.reject) clear_button.clicked.connect(self.scene.editWidget.clearLinks) layout.addWidget(self.view) layout.addWidget(buttons) self.setLayout(layout) layout.setSizeConstraint(QVBoxLayout.SetFixedSize) self.setSizeGripEnabled(False)
def __setupUi(self): layout = QVBoxLayout() label = QLabel(self) pixmap, _ = config.splash_screen() label.setPixmap(pixmap) layout.addWidget(label, Qt.AlignCenter) name = QApplication.applicationName() version = QApplication.applicationVersion() text = ABOUT_TEMPLATE.format( name=escape(name), version=escape(version), ) # TODO: Also list all known add-on versions??. text_label = QLabel(text) layout.addWidget(text_label, Qt.AlignCenter) buttons = QDialogButtonBox( QDialogButtonBox.Close, Qt.Horizontal, self) layout.addWidget(buttons) buttons.rejected.connect(self.accept) layout.setSizeConstraint(QVBoxLayout.SetFixedSize) self.setLayout(layout)
def __setupUi(self): layout = QVBoxLayout() # Scene with the link editor. self.scene = LinksEditScene() self.view = QGraphicsView(self.scene) self.view.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff) self.view.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff) self.view.setRenderHint(QPainter.Antialiasing) self.scene.editWidget.geometryChanged.connect(self.__onGeometryChanged) # Ok/Cancel/Clear All buttons. buttons = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel | QDialogButtonBox.Reset, Qt.Horizontal) clear_button = buttons.button(QDialogButtonBox.Reset) clear_button.setText(self.tr("Clear All")) buttons.accepted.connect(self.accept) buttons.rejected.connect(self.reject) clear_button.clicked.connect(self.scene.editWidget.clearLinks) layout.addWidget(self.view) layout.addWidget(buttons) self.setLayout(layout) layout.setSizeConstraint(QVBoxLayout.SetFixedSize) self.setSizeGripEnabled(False)
def __setupUi(self): layout = QVBoxLayout() label = QLabel(self) pixmap, _ = config.splash_screen() label.setPixmap(pixmap) layout.addWidget(label, Qt.AlignCenter) try: from Orange.version import version from Orange.version import git_revision except ImportError: dist = pkg_resources.get_distribution("Orange3") version = dist.version git_revision = "Unknown" text = ABOUT_TEMPLATE.format(version=version, git_revision=git_revision[:7]) # TODO: Also list all known add-on versions. text_label = QLabel(text) layout.addWidget(text_label, Qt.AlignCenter) buttons = QDialogButtonBox(QDialogButtonBox.Close, Qt.Horizontal, self) layout.addWidget(buttons) buttons.rejected.connect(self.accept) layout.setSizeConstraint(QVBoxLayout.SetFixedSize) self.setLayout(layout)
def __setupUi(self): layout = QVBoxLayout() label = QLabel(self) pixmap, _ = config.splash_screen() label.setPixmap(pixmap) layout.addWidget(label, Qt.AlignCenter) try: from Orange.version import version from Orange.version import git_revision except ImportError: dist = pkg_resources.get_distribution("Orange3") version = dist.version git_revision = "Unknown" text = ABOUT_TEMPLATE.format(version=version, git_revision=git_revision[:7]) # TODO: Also list all known add-on versions. text_label = QLabel(text) layout.addWidget(text_label, Qt.AlignCenter) buttons = QDialogButtonBox(QDialogButtonBox.Close, Qt.Horizontal, self) layout.addWidget(buttons) buttons.rejected.connect(self.accept) layout.setSizeConstraint(QVBoxLayout.SetFixedSize) self.setLayout(layout)
def __setupUi(self): layout = QVBoxLayout() label = QLabel(self) pixmap, _ = config.splash_screen() label.setPixmap(pixmap) layout.addWidget(label, Qt.AlignCenter) name = QApplication.applicationName() version = QApplication.applicationVersion() text = ABOUT_TEMPLATE.format( name=escape(name), version=escape(version), ) # TODO: Also list all known add-on versions??. text_label = QLabel(text) layout.addWidget(text_label, Qt.AlignCenter) buttons = QDialogButtonBox(QDialogButtonBox.Close, Qt.Horizontal, self) layout.addWidget(buttons) buttons.rejected.connect(self.accept) layout.setSizeConstraint(QVBoxLayout.SetFixedSize) self.setLayout(layout)
def __run_add_package_dialog(self): self.__add_package_by_name_dialog = dlg = QDialog( self, windowTitle="Add add-on by name", ) dlg.setAttribute(Qt.WA_DeleteOnClose) vlayout = QVBoxLayout() form = QFormLayout() form.setContentsMargins(0, 0, 0, 0) nameentry = QLineEdit(placeholderText="Package name", toolTip="Enter a package name as displayed on " "PyPI (capitalization is not important)") nameentry.setMinimumWidth(250) form.addRow("Name:", nameentry) vlayout.addLayout(form) buttons = QDialogButtonBox(standardButtons=QDialogButtonBox.Ok | QDialogButtonBox.Cancel) okb = buttons.button(QDialogButtonBox.Ok) okb.setEnabled(False) okb.setText("Add") def changed(name): okb.setEnabled(bool(name)) nameentry.textChanged.connect(changed) vlayout.addWidget(buttons) vlayout.setSizeConstraint(QVBoxLayout.SetFixedSize) dlg.setLayout(vlayout) f = None def query(): nonlocal f name = nameentry.text() def query_pypi(name): # type: (str) -> _QueryResult res, = pypi_json_query_project_meta([name]) inst = None # type: Optional[Installable] if res is not None: inst = installable_from_json_response(res) else: inst = None return _QueryResult(queryname=name, installable=inst) f = self.__executor.submit(query_pypi, name) okb.setDisabled(True) f.add_done_callback( method_queued(self.__on_add_single_query_finish, (object, ))) buttons.accepted.connect(query) buttons.rejected.connect(dlg.reject) dlg.exec_()
def __run_add_package_dialog(self): self.__add_package_by_name_dialog = dlg = QDialog( self, windowTitle="Add add-on by name", ) dlg.setAttribute(Qt.WA_DeleteOnClose) vlayout = QVBoxLayout() form = QFormLayout() form.setContentsMargins(0, 0, 0, 0) nameentry = QLineEdit( placeholderText="Package name", toolTip="Enter a package name as displayed on " "PyPI (capitalization is not important)") nameentry.setMinimumWidth(250) form.addRow("Name:", nameentry) vlayout.addLayout(form) buttons = QDialogButtonBox( standardButtons=QDialogButtonBox.Ok | QDialogButtonBox.Cancel ) okb = buttons.button(QDialogButtonBox.Ok) okb.setEnabled(False) okb.setText("Add") def changed(name): okb.setEnabled(bool(name)) nameentry.textChanged.connect(changed) vlayout.addWidget(buttons) vlayout.setSizeConstraint(QVBoxLayout.SetFixedSize) dlg.setLayout(vlayout) f = None def query(): nonlocal f name = nameentry.text() def query_pypi(name): # type: (str) -> _QueryResult res = pypi_json_query_project_meta([name]) assert len(res) == 1 r = res[0] if r is not None: r = installable_from_json_response(r) return _QueryResult(queryname=name, installable=r) f = self.__executor.submit(query_pypi, name) okb.setDisabled(True) f.add_done_callback( method_queued(self.__on_add_single_query_finish, (object,)) ) buttons.accepted.connect(query) buttons.rejected.connect(dlg.reject) dlg.exec_()
def __setupUi(self): layout = QVBoxLayout() layout.setContentsMargins(0, 0, 0, 0) self.setContentsMargins(0, 0, 0, 0) heading = self.tr("预览") heading = "<h3>{0}</h3>".format(heading) self.__heading = QLabel(heading, self, objectName="heading") self.__heading.setContentsMargins(12, 12, 12, 0) self.__browser = previewbrowser.PreviewBrowser(self) self.__buttons = QDialogButtonBox(QDialogButtonBox.Open | \ QDialogButtonBox.Cancel, Qt.Horizontal,) self.__buttons.button(QDialogButtonBox.Open).setAutoDefault(True) # Set the Open dialog as disabled until the current index changes self.__buttons.button(QDialogButtonBox.Open).setEnabled(False) self.__buttons.button(QDialogButtonBox.Open).setText("打开") self.__buttons.button(QDialogButtonBox.Cancel).setText("取消") # The QDialogButtonsWidget messes with the layout if it is # contained directly in the QDialog. So we create an extra # layer of indirection. buttons = QWidget(objectName="button-container") buttons_l = QVBoxLayout() buttons_l.setContentsMargins(12, 0, 12, 12) buttons.setLayout(buttons_l) buttons_l.addWidget(self.__buttons) layout.addWidget(self.__heading) layout.addWidget(self.__browser) layout.addWidget(buttons) self.__buttons.accepted.connect(self.accept) self.__buttons.rejected.connect(self.reject) self.__browser.currentIndexChanged.connect( self.__on_currentIndexChanged ) self.__browser.activated.connect(self.__on_activated) layout.setSizeConstraint(QVBoxLayout.SetFixedSize) self.setLayout(layout) self.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
def __setupUi(self): layout = QVBoxLayout() layout.setContentsMargins(0, 0, 0, 0) self.setContentsMargins(0, 0, 0, 0) heading = self.tr("Preview") heading = "<h3>{0}</h3>".format(heading) self.__heading = QLabel(heading, self, objectName="heading") self.__heading.setContentsMargins(12, 12, 12, 0) self.__browser = previewbrowser.PreviewBrowser(self) self.__buttons = QDialogButtonBox(QDialogButtonBox.Open | \ QDialogButtonBox.Cancel, Qt.Horizontal,) self.__buttons.button(QDialogButtonBox.Open).setAutoDefault(True) # Set the Open dialog as disabled until the current index changes self.__buttons.button(QDialogButtonBox.Open).setEnabled(False) # The QDialogButtonsWidget messes with the layout if it is # contained directly in the QDialog. So we create an extra # layer of indirection. buttons = QWidget(objectName="button-container") buttons_l = QVBoxLayout() buttons_l.setContentsMargins(12, 0, 12, 12) buttons.setLayout(buttons_l) buttons_l.addWidget(self.__buttons) layout.addWidget(self.__heading) layout.addWidget(self.__browser) layout.addWidget(buttons) self.__buttons.accepted.connect(self.accept) self.__buttons.rejected.connect(self.reject) self.__browser.currentIndexChanged.connect( self.__on_currentIndexChanged ) self.__browser.activated.connect(self.__on_activated) layout.setSizeConstraint(QVBoxLayout.SetFixedSize) self.setLayout(layout) self.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
def __run_add_package_dialog(self): dlg = QDialog(self, windowTitle="Add add-on by name") dlg.setAttribute(Qt.WA_DeleteOnClose) vlayout = QVBoxLayout() form = QFormLayout() form.setContentsMargins(0, 0, 0, 0) nameentry = QLineEdit(placeholderText="Package name", toolTip="Enter a package name as displayed on " "PyPI (capitalization is not important)") nameentry.setMinimumWidth(250) form.addRow("Name:", nameentry) vlayout.addLayout(form) buttons = QDialogButtonBox(standardButtons=QDialogButtonBox.Ok | QDialogButtonBox.Cancel) okb = buttons.button(QDialogButtonBox.Ok) okb.setEnabled(False) okb.setText("Add") def changed(name): okb.setEnabled(bool(name)) nameentry.textChanged.connect(changed) vlayout.addWidget(buttons) vlayout.setSizeConstraint(QVBoxLayout.SetFixedSize) dlg.setLayout(vlayout) f = None def query(): nonlocal f name = nameentry.text() f = self._executor.submit(pypi_json_query_project_meta, [name]) okb.setDisabled(True) def ondone(f): error_text = "" error_details = "" try: pkgs = f.result() except Exception: log.error("Query error:", exc_info=True) error_text = "Failed to query package index" error_details = traceback.format_exc() pkg = None else: pkg = pkgs[0] if pkg is None: error_text = "'{}' not was not found".format(name) if pkg: method_queued(self.add_package, (object, ))(pkg) method_queued(dlg.accept, ())() else: method_queued(self.__show_error_for_query, (str, str)) \ (error_text, error_details) method_queued(dlg.reject, ())() f.add_done_callback(ondone) buttons.accepted.connect(query) buttons.rejected.connect(dlg.reject) dlg.exec_()
def __run_add_package_dialog(self): dlg = QDialog(self, windowTitle="Add add-on by name") dlg.setAttribute(Qt.WA_DeleteOnClose) vlayout = QVBoxLayout() form = QFormLayout() form.setContentsMargins(0, 0, 0, 0) nameentry = QLineEdit( placeholderText="Package name", toolTip="Enter a package name as displayed on " "PyPI (capitalization is not important)") nameentry.setMinimumWidth(250) form.addRow("Name:", nameentry) vlayout.addLayout(form) buttons = QDialogButtonBox( standardButtons=QDialogButtonBox.Ok | QDialogButtonBox.Cancel ) okb = buttons.button(QDialogButtonBox.Ok) okb.setEnabled(False) okb.setText("Add") def changed(name): okb.setEnabled(bool(name)) nameentry.textChanged.connect(changed) vlayout.addWidget(buttons) vlayout.setSizeConstraint(QVBoxLayout.SetFixedSize) dlg.setLayout(vlayout) f = None def query(): nonlocal f name = nameentry.text() f = self._executor.submit(pypi_json_query_project_meta, [name]) okb.setDisabled(True) def ondone(f): error_text = "" error_details = "" try: pkgs = f.result() except Exception: log.error("Query error:", exc_info=True) error_text = "Failed to query package index" error_details = traceback.format_exc() pkg = None else: pkg = pkgs[0] if pkg is None: error_text = "'{}' not was not found".format(name) if pkg: method_queued(self.add_package, (object,))(pkg) method_queued(dlg.accept, ())() else: method_queued(self.__show_error_for_query, (str, str)) \ (error_text, error_details) method_queued(dlg.reject, ())() f.add_done_callback(ondone) buttons.accepted.connect(query) buttons.rejected.connect(dlg.reject) dlg.exec_()
class ToolBox(QFrame): """ A tool box widget. """ # Emitted when a tab is toggled. tabToogled = Signal(int, bool) def setExclusive(self, exclusive): """ Set exclusive tabs (only one tab can be open at a time). """ if self.__exclusive != exclusive: self.__exclusive = exclusive self.__tabActionGroup.setExclusive(exclusive) checked = self.__tabActionGroup.checkedAction() if checked is None: # The action group can be out of sync with the actions state # when switching between exclusive states. actions_checked = [ page.action for page in self.__pages if page.action.isChecked() ] if actions_checked: checked = actions_checked[0] # Trigger/toggle remaining open pages if exclusive and checked is not None: for page in self.__pages: if checked != page.action and page.action.isChecked(): page.action.trigger() def exclusive(self): """ Are the tabs in the toolbox exclusive. """ return self.__exclusive exclusive_ = Property( bool, fget=exclusive, fset=setExclusive, designable=True, doc="Exclusive tabs" ) def __init__(self, parent=None, **kwargs): QFrame.__init__(self, parent, **kwargs) self.__pages = [] self.__tabButtonHeight = -1 self.__tabIconSize = QSize() self.__exclusive = False self.__setupUi() def __setupUi(self): layout = QVBoxLayout() layout.setContentsMargins(0, 0, 0, 0) # Scroll area for the contents. self.__scrollArea = _ToolBoxScrollArea(self, objectName="toolbox-scroll-area") self.__scrollArea.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOn) self.__scrollArea.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff) self.__scrollArea.setSizePolicy( QSizePolicy.MinimumExpanding, QSizePolicy.MinimumExpanding ) self.__scrollArea.setFrameStyle(QScrollArea.NoFrame) self.__scrollArea.setWidgetResizable(True) # A widget with all of the contents. # The tabs/contents are placed in the layout inside this widget self.__contents = QWidget(self.__scrollArea, objectName="toolbox-contents") # The layout where all the tab/pages are placed self.__contentsLayout = QVBoxLayout() self.__contentsLayout.setContentsMargins(0, 0, 0, 0) self.__contentsLayout.setSizeConstraint(QVBoxLayout.SetMinAndMaxSize) self.__contentsLayout.setSpacing(0) self.__contents.setLayout(self.__contentsLayout) self.__scrollArea.setWidget(self.__contents) layout.addWidget(self.__scrollArea) self.setLayout(layout) self.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.MinimumExpanding) self.__tabActionGroup = QActionGroup( self, objectName="toolbox-tab-action-group" ) self.__tabActionGroup.setExclusive(self.__exclusive) self.__actionMapper = QSignalMapper(self) self.__actionMapper.mapped[QObject].connect(self.__onTabActionToogled) def setTabButtonHeight(self, height): """ Set the tab button height. """ if self.__tabButtonHeight != height: self.__tabButtonHeight = height for page in self.__pages: page.button.setFixedHeight(height) def tabButtonHeight(self): """ Return the tab button height. """ return self.__tabButtonHeight def setTabIconSize(self, size): """ Set the tab button icon size. """ if self.__tabIconSize != size: self.__tabIconSize = size for page in self.__pages: page.button.setIconSize(size) def tabIconSize(self): """ Return the tab icon size. """ return self.__tabIconSize def tabButton(self, index): """ Return the tab button at `index` """ return self.__pages[index].button def tabAction(self, index): """ Return open/close action for the tab at `index`. """ return self.__pages[index].action def addItem(self, widget, text, icon=None, toolTip=None): """ Append the `widget` in a new tab and return its index. Parameters ---------- widget : :class:`QWidget` A widget to be inserted. The toolbox takes ownership of the widget. text : str Name/title of the new tab. icon : :class:`QIcon`, optional An icon for the tab button. toolTip : str, optional Tool tip for the tab button. """ return self.insertItem(self.count(), widget, text, icon, toolTip) def insertItem(self, index, widget, text, icon=None, toolTip=None): """ Insert the `widget` in a new tab at position `index`. See also -------- ToolBox.addItem """ button = self.createTabButton(widget, text, icon, toolTip) self.__contentsLayout.insertWidget(index * 2, button) self.__contentsLayout.insertWidget(index * 2 + 1, widget) widget.hide() page = _ToolBoxPage(index, widget, button.defaultAction(), button) self.__pages.insert(index, page) for i in range(index + 1, self.count()): self.__pages[i] = self.__pages[i]._replace(index=i) self.__updatePositions() # Show (open) the first tab. if self.count() == 1 and index == 0: page.action.trigger() self.__updateSelected() self.updateGeometry() return index def removeItem(self, index): """ Remove the widget at `index`. .. note:: The widget hidden but is is not deleted. """ self.__contentsLayout.takeAt(2 * index + 1) self.__contentsLayout.takeAt(2 * index) page = self.__pages.pop(index) # Update the page indexes for i in range(index, self.count()): self.__pages[i] = self.__pages[i]._replace(index=i) page.button.deleteLater() # Hide the widget and reparent to self # This follows QToolBox.removeItem page.widget.hide() page.widget.setParent(self) self.__updatePositions() self.__updateSelected() self.updateGeometry() def count(self): """ Return the number of widgets inserted in the toolbox. """ return len(self.__pages) def widget(self, index): """ Return the widget at `index`. """ return self.__pages[index].widget def createTabButton(self, widget, text, icon=None, toolTip=None): """ Create the tab button for `widget`. """ action = QAction(text, self) action.setCheckable(True) if icon: action.setIcon(icon) if toolTip: action.setToolTip(toolTip) self.__tabActionGroup.addAction(action) self.__actionMapper.setMapping(action, action) action.toggled.connect(self.__actionMapper.map) button = ToolBoxTabButton(self, objectName="toolbox-tab-button") button.setDefaultAction(action) button.setToolButtonStyle(Qt.ToolButtonTextBesideIcon) button.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed) if self.__tabIconSize.isValid(): button.setIconSize(self.__tabIconSize) if self.__tabButtonHeight > 0: button.setFixedHeight(self.__tabButtonHeight) return button def ensureWidgetVisible(self, child, xmargin=50, ymargin=50): """ Scroll the contents so child widget instance is visible inside the viewport. """ self.__scrollArea.ensureWidgetVisible(child, xmargin, ymargin) def sizeHint(self): hint = self.__contentsLayout.sizeHint() if self.count(): # Compute max width of hidden widgets also. scroll = self.__scrollArea scroll_w = scroll.verticalScrollBar().sizeHint().width() frame_w = self.frameWidth() * 2 + scroll.frameWidth() * 2 max_w = max([p.widget.sizeHint().width() for p in self.__pages]) hint = QSize(max(max_w, hint.width()) + scroll_w + frame_w, hint.height()) return QSize(200, 200).expandedTo(hint) def __onTabActionToogled(self, action): page = find(self.__pages, action, key=attrgetter("action")) on = action.isChecked() page.widget.setVisible(on) index = page.index if index > 0: # Update the `previous` tab buttons style hints previous = self.__pages[index - 1].button flag = QStyleOptionToolBox.NextIsSelected if on: previous.selected |= flag else: previous.selected &= ~flag previous.update() if index < self.count() - 1: next = self.__pages[index + 1].button flag = QStyleOptionToolBox.PreviousIsSelected if on: next.selected |= flag else: next.selected &= ~flag next.update() self.tabToogled.emit(index, on) self.__contentsLayout.invalidate() def __updateSelected(self): """Update the tab buttons selected style flags. """ if self.count() == 0: return opt = QStyleOptionToolBox def update(button, next_sel, prev_sel): if next_sel: button.selected |= opt.NextIsSelected else: button.selected &= ~opt.NextIsSelected if prev_sel: button.selected |= opt.PreviousIsSelected else: button.selected &= ~opt.PreviousIsSelected button.update() if self.count() == 1: update(self.__pages[0].button, False, False) elif self.count() >= 2: pages = self.__pages for i in range(1, self.count() - 1): update( pages[i].button, pages[i + 1].action.isChecked(), pages[i - 1].action.isChecked(), ) def __updatePositions(self): """Update the tab buttons position style flags. """ if self.count() == 0: return elif self.count() == 1: self.__pages[0].button.position = QStyleOptionToolBox.OnlyOneTab else: self.__pages[0].button.position = QStyleOptionToolBox.Beginning self.__pages[-1].button.position = QStyleOptionToolBox.End for p in self.__pages[1:-1]: p.button.position = QStyleOptionToolBox.Middle for p in self.__pages: p.button.update()
class ToolBox(QFrame): """ A tool box widget. """ # Emitted when a tab is toggled. tabToogled = Signal(int, bool) def setExclusive(self, exclusive): """ Set exclusive tabs (only one tab can be open at a time). """ if self.__exclusive != exclusive: self.__exclusive = exclusive self.__tabActionGroup.setExclusive(exclusive) checked = self.__tabActionGroup.checkedAction() if checked is None: # The action group can be out of sync with the actions state # when switching between exclusive states. actions_checked = [page.action for page in self.__pages if page.action.isChecked()] if actions_checked: checked = actions_checked[0] # Trigger/toggle remaining open pages if exclusive and checked is not None: for page in self.__pages: if checked != page.action and page.action.isChecked(): page.action.trigger() def exclusive(self): """ Are the tabs in the toolbox exclusive. """ return self.__exclusive exclusive_ = Property(bool, fget=exclusive, fset=setExclusive, designable=True, doc="Exclusive tabs") def __init__(self, parent=None, **kwargs): QFrame.__init__(self, parent, **kwargs) self.__pages = [] self.__tabButtonHeight = -1 self.__tabIconSize = QSize() self.__exclusive = False self.__setupUi() def __setupUi(self): layout = QVBoxLayout() layout.setContentsMargins(0, 0, 0, 0) # Scroll area for the contents. self.__scrollArea = \ _ToolBoxScrollArea(self, objectName="toolbox-scroll-area") self.__scrollArea.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOn) self.__scrollArea.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff) self.__scrollArea.setSizePolicy(QSizePolicy.MinimumExpanding, QSizePolicy.MinimumExpanding) self.__scrollArea.setFrameStyle(QScrollArea.NoFrame) self.__scrollArea.setWidgetResizable(True) # A widget with all of the contents. # The tabs/contents are placed in the layout inside this widget self.__contents = QWidget(self.__scrollArea, objectName="toolbox-contents") # The layout where all the tab/pages are placed self.__contentsLayout = QVBoxLayout() self.__contentsLayout.setContentsMargins(0, 0, 0, 0) self.__contentsLayout.setSizeConstraint(QVBoxLayout.SetMinAndMaxSize) self.__contentsLayout.setSpacing(0) self.__contents.setLayout(self.__contentsLayout) self.__scrollArea.setWidget(self.__contents) layout.addWidget(self.__scrollArea) self.setLayout(layout) self.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.MinimumExpanding) self.__tabActionGroup = \ QActionGroup(self, objectName="toolbox-tab-action-group") self.__tabActionGroup.setExclusive(self.__exclusive) self.__actionMapper = QSignalMapper(self) self.__actionMapper.mapped[QObject].connect(self.__onTabActionToogled) def setTabButtonHeight(self, height): """ Set the tab button height. """ if self.__tabButtonHeight != height: self.__tabButtonHeight = height for page in self.__pages: page.button.setFixedHeight(height) def tabButtonHeight(self): """ Return the tab button height. """ return self.__tabButtonHeight def setTabIconSize(self, size): """ Set the tab button icon size. """ if self.__tabIconSize != size: self.__tabIconSize = size for page in self.__pages: page.button.setIconSize(size) def tabIconSize(self): """ Return the tab icon size. """ return self.__tabIconSize def tabButton(self, index): """ Return the tab button at `index` """ return self.__pages[index].button def tabAction(self, index): """ Return open/close action for the tab at `index`. """ return self.__pages[index].action def addItem(self, widget, text, icon=None, toolTip=None): """ Append the `widget` in a new tab and return its index. Parameters ---------- widget : :class:`QWidget` A widget to be inserted. The toolbox takes ownership of the widget. text : str Name/title of the new tab. icon : :class:`QIcon`, optional An icon for the tab button. toolTip : str, optional Tool tip for the tab button. """ return self.insertItem(self.count(), widget, text, icon, toolTip) def insertItem(self, index, widget, text, icon=None, toolTip=None): """ Insert the `widget` in a new tab at position `index`. See also -------- ToolBox.addItem """ button = self.createTabButton(widget, text, icon, toolTip) self.__contentsLayout.insertWidget(index * 2, button) self.__contentsLayout.insertWidget(index * 2 + 1, widget) widget.hide() page = _ToolBoxPage(index, widget, button.defaultAction(), button) self.__pages.insert(index, page) for i in range(index + 1, self.count()): self.__pages[i] = self.__pages[i]._replace(index=i) self.__updatePositions() # Show (open) the first tab. if self.count() == 1 and index == 0: page.action.trigger() self.__updateSelected() self.updateGeometry() return index def removeItem(self, index): """ Remove the widget at `index`. .. note:: The widget hidden but is is not deleted. """ self.__contentsLayout.takeAt(2 * index + 1) self.__contentsLayout.takeAt(2 * index) page = self.__pages.pop(index) # Update the page indexes for i in range(index, self.count()): self.__pages[i] = self.__pages[i]._replace(index=i) page.button.deleteLater() # Hide the widget and reparent to self # This follows QToolBox.removeItem page.widget.hide() page.widget.setParent(self) self.__updatePositions() self.__updateSelected() self.updateGeometry() def count(self): """ Return the number of widgets inserted in the toolbox. """ return len(self.__pages) def widget(self, index): """ Return the widget at `index`. """ return self.__pages[index].widget def createTabButton(self, widget, text, icon=None, toolTip=None): """ Create the tab button for `widget`. """ action = QAction(text, self) action.setCheckable(True) if icon: action.setIcon(icon) if toolTip: action.setToolTip(toolTip) self.__tabActionGroup.addAction(action) self.__actionMapper.setMapping(action, action) action.toggled.connect(self.__actionMapper.map) button = ToolBoxTabButton(self, objectName="toolbox-tab-button") button.setDefaultAction(action) button.setToolButtonStyle(Qt.ToolButtonTextBesideIcon) button.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed) if self.__tabIconSize.isValid(): button.setIconSize(self.__tabIconSize) if self.__tabButtonHeight > 0: button.setFixedHeight(self.__tabButtonHeight) return button def ensureWidgetVisible(self, child, xmargin=50, ymargin=50): """ Scroll the contents so child widget instance is visible inside the viewport. """ self.__scrollArea.ensureWidgetVisible(child, xmargin, ymargin) def sizeHint(self): hint = self.__contentsLayout.sizeHint() if self.count(): # Compute max width of hidden widgets also. scroll = self.__scrollArea scroll_w = scroll.verticalScrollBar().sizeHint().width() frame_w = self.frameWidth() * 2 + scroll.frameWidth() * 2 max_w = max([p.widget.sizeHint().width() for p in self.__pages]) hint = QSize(max(max_w, hint.width()) + scroll_w + frame_w, hint.height()) return QSize(200, 200).expandedTo(hint) def __onTabActionToogled(self, action): page = find(self.__pages, action, key=attrgetter("action")) on = action.isChecked() page.widget.setVisible(on) index = page.index if index > 0: # Update the `previous` tab buttons style hints previous = self.__pages[index - 1].button flag = QStyleOptionToolBox.NextIsSelected if on: previous.selected |= flag else: previous.selected &= ~flag previous.update() if index < self.count() - 1: next = self.__pages[index + 1].button flag = QStyleOptionToolBox.PreviousIsSelected if on: next.selected |= flag else: next.selected &= ~flag next.update() self.tabToogled.emit(index, on) self.__contentsLayout.invalidate() def __updateSelected(self): """Update the tab buttons selected style flags. """ if self.count() == 0: return opt = QStyleOptionToolBox def update(button, next_sel, prev_sel): if next_sel: button.selected |= opt.NextIsSelected else: button.selected &= ~opt.NextIsSelected if prev_sel: button.selected |= opt.PreviousIsSelected else: button.selected &= ~ opt.PreviousIsSelected button.update() if self.count() == 1: update(self.__pages[0].button, False, False) elif self.count() >= 2: pages = self.__pages for i in range(1, self.count() - 1): update(pages[i].button, pages[i + 1].action.isChecked(), pages[i - 1].action.isChecked()) def __updatePositions(self): """Update the tab buttons position style flags. """ if self.count() == 0: return elif self.count() == 1: self.__pages[0].button.position = QStyleOptionToolBox.OnlyOneTab else: self.__pages[0].button.position = QStyleOptionToolBox.Beginning self.__pages[-1].button.position = QStyleOptionToolBox.End for p in self.__pages[1:-1]: p.button.position = QStyleOptionToolBox.Middle for p in self.__pages: p.button.update()