def initGlobalStyle(cls, *args): """ Initialize style that will be used across the application .. note:: A limited set of pre-defined styles are available If desired it is possible to create a completely custom style, see the links below... Best left for major application creation in C++, not recommended for Python https://doc.qt.io/qt-5/qstyle.html#creating-a-custom-style https://doc.qt.io/qt-5/qstyleplugin.html https://doc.qt.io/qt-5/qstylefactory.html """ print("\n\nAvailable styles: " + ", ".join(sorted(QStyleFactory.keys()))) style = "Fusion" for arg in args: if arg.lower() in [k.lower() for k in QStyleFactory.keys()]: style = arg style = QStyleFactory.create(style) QApplication.instance().setStyle(style)
def setAppStyle(app): if "Fusion" in [st for st in QStyleFactory.keys()]: app.setStyle(QStyleFactory.create("Fusion")) elif sys.platform == "win32": app.setStyle(QStyleFactory.create("WindowsVista")) elif sys.platform == "linux": app.setStyle(QStyleFactory.create("gtk")) elif sys.platform == "darwin": app.setStyle(QStyleFactory.create("macintosh"))
def launch_qt_gui(bk, prefs): supports_theming = (bk.launcher_version() >= 20200117) app = QApplication(sys.argv) # Make plugin match Sigil's light/dark theme if supports_theming: if bk.colorMode() == "dark": app.setStyle(QStyleFactory.create("Fusion")) app.setPalette(dark_palette(bk.color)) print('Application dir: {}'.format(QCoreApplication.applicationDirPath())) # Install qtbase translator for standard dialogs and such. # Use the Sigil language setting unless manually overridden. qt_translator = QTranslator() if prefs['language_override'] is not None: print('Plugin preferences language override in effect') qmf = 'qtbase_{}'.format(prefs['language_override']) else: qmf = 'qtbase_{}'.format(bk.sigil_ui_lang) # Get bundled or external translations directory qt_trans_dir = getQtTranslationsPath(bk._w.appdir) print('Qt translation dir: {}'.format(qt_trans_dir)) print('Looking for {} in {}'.format(qmf, qt_trans_dir)) qt_translator.load(qmf, qt_trans_dir) print('Translator succesfully installed: {}'.format( app.installTranslator(qt_translator))) ex = App(bk, prefs) ex.show() app.exec_() return _DETAILS
def initUI(self): hbox = QHBoxLayout(self) topleft = QFrame(self) topleft.setFrameShape(QFrame.StyledPanel) topright = QFrame(self) topright.setFrameShape(QFrame.StyledPanel) bottom = QFrame(self) bottom.setFrameShape(QFrame.StyledPanel) splitter1 = QSplitter(QtCore.Qt.Horizontal) splitter1.addWidget(topleft) splitter1.addWidget(topright) splitter2 = QSplitter(QtCore.Qt.Vertical) splitter2.addWidget(splitter1) splitter2.addWidget(bottom) hbox.addWidget(splitter2) self.setLayout(hbox) QApplication.setStyle(QStyleFactory.create('Cleanlooks')) self.setGeometry(500, 500, 500, 500) self.setWindowTitle('QSplitter') self.show()
def main(): multiprocessing.freeze_support() app = QApplication(sys.argv) app.setApplicationName("nfb-studio") app.setApplicationDisplayName("NFB Studio") app.setStyle(QStyleFactory.create("fusion")) if platform.system() == "Darwin": icon_dir = package.dir / "assets/window-icon/macos" else: icon_dir = package.dir / "assets/window-icon/generic" icon = QIcon() for file in icon_dir.glob("*"): icon.addFile(str(file)) app.setWindowIcon(icon) main_window = ExperimentView() main_window.show() # If a file was passed as a command-line argument, load it if len(sys.argv) > 1: main_window.fileOpen(sys.argv[1]) return app.exec_()
def setup_app(): QCoreApplication.setAttribute(Qt.AA_DisableHighDpiScaling) app = QApplication(sys.argv) splash = QSplashScreen() pixmap = QPixmap(os.path.join(QGRAIN_ROOT_PATH, "assets", "icon.png")) pixmap.setDevicePixelRatio(1.0) splash.setPixmap(pixmap) splash.show() create_necessary_folders() app.setWindowIcon(QIcon(pixmap)) app.setApplicationDisplayName(f"QGrain ({QGRAIN_VERSION})") app.setApplicationVersion(QGRAIN_VERSION) app.setStyle(QStyleFactory.create("Fusion")) app.setStyleSheet("""* {font-family:Arial,Helvetica,Tahoma,Verdana; color:#000000;background-color:#c4cbcf;alternate-background-color:#b2bbbe; selection-color:#ffffff;selection-background-color:#555f69}""") plt.style.use(["science", "no-latex"]) plt.set_cmap("tab10") plt.rcParams["axes.facecolor"] = "#c4cbcf" plt.rcParams["figure.facecolor"] = "#c4cbcf" plt.rcParams["savefig.dpi"] = 300.0 plt.rcParams["savefig.facecolor"] = "white" plt.rcParams["savefig.transparent"] = True plt.rcParams["figure.max_open_warning"] = False setup_language(app) setup_logging() return app, splash
def dark_palette(bk, app): if not (bk.launcher_version() >= 20200117): return if bk.colorMode() != "dark": return p = QPalette() sigil_colors = bk.color dark_color = QColor(sigil_colors("Window")) disabled_color = QColor(127, 127, 127) dark_link_color = QColor(108, 180, 238) text_color = QColor(sigil_colors("Text")) p.setColor(p.Window, dark_color) p.setColor(p.WindowText, text_color) p.setColor(p.Base, QColor(sigil_colors("Base"))) p.setColor(p.AlternateBase, dark_color) p.setColor(p.ToolTipBase, dark_color) p.setColor(p.ToolTipText, text_color) p.setColor(p.Text, text_color) p.setColor(p.Disabled, p.Text, disabled_color) p.setColor(p.Button, dark_color) p.setColor(p.ButtonText, text_color) p.setColor(p.Disabled, p.ButtonText, disabled_color) p.setColor(p.BrightText, Qt.red) p.setColor(p.Link, dark_link_color) p.setColor(p.Highlight, QColor(sigil_colors("Highlight"))) p.setColor(p.HighlightedText, QColor(sigil_colors("HighlightedText"))) p.setColor(p.Disabled, p.HighlightedText, disabled_color) app.setStyle(QStyleFactory.create("Fusion")) app.setPalette(p)
def testSetStyle(self): '''All this test have to do is not break with some invalid Python wrapper.''' def setStyleHelper(widget, style): widget.setStyle(style) widget.setPalette(style.standardPalette()) for child in widget.children(): if isinstance(child, QWidget): setStyleHelper(child, style) container = QWidget() # QFontComboBox is used because it has an QLineEdit created in C++ inside it, # and if the QWidget.setStyle(style) steals the ownership of the style # for the C++ originated widget everything will break. fontComboBox = QFontComboBox(container) label = QLabel(container) label.setText('Label') style = QStyleFactory.create(QStyleFactory.keys()[0]) setStyleHelper(container, style)
def __init__(self, parent=None): super(WidgetGallery, self).__init__(parent) self.originalPalette = QApplication.palette() styleComboBox = QComboBox() styleComboBox.addItems(QStyleFactory.keys()) styleLabel = QLabel("&Style:") styleLabel.setBuddy(styleComboBox) self.useStylePaletteCheckBox = QCheckBox( "&Use style's standard palette") self.useStylePaletteCheckBox.setChecked(True) disableWidgetsCheckBox = QCheckBox("&Disable widgets") self.createTopLeftGroupBox() self.createTopRightGroupBox() self.createBottomLeftTabWidget() self.createBottomRightGroupBox() self.createProgressBar() styleComboBox.activated[str].connect(self.changeStyle) self.useStylePaletteCheckBox.toggled.connect(self.changePalette) disableWidgetsCheckBox.toggled.connect( self.topLeftGroupBox.setDisabled) disableWidgetsCheckBox.toggled.connect( self.topRightGroupBox.setDisabled) disableWidgetsCheckBox.toggled.connect( self.bottomLeftTabWidget.setDisabled) disableWidgetsCheckBox.toggled.connect( self.bottomRightGroupBox.setDisabled) topLayout = QHBoxLayout() topLayout.addWidget(styleLabel) topLayout.addWidget(styleComboBox) topLayout.addStretch(1) topLayout.addWidget(self.useStylePaletteCheckBox) topLayout.addWidget(disableWidgetsCheckBox) mainLayout = QGridLayout() mainLayout.addLayout(topLayout, 0, 0, 1, 2) mainLayout.addWidget(self.topLeftGroupBox, 1, 0) mainLayout.addWidget(self.topRightGroupBox, 1, 1) mainLayout.addWidget(self.bottomLeftTabWidget, 2, 0) mainLayout.addWidget(self.bottomRightGroupBox, 2, 1) mainLayout.addWidget(self.progressBar, 3, 0, 1, 2) mainLayout.setRowStretch(1, 1) mainLayout.setRowStretch(2, 1) mainLayout.setColumnStretch(0, 1) mainLayout.setColumnStretch(1, 1) self.setLayout(mainLayout) self.setWindowTitle("Common Qt Widgets") self.changeStyle('Fusion')
def _populate_themes_menu(self): self.theme_menu = self.menuOptions.addMenu("Theme") current_theme = locator.get_static("SettingsService").get_theme() for theme in QStyleFactory.keys(): action = self.theme_menu.addAction(theme) action.setCheckable(True) if theme == current_theme: action.setChecked(True) action.setActionGroup(self.theme_action_group) action.changed.connect( lambda a=action, t=theme: self._on_theme_changed(a, t))
def testSetProxyStyle(self): label = QLabel("QtWidgets/ProxyStyle test") baseStyle = QStyleFactory.create( QApplication.instance().style().objectName()) self.assertTrue(baseStyle) proxyStyle = ProxyStyle(baseStyle) label.setStyle(proxyStyle) label.show() while not label.windowHandle().isExposed(): QApplication.instance().processEvents() self.assertTrue(proxyStyle.polished > 0)
def __init__(self): super(MainWindow, self).__init__() self.ui = Ui_MainWindow() self.ui.setupUi(self) # print available styles print(QStyleFactory.keys()) # Signals self.ui.my_button.clicked.connect(self.test)
def launch_qt_gui(bk, prefs): supports_theming = (bk.launcher_version() >= 20200117) if not ismacos: setup_highdpi(bk._w.highdpi) setup_ui_font(bk._w.uifont) if not ismacos and not iswindows: # Qt 5.10.1 on Linux resets the global font on first event loop tick. # So workaround it by setting the font once again in a timer. QTimer.singleShot(0, lambda: setup_ui_font(bk._w.uifont)) app = QApplication(sys.argv) icon = os.path.join(bk._w.plugin_dir, bk._w.plugin_name, 'plugin.svg') app.setWindowIcon(QIcon(icon)) if tuple_version(qVersion()) >= (5, 10, 0): app.setAttribute(Qt.AA_DisableWindowContextHelpButton) # Make plugin match Sigil's light/dark theme if supports_theming: if bk.colorMode() == "dark": app.setStyle(QStyleFactory.create("Fusion")) app.setPalette(dark_palette(bk.color)) print('Application dir: {}'.format(QCoreApplication.applicationDirPath())) # Install qtbase translator for standard dialogs and such. # Use the Sigil language setting unless manually overridden. qt_translator = QTranslator() if prefs['language_override'] is not None: print('Plugin preferences language override in effect') qmf = 'qtbase_{}'.format(prefs['language_override']) else: qmf = 'qtbase_{}'.format(bk.sigil_ui_lang) # Get bundled or external translations directory qt_trans_dir = getQtTranslationsPath(bk._w.appdir) print('Qt translation dir: {}'.format(qt_trans_dir)) print('Looking for {} in {}'.format(qmf, qt_trans_dir)) qt_translator.load(qmf, qt_trans_dir) print('Translator succesfully installed: {}'.format( app.installTranslator(qt_translator))) ex = App(bk, prefs) ex.show() app.exec_() return _DETAILS
def __init__(self): super().__init__('settings') self.app = QApplication.instance() idx = self.fontComboBox.findText( settings.value('appearance/font', 'MS Shell Dlg 2')) self.fontComboBox.setCurrentIndex(idx) self.styleComboBox.addItems(QStyleFactory.keys()) idx = self.styleComboBox.findText( settings.value('appearance/style', self.app.style().objectName())) self.styleComboBox.setCurrentIndex(idx) self.loopsSpinBox.setValue(int(settings.value('loopsNumber', 8))) self.buttonBox.accepted.connect(self.saveSettings) self.buttonBox.button(self.buttonBox.Reset).clicked.connect( self.resetSettings)
def __init__(self, download_item): super(DownloadWidget, self).__init__() self._download_item = download_item download_item.finished.connect(self._finished) download_item.downloadProgress.connect(self._download_progress) download_item.stateChanged.connect(self._update_tool_tip()) path = download_item.path() self.setMaximumWidth(300) # Shorten 'PySide2-5.11.0a1-5.11.0-cp36-cp36m-linux_x86_64.whl'... description = QFileInfo(path).fileName() description_length = len(description) if description_length > 30: description = '{}...{}'.format(description[0:10], description[description_length - 10:]) self.setFormat('{} %p%'.format(description)) self.setOrientation(Qt.Horizontal) self.setMinimum(0) self.setValue(0) self.setMaximum(100) self._update_tool_tip() # Force progress bar text to be shown on macoS by using 'fusion' style if sys.platform == 'darwin': self.setStyle(QStyleFactory.create('fusion'))
def restore_state(self, window): """Restore application state. :param window: """ log.info('Restoring main window state') settings = self.settings settings.beginGroup("MainWindow") self['size'] = settings.value("size", QSize(1024, 768)) self['pos'] = settings.value("pos", QPoint(200, 200)) self['state'] = settings.value("state", QByteArray()) self['geometry'] = settings.value("geometry", QByteArray()) settings.endGroup() settings.beginGroup("Appearance") self['style'] = settings.value("style", default_style()) settings.endGroup() window.resize(self['size']) window.move(self['pos']) window.restoreGeometry(self['geometry']) window.restoreState(self['state']) QApplication.setStyle(QStyleFactory.create(self['style']))
def __init__(self, value=0, show_percentage=False): super().__init__() self.value = value self.setValue(self.value) self.setTextVisible(show_percentage) self.setStyle(QStyleFactory.create("windowsvista"))
def createUI(self): # # Windows # self.progressWindow = None self.helpwindow = HelpWindow(self) self.presetWindow = PresetWindow(self) self.presetWindow.logmessage.connect(self.logmessage) self.apiWindow = ApiViewer(self) self.apiWindow.logmessage.connect(self.logmessage) self.dataWindow = DataViewer(self) self.timerWindow = TimerWindow(self) self.selectNodesWindow = SelectNodesWindow(self) self.timerWindow.timerstarted.connect(self.guiActions.timerStarted) self.timerWindow.timerstopped.connect(self.guiActions.timerStopped) self.timerWindow.timercountdown.connect(self.guiActions.timerCountdown) self.timerWindow.timerfired.connect(self.guiActions.timerFired) # # Statusbar and toolbar # self.statusbar = self.statusBar() self.toolbar = Toolbar(parent=self, mainWindow=self) self.addToolBar(Qt.TopToolBarArea, self.toolbar) self.timerStatus = QLabel("Timer stopped ") self.statusbar.addPermanentWidget(self.timerStatus) self.databaseLabel = QPushButton("No database connection ") self.statusbar.addWidget(self.databaseLabel) self.selectionStatus = QLabel("0 node(s) selected ") self.statusbar.addPermanentWidget(self.selectionStatus) #self.statusBar.showMessage('No database connection') self.statusbar.setSizeGripEnabled(False) self.databaseLabel.setFlat(True) self.databaseLabel.clicked.connect(self.databaseLabelClicked) # # Layout # #dummy widget to contain the layout manager self.mainWidget = QSplitter(self) self.mainWidget.setOrientation(Qt.Vertical) self.setCentralWidget(self.mainWidget) #top topWidget = QWidget(self) self.mainWidget.addWidget(topWidget) dataLayout = QHBoxLayout() topWidget.setLayout(dataLayout) dataSplitter = QSplitter(self) dataLayout.addWidget(dataSplitter) #top left dataWidget = QWidget() dataLayout = QVBoxLayout() dataLayout.setContentsMargins(0, 0, 0, 0) dataWidget.setLayout(dataLayout) dataSplitter.addWidget(dataWidget) dataSplitter.setStretchFactor(0, 1) #top right detailSplitter = QSplitter(self) detailSplitter.setOrientation(Qt.Vertical) #top right top detailWidget = QWidget(self) detailLayout = QVBoxLayout() detailLayout.setContentsMargins(11, 0, 0, 0) detailWidget.setLayout(detailLayout) detailSplitter.addWidget(detailWidget) dataSplitter.addWidget(detailSplitter) dataSplitter.setStretchFactor(1, 0) #bottom bottomSplitter = QSplitter(self) self.mainWidget.addWidget(bottomSplitter) self.mainWidget.setStretchFactor(0, 1) #requestLayout=QHBoxLayout() #bottomWidget.setLayout(requestLayout) #bottom left modulesWidget = QWidget(self) moduleslayout = QVBoxLayout() modulesWidget.setLayout(moduleslayout) bottomSplitter.addWidget(modulesWidget) #bottom middle fetchWidget = QWidget(self) fetchLayout = QVBoxLayout() fetchWidget.setLayout(fetchLayout) bottomSplitter.addWidget(fetchWidget) settingsGroup = QGroupBox("Settings") fetchLayout.addWidget(settingsGroup) fetchsettings = QFormLayout() fetchsettings.setRowWrapPolicy(QFormLayout.DontWrapRows) fetchsettings.setFieldGrowthPolicy(QFormLayout.AllNonFixedFieldsGrow) fetchsettings.setFormAlignment(Qt.AlignLeft | Qt.AlignTop) fetchsettings.setLabelAlignment(Qt.AlignLeft) settingsGroup.setLayout(fetchsettings) #fetchLayout.addLayout(fetchsettings) fetchdata = QHBoxLayout() fetchdata.setContentsMargins(10, 0, 10, 0) fetchLayout.addLayout(fetchdata) #bottom right statusWidget = QWidget(self) statusLayout = QVBoxLayout() statusWidget.setLayout(statusLayout) bottomSplitter.addWidget(statusWidget) # # Settings widget #s self.settingsWidget = QWidget() self.settingsLayout = QFormLayout() self.settingsLayout.setContentsMargins(0, 0, 0, 0) self.settingsWidget.setLayout(self.settingsLayout) # Add headers self.headersCheckbox = QCheckBox("Create header nodes", self) self.headersCheckbox.setChecked( str(self.settings.value('saveheaders', 'false')) == 'true') self.headersCheckbox.setToolTip( wraptip( "Check if you want to create nodes containing headers of the response." )) self.settingsLayout.addRow(self.headersCheckbox) # Full offcut self.offcutCheckbox = QCheckBox("Keep all data in offcut", self) self.offcutCheckbox.setChecked( str(self.settings.value('fulloffcut', 'false')) == 'true') self.offcutCheckbox.setToolTip( wraptip( "Check if you don't want to filter out data from the offcut node. Useful for webscraping, keeps the full HTML content" )) self.settingsLayout.addRow(self.offcutCheckbox) # Timeout self.timeoutEdit = QSpinBox(self) self.timeoutEdit.setMinimum(1) self.timeoutEdit.setMaximum(300) self.timeoutEdit.setToolTip( wraptip("How many seconds will you wait for a response?")) self.timeoutEdit.setValue(self.settings.value('timeout', 15)) self.settingsLayout.addRow('Request timeout', self.timeoutEdit) # Max data size self.maxsizeEdit = QSpinBox(self) self.maxsizeEdit.setMinimum(1) self.maxsizeEdit.setMaximum(300000) self.maxsizeEdit.setToolTip( wraptip("How many megabytes will you download at maximum?")) self.maxsizeEdit.setValue(self.settings.value('maxsize', 5)) self.settingsLayout.addRow('Maximum size', self.maxsizeEdit) # Expand Box self.autoexpandCheckbox = QCheckBox("Expand new nodes", self) self.autoexpandCheckbox.setToolTip( wraptip( "Check to automatically expand new nodes when fetching data. Disable for big queries to speed up the process." )) self.settingsLayout.addRow(self.autoexpandCheckbox) self.autoexpandCheckbox.setChecked( str(self.settings.value('expand', 'true')) == 'true') # Log Settings self.logCheckbox = QCheckBox("Log all requests", self) self.logCheckbox.setToolTip( wraptip( "Check to see every request in the status log; uncheck to hide request messages." )) self.settingsLayout.addRow(self.logCheckbox) self.logCheckbox.setChecked( str(self.settings.value('logrequests', 'true')) == 'true') # Clear setttings self.clearCheckbox = QCheckBox("Clear settings when closing.", self) self.settings.beginGroup("GlobalSettings") self.clearCheckbox.setChecked( str(self.settings.value('clearsettings', 'false')) == 'true') self.settings.endGroup() self.clearCheckbox.setToolTip( wraptip( "Check to clear all settings and access tokens when closing Facepager. You should check this on public machines to clear credentials." )) self.settingsLayout.addRow(self.clearCheckbox) # Style self.styleEdit = QComboBox(self) self.styleEdit.setToolTip(wraptip("Choose the styling of Facepager.")) styles = [x for x in QStyleFactory.keys() if x != "Windows"] styles = ['<default>'] + styles self.styleEdit.insertItems(0, styles) self.styleEdit.setCurrentText(self.settings.value( 'style', '<default>')) self.styleEdit.currentIndexChanged.connect(self.setStyle) self.settingsLayout.addRow('Style', self.styleEdit) # # Components # #main tree treetoolbar = QToolBar(self) treetoolbar.setToolButtonStyle(Qt.ToolButtonTextBesideIcon) treetoolbar.setIconSize(QSize(16, 16)) treetoolbar.addActions(self.guiActions.treeActions.actions()) dataLayout.addWidget(treetoolbar) self.tree = DataTree(self.mainWidget) self.tree.nodeSelected.connect(self.guiActions.treeNodeSelected) self.tree.logmessage.connect(self.logmessage) self.tree.showprogress.connect(self.showprogress) self.tree.hideprogress.connect(self.hideprogress) self.tree.stepprogress.connect(self.stepprogress) dataLayout.addWidget(self.tree) #right sidebar - toolbar detailtoolbar = QToolBar(self) detailtoolbar.setToolButtonStyle(Qt.ToolButtonTextBesideIcon) detailtoolbar.setIconSize(QSize(16, 16)) detailtoolbar.addActions(self.guiActions.detailActions.actions()) detailLayout.addWidget(detailtoolbar) #right sidebar - json viewer self.detailTree = DictionaryTree(self.mainWidget, self.apiWindow) detailLayout.addWidget(self.detailTree) #right sidebar - column setup detailGroup = QGroupBox("Custom Table Columns (one key per line)") detailSplitter.addWidget(detailGroup) groupLayout = QVBoxLayout() detailGroup.setLayout(groupLayout) self.fieldList = QTextEdit() self.fieldList.setLineWrapMode(QTextEdit.NoWrap) self.fieldList.setWordWrapMode(QTextOption.NoWrap) self.fieldList.acceptRichText = False self.fieldList.clear() self.fieldList.append('name') self.fieldList.append('message') self.fieldList.setPlainText( self.settings.value('columns', self.fieldList.toPlainText())) groupLayout.addWidget(self.fieldList) #column setup toolbar columntoolbar = QToolBar(self) columntoolbar.setToolButtonStyle(Qt.ToolButtonTextBesideIcon) columntoolbar.setIconSize(QSize(16, 16)) columntoolbar.addActions(self.guiActions.columnActions.actions()) groupLayout.addWidget(columntoolbar) #Requests/Apimodules self.RequestTabs = QTabWidget() moduleslayout.addWidget(self.RequestTabs) self.RequestTabs.addTab(YoutubeTab(self), "YouTube") self.RequestTabs.addTab(TwitterTab(self), "Twitter") self.RequestTabs.addTab(TwitterStreamingTab(self), "Twitter Streaming") self.RequestTabs.addTab(FacebookTab(self), "Facebook") self.RequestTabs.addTab(AmazonTab(self), "Amazon") self.RequestTabs.addTab(GenericTab(self), "Generic") module = self.settings.value('module', False) tab = self.getModule(module) if tab is not None: self.RequestTabs.setCurrentWidget(tab) #Fetch settings #-Level self.levelEdit = QSpinBox(self.mainWidget) self.levelEdit.setMinimum(1) self.levelEdit.setToolTip( wraptip( "Based on the selected nodes, only fetch data for nodes and subnodes of the specified level (base level is 1)" )) fetchsettings.addRow("Node level", self.levelEdit) #-Selected nodes self.allnodesCheckbox = QCheckBox(self) self.allnodesCheckbox.setCheckState(Qt.Unchecked) self.allnodesCheckbox.setToolTip( wraptip( "Check if you want to fetch data for all nodes. This helps with large datasets because manually selecting all nodes slows down Facepager." )) fetchsettings.addRow("Select all nodes", self.allnodesCheckbox) #-Empty nodes self.emptyCheckbox = QCheckBox(self) self.emptyCheckbox.setCheckState(Qt.Unchecked) self.emptyCheckbox.setToolTip( wraptip("Check if you want process only empty nodes.")) fetchsettings.addRow("Only empty nodes", self.emptyCheckbox) #Object types self.typesEdit = QLineEdit('offcut') self.typesEdit.setToolTip( wraptip( "Skip nodes with these object types, comma separated list. Normally this should not be changed." )) fetchsettings.addRow("Exclude object types", self.typesEdit) #-Continue pagination self.resumeCheckbox = QCheckBox(self) self.resumeCheckbox.setCheckState(Qt.Unchecked) self.resumeCheckbox.setToolTip( wraptip( "Check if you want to continue collection after fetching was cancelled or nodes were skipped. The last fetched offcut or data node is used to determine the pagination value. Nodes are skipped if no pagination value can be found. Nodes without children having status fetched(200) are processed anyway." )) fetchsettings.addRow("Resume collection", self.resumeCheckbox) # Thread Box self.threadsEdit = QSpinBox(self) self.threadsEdit.setMinimum(1) self.threadsEdit.setMaximum(40) self.threadsEdit.setToolTip( wraptip( "The number of concurrent threads performing the requests. Higher values increase the speed, but may result in API-Errors/blocks" )) fetchsettings.addRow("Parallel Threads", self.threadsEdit) # Speed Box self.speedEdit = QSpinBox(self) self.speedEdit.setMinimum(1) self.speedEdit.setMaximum(60000) self.speedEdit.setValue(200) self.speedEdit.setToolTip( wraptip( "Limit the total amount of requests per minute (calm down to avoid API blocking)" )) fetchsettings.addRow("Requests per minute", self.speedEdit) #Error Box self.errorEdit = QSpinBox(self) self.errorEdit.setMinimum(1) self.errorEdit.setMaximum(100) self.errorEdit.setValue(10) self.errorEdit.setToolTip( wraptip( "Set the number of consecutive errors after which fetching will be cancelled. Please handle with care! Continuing with erroneous requests places stress on the servers." )) fetchsettings.addRow("Maximum errors", self.errorEdit) #More button = QPushButton(QIcon(":/icons/more.png"), "", self.mainWidget) button.setToolTip( wraptip( "Can't get enough? Here you will find even more settings!")) # button.setMinimumSize(QSize(120,40)) # button.setIconSize(QSize(32,32)) button.clicked.connect(self.guiActions.actionSettings.trigger) fetchsettings.addRow("More settings", button) #Fetch data #-button f = QFont() f.setPointSize(11) button = QPushButton(QIcon(":/icons/fetch.png"), "Fetch Data", self.mainWidget) button.setToolTip( wraptip( "Fetch data from the API with the current settings. If you click the button with the control key pressed, a browser window is opened instead." )) button.setMinimumSize(QSize(120, 40)) button.setIconSize(QSize(32, 32)) button.clicked.connect(self.guiActions.actionQuery.trigger) button.setFont(f) fetchdata.addWidget(button, 1) #-timer button button = QToolButton(self.mainWidget) button.setIcon(QIcon(":/icons/timer.png")) button.setMinimumSize(QSize(40, 40)) button.setIconSize(QSize(25, 25)) button.clicked.connect(self.guiActions.actionTimer.trigger) fetchdata.addWidget(button, 1) #Status detailGroup = QGroupBox("Status Log") groupLayout = QVBoxLayout() detailGroup.setLayout(groupLayout) statusLayout.addWidget(detailGroup, 1) self.loglist = QTextEdit() self.loglist.setLineWrapMode(QTextEdit.NoWrap) self.loglist.setWordWrapMode(QTextOption.NoWrap) self.loglist.acceptRichText = False self.loglist.clear() groupLayout.addWidget(self.loglist)
def changeStyle(self, styleName): QApplication.setStyle(QStyleFactory.create(styleName)) self.changePalette()
# Qt5: this is gone: from PySide2.QtGui import QMacStyle from PySide2.QtWidgets import QApplication, QLabel, QStyleFactory from PySide2.QtCore import QObject import unittest from helper import UsesQApplication QMacStyle = type(QStyleFactory.create('Macintosh')) class QMacStyleTest(UsesQApplication): def testWidgetStyle(self): w = QLabel('Hello') self.assertTrue(isinstance(w.style(), QMacStyle)) if __name__ == '__main__': unittest.main()
def setUp(self): UsesQApplication.setUp(self) self.QMacStyle = type(QStyleFactory.create('Macintosh'))
class MainWindow(QMainWindow): def __init__(self): super(MainWindow, self).__init__() self.ui = Ui_MainWindow() self.ui.setupUi(self) # print available styles print(QStyleFactory.keys()) # Signals self.ui.my_button.clicked.connect(self.test) def test(self): print("test!") if __name__ == "__main__": app = QApplication(sys.argv) style = QStyleFactory.create('Fusion') app.setStyle(style) window = MainWindow() window.show() sys.exit(app.exec_())
def _load_theme_from_settings(app: QApplication): theme = locator.get_static("SettingsService").get_theme() if theme and theme in QStyleFactory.keys(): app.setStyle(theme)
def set_application_style(): MainApplication.setStyle(QStyleFactory.create("Fusion"))
def __init__(self, parent=None): super(WidgetGallery, self).__init__(parent) # System State self.adc_scale = 1 self.adc_decimation = 1 self.offset = 0 self.samples = None self.serial_state = None self.serial_state_timeout = time.time() self.originalPalette = QApplication.palette() QApplication.setStyle(QStyleFactory.create("Fusion")) serial_label = QLabel() serial_label.setText("Serial Port:") self.Serial_Handel = serial.Serial() self.Serial_Handel.timeout = 0 self.Serial_Handel.baudrate = 115200 self.serial_lock = QtCore.QMutex() self.serial_thread = SerialThread(self.Serial_Handel, self.serial_lock, self.command_callback) self.serial_thread.start() self.Serial_Port_Box = SelfPopulatingComboBox() self.Serial_Port_Box.view().setMinimumWidth(30) self.update_ports() self.Serial_Port_Box.setCurrentIndex(0) self.port_list = dict() self.Serial_Port_Box.popupAboutToBeShown.connect(self.update_ports) self.Serial_Port_Box.currentIndexChanged.connect(self.selected_port) # create plot self.main_plot = pyqtgraph.PlotWidget() self.curve = self.main_plot.plot() self.curve.setPen((200, 200, 100)) self.main_plot.getAxis('left').setGrid(255) self.main_plot.getAxis('bottom').setGrid(255) self.curve.getViewBox().setMouseMode(pyqtgraph.ViewBox.RectMode) self.ControlGroupBox = QGroupBox("Controls") self.create_control_group_box() topLayout = QHBoxLayout() topLayout.addStretch(1) topLayout.addWidget(serial_label) topLayout.addWidget(self.Serial_Port_Box, 2) self.label_font = QtGui.QFont("Times", 600, QtGui.QFont.Bold) self.bottom_layout = QHBoxLayout() self.bottom_layout.addStretch(1) measurement_label = QLabel() measurement_label.setText("Measurements:") measurement_label.setFont(self.label_font) self.measurements_list = list() self.measurements_functions = [ measurements.meas_pk_pk, measurements.meas_rms, measurements.meas_average, None ] for i in range(4): print("{}: N/A".format(i + 1)) meas_n = QLabel() meas_n.setText("{}: N/A".format(i + 1)) meas_n.setAlignment(QtCore.Qt.AlignLeft) self.measurements_list.append(meas_n) self.bottom_layout.addWidget(meas_n, alignment=QtCore.Qt.AlignLeft) mainLayout = QGridLayout() mainLayout.addLayout(topLayout, 0, 0, 1, 2) mainLayout.addWidget(self.main_plot, 1, 0, 2, 1) mainLayout.addWidget(self.ControlGroupBox, 1, 1, 2, 1) mainLayout.addLayout(self.bottom_layout, 3, 0, 1, 2, alignment=QtCore.Qt.AlignLeft) mainLayout.setRowMinimumHeight(3, 20) mainLayout.setRowStretch(1, 1) mainLayout.setRowStretch(2, 1) mainLayout.setColumnStretch(0, 10) mainLayout.setColumnStretch(1, 1) self.cent_widget = QWidget(self) self.setCentralWidget(self.cent_widget) self.cent_widget.setLayout(mainLayout) self.setWindowTitle("Probe-Scope Acquisition")
def __init__(self, nrows=1, ncols=1, **kwargs): matplotlib.use('Qt5Agg') qapp = QtWidgets.QApplication.instance() if qapp is None: qapp = QtWidgets.QApplication(sys.argv) self.qapp = qapp super().__init__() self._main = QtWidgets.QWidget() self.setStyle(QStyleFactory.create('Fusion')) self.setCentralWidget(self._main) self.layout = QGridLayout(self._main) marker_kw = {} for k in marker_default_params.keys(): if k in kwargs.keys(): marker_kw[k] = kwargs.pop(k) title = kwargs.pop('title', None) icon = kwargs.pop('icon', None) if icon != None: self.setWindowIcon(QtGui.QIcon(str(icon))) marker_kw['interactive'] = kwargs.pop('interactive', True) marker_kw['top_axes'] = kwargs.pop('top_axes', None) marker_kw['link_all'] = kwargs.pop('link_all', False) self.single_trace = kwargs.pop('single_trace', False) subplot_kw = kwargs.pop('subplot_kw', {}) sharex = kwargs.pop('sharex', False) sharey = kwargs.pop('sharey', False) gridspec_kw = kwargs.pop('gridspec_kw', None) self.fig = plt.figure(**kwargs) self.axes_grid = self.fig.subplots(nrows, ncols, squeeze=False, sharex=False, sharey=False, subplot_kw=subplot_kw, gridspec_kw=gridspec_kw) self.axes = self.axes_grid.flatten() self.nrows = nrows self.ncols = ncols self.canvas = self.fig.canvas self.canvas.mpl_disconnect(self.canvas.manager.key_press_handler_id) self.canvas.manager.show = self._show self.layout.addWidget(self.canvas, 0, 0, (self.nrows * self.ncols) + 1, 1) self.toolbar = NavigationToolbar(self.canvas, self, coordinates=False) self.build_toolbar() self.addToolBar(self.toolbar) self.fig.canvas.toolbar = self.toolbar self.canvas.setFocusPolicy(QtCore.Qt.ClickFocus) self.canvas.setFocus() p = self.palette() p.setColor(self.backgroundRole(), Qt.white) self.setPalette(p) title = 'Figure {}'.format( self.fig.canvas.manager.num) if title == None else title self.setWindowTitle(title) self._drop_event_handler = None self.fig.marker_enable(**marker_kw) self.fig.qapp = self.qapp self.fig.app = self self.draw_updates = False self.axes_cb_group = [] self.current_data_format = None self.data_format_options = None for i, ax in enumerate(self.axes): ax_cb = AxesCheckBoxGroup( self, ax, "Axes {},{}".format(i // self.nrows, i % self.nrows)) self.axes_cb_group.append(ax_cb)
def testSetStyleOwnership(self): style = QStyleFactory.create(QStyleFactory.keys()[0]) self.assertEqual(sys.getrefcount(style), 2) QApplication.instance().setStyle(style) self.assertEqual(sys.getrefcount(style), 3)
def __init__(self, style=None): super(Style, self).__init__(style if style else QStyleFactory.create('Fusion')) self._qss = self._load()
## ## GNU General Public License Usage ## Alternatively, this file may be used under the terms of the GNU ## General Public License version 3 as published by the Free Software ## Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT ## included in the packaging of this file. Please review the following ## information to ensure the GNU General Public License requirements will ## be met: https://www.gnu.org/licenses/gpl-3.0.html. ## ## $QT_END_LICENSE$ ## ############################################################################# # Qt5: this is gone: from PySide2.QtGui import QMacStyle from PySide2.QtWidgets import QApplication, QLabel, QStyleFactory from PySide2.QtCore import QObject import unittest from helper import UsesQApplication QMacStyle = type(QStyleFactory.create('Macintosh')) class QMacStyleTest(UsesQApplication): def testWidgetStyle(self): w = QLabel('Hello') self.assertTrue(isinstance(w.style(), QMacStyle)) if __name__ == '__main__': unittest.main()
self.tabs.addTab(self.web_tab, self.web_tab.title) self.setCentralWidget(self.tabs) self.ds = DataSource() self.resize(settings.value('main/size', QSize(640, 480))) self.move(settings.value('main/pos', QPoint(200, 200))) def closeEvent(self, event): self.rss.finish() self.twidget.finish() self.t2widget.finish() settings = QSettings('dreamix Studio', 'rt-stats') settings.setValue('main/size', self.size()) settings.setValue('main/pos', self.pos()) settings.setValue('main/rss/splitter', self.rss.splitter.saveState()) settings.setValue('main/new/splitter', self.twidget.splitter.saveState()) settings.setValue('main/new/tree', self.twidget.list.header().saveState()) settings.setValue('main/update/splitter', self.t2widget.splitter.saveState()) event.accept() if __name__ == "__main__": app = QApplication(sys.argv) QApplication.setStyle(QStyleFactory.create('Fusion')) window = MainWindow() window.show() sys.exit(app.exec_())
button = self.window.findChild(QObject, 'button') # Conectando o signal a um slot. button.clicked.connect(self.on_button_clicked) def on_button_clicked(self): if self.text_field.property('text'): self.label.setProperty('text', self.text_field.property('text')) else: self.label.setProperty('text', 'Digite algo no campo de texto :)') if __name__ == "__main__": import sys styles = QStyleFactory.keys() print('Estilos disponÃveis:', styles) # Aplicando estilo. # Testado no Windows e funcionou. # sys.argv += ['--style', 'Default'] # sys.argv += ['--style', 'Fusion'] # sys.argv += ['--style', 'Imagine'] # sys.argv += ['--style', 'Material'] # sys.argv += ['--style', 'Universal'] # sys.argv += ['--style', 'Windows'] # sys.argv += ['--style', 'org.kde.desktop'] # ou # environ['QT_QUICK_CONTROLS_STYLE'] = 'Default' # environ['QT_QUICK_CONTROLS_STYLE'] = 'Fusion'