def paint(self, painter, option, index): option = QStyleOptionViewItem(option) # copy option self.initStyleOption(option, index) style = option.widget.style() if option.widget else QApplication.style() doc = QTextDocument() doc.setHtml(option.text) # painting item without text option.text = "" style.drawControl(QStyle.CE_ItemViewItem, option, painter) ctx = QAbstractTextDocumentLayout.PaintContext() # Hilight text if item is selected if option.state & QStyle.State_Selected: ctx.palette.setColor(QPalette.Text, option.palette.color(QPalette.Active, QPalette.HighlightedText)) textRect = style.subElementRect(QStyle.SE_ItemViewItemText, option) painter.save() painter.translate(textRect.topLeft()) painter.setClipRect(textRect.translated(-textRect.topLeft())) doc.documentLayout().draw(painter, ctx) painter.restore()
def _paint_checkbox(self, style, painter): if hasattr(QSysInfo, 'MacintoshVersion') and \ QSysInfo.MacintoshVersion >= QSysInfo.MV_10_9 and \ style.state & QStyle.State_Enabled: self._paint_checkbox_osx_workaround(style, painter) else: QApplication.style().drawControl( QStyle.CE_CheckBox, style, painter)
def paint(self, painter, option, index): """ Draw button in cell. """ opts = QStyleOptionButton() opts.state |= QStyle.State_Active opts.state |= QStyle.State_Enabled if QT_VERSION_STR[0] == '4': opts.state |= (QStyle.State_Sunken if self._isMousePressed else QStyle.State_Raised) elif QT_VERSION_STR[0] == '5': # When raised in PyQt5, white text cannot be seen on white background. # Should probably fix this by initializing form styled button, but for now I'll just sink it all the time. opts.state |= QStyle.State_Sunken opts.rect = option.rect opts.text = self.text QApplication.style().drawControl(QStyle.CE_PushButton, opts, painter)
def paint(self, painter, option, index): """Re-implemented paint method""" item = index.internalPointer() col = index.column() if not item.parent and (col == 3 or col == 4): s = QStyleOptionButton() checkbox_rect = QApplication.style(). \ subElementRect(QStyle.SE_CheckBoxIndicator, option) s.rect = option.rect center_offset = s.rect.width() / 2 - checkbox_rect.width() / 2 s.rect.adjust(center_offset, 0, 0, 0) if col == 3: if not item.doing_transaction(): s.state = QStyle.State_Enabled if item.logging_started(): s.state |= QStyle.State_On if col == 4: s.state = QStyle.State_Enabled if item.writing_to_file(): s.state |= QStyle.State_On self._paint_checkbox(s, painter) else: super(CheckboxDelegate, self).paint(painter, option, index)
def pixmap(name, size, mode, state): """Returns a (possibly cached) pixmap of the name and size with the default text color. The state argument is ignored for now. """ if mode == QIcon.Selected: color = QApplication.palette().highlightedText().color() else: color = QApplication.palette().text().color() key = (name, size.width(), size.height(), color.rgb(), mode) try: return _pixmaps[key] except KeyError: i = QImage(size, QImage.Format_ARGB32_Premultiplied) i.fill(0) painter = QPainter(i) # render SVG symbol QSvgRenderer(os.path.join(__path__[0], name + ".svg")).render(painter) # recolor to text color painter.setCompositionMode(QPainter.CompositionMode_SourceIn) painter.fillRect(i.rect(), color) painter.end() # let style alter the drawing based on mode, and create QPixmap pixmap = QApplication.style().generatedIconPixmap(mode, QPixmap.fromImage(i), QStyleOption()) _pixmaps[key] = pixmap return pixmap
def main(): """Main Loop.""" APPNAME = str(__package__ or __doc__)[:99].lower().strip().replace(" ", "") if not sys.platform.startswith("win") and sys.stderr.isatty(): def add_color_emit_ansi(fn): """Add methods we need to the class.""" def new(*args): """Method overload.""" if len(args) == 2: new_args = (args[0], copy(args[1])) else: new_args = (args[0], copy(args[1]), args[2:]) if hasattr(args[0], 'baseFilename'): return fn(*args) levelno = new_args[1].levelno if levelno >= 50: color = '\x1b[31;5;7m\n ' # blinking red with black elif levelno >= 40: color = '\x1b[31m' # red elif levelno >= 30: color = '\x1b[33m' # yellow elif levelno >= 20: color = '\x1b[32m' # green elif levelno >= 10: color = '\x1b[35m' # pink else: color = '\x1b[0m' # normal try: new_args[1].msg = color + str(new_args[1].msg) + ' \x1b[0m' except Exception as reason: print(reason) # Do not use log here. return fn(*new_args) return new # all non-Windows platforms support ANSI Colors so we use them log.StreamHandler.emit = add_color_emit_ansi(log.StreamHandler.emit) log.basicConfig(level=-1, format="%(levelname)s:%(asctime)s %(message)s") log.getLogger().addHandler(log.StreamHandler(sys.stderr)) log.info(__doc__) try: os.nice(19) # smooth cpu priority libc = cdll.LoadLibrary('libc.so.6') # set process name buff = create_string_buffer(len(APPNAME) + 1) buff.value = bytes(APPNAME.encode("utf-8")) libc.prctl(15, byref(buff), 0, 0, 0) except Exception as reason: log.warning(reason) signal.signal(signal.SIGINT, signal.SIG_DFL) # CTRL+C work to quit app app = QApplication(sys.argv) app.setApplicationName(APPNAME) app.setOrganizationName(APPNAME) app.setOrganizationDomain(APPNAME) app.instance().setQuitOnLastWindowClosed(False) # no quit on dialog close icon = QIcon(app.style().standardPixmap(QStyle.SP_FileIcon)) app.setWindowIcon(icon) win = MainWindow(icon) win.show() log.info('Total Maximum RAM Memory used: ~{} MegaBytes.'.format(int( resource.getrusage(resource.RUSAGE_SELF).ru_maxrss * resource.getpagesize() / 1024 / 1024 if resource else 0))) sys.exit(app.exec_())
def get_context_menu(self) -> QMenu: """ Create the context menu. It shows up on left click. Note: icons will not be displayed on every GNU/Linux distributions, it depends on the graphical environment. """ style = QApplication.style() menu = QMenu() menu.addAction( style.standardIcon(QStyle.SP_FileDialogInfoView), Translator.get("SETTINGS"), self.application.show_settings, ) menu.addSeparator() menu.addAction( style.standardIcon(QStyle.SP_MessageBoxQuestion), Translator.get("HELP"), self.application.open_help, ) menu.addSeparator() menu.addAction( style.standardIcon(QStyle.SP_DialogCloseButton), Translator.get("QUIT"), self.application.quit, ) return menu
def paint(self, painter, option, index): self.initStyleOption(option, index) style = QApplication.style() doc = QTextDocument() if index.column() in (NetworkTableModel.columns_types.index('address'), NetworkTableModel.columns_types.index('port'), NetworkTableModel.columns_types.index('api')): doc.setHtml(option.text) else: doc.setPlainText(option.text) option.text = "" style.drawControl(QStyle.CE_ItemViewItem, option, painter) ctx = QAbstractTextDocumentLayout.PaintContext() text_rect = style.subElementRect(QStyle.SE_ItemViewItemText, option) painter.save() painter.translate(text_rect.topLeft()) painter.setClipRect(text_rect.translated(-text_rect.topLeft())) doc.documentLayout().draw(painter, ctx) painter.restore()
def sizeHint(self, option, index): """ Public method to get a size hint for the specified list item. @param option style option used for painting (QStyleOptionViewItem) @param index model index of the item (QModelIndex) @return size hint (QSize) """ if not self.__rowHeight: opt = QStyleOptionViewItem(option) self.initStyleOption(opt, index) widget = opt.widget style = widget.style() if widget is not None else QApplication.style() padding = style.pixelMetric(QStyle.PM_FocusFrameHMargin) + 1 titleFont = opt.font titleFont.setBold(True) titleFont.setPointSize(titleFont.pointSize() + 1) self.__padding = ( padding if padding > GreaseMonkeyConfigurationListDelegate.MinPadding else GreaseMonkeyConfigurationListDelegate.MinPadding ) titleMetrics = QFontMetrics(titleFont) self.__rowHeight = ( 2 * self.__padding + opt.fontMetrics.leading() + opt.fontMetrics.height() + titleMetrics.height() ) return QSize(GreaseMonkeyConfigurationListDelegate.ItemWidth, self.__rowHeight)
def paint(self, painter, option, index): """ Paint a checkbox without the label. """ checked = bool(index.model().data(index, Qt.DisplayRole)) opts = QStyleOptionButton() opts.state |= QStyle.State_Active if index.flags() & Qt.ItemIsEditable: opts.state |= QStyle.State_Enabled else: opts.state |= QStyle.State_ReadOnly if checked: opts.state |= QStyle.State_On else: opts.state |= QStyle.State_Off opts.rect = self.getCheckBoxRect(option) QApplication.style().drawControl(QStyle.CE_CheckBox, opts, painter)
def paint(self, painter, option, index): self.initStyleOption(option, index) foreground = index.data(Qt.ForegroundRole) font = index.data(Qt.FontRole) style = QApplication.style() doc = QTextDocument() if index.column() == HistoryTableModel.columns_types.index('pubkey'): doc.setHtml(option.text) else: doc.setPlainText(option.text) option.text = "" style.drawControl(QStyle.CE_ItemViewItem, option, painter) ctx = QAbstractTextDocumentLayout.PaintContext() if foreground: if foreground.isValid(): ctx.palette.setColor(QPalette.Text, foreground) if font: doc.setDefaultFont(font) text_rect = style.subElementRect(QStyle.SE_ItemViewItemText, option) painter.save() painter.translate(text_rect.topLeft()) painter.setClipRect(text_rect.translated(-text_rect.topLeft())) doc.documentLayout().draw(painter, ctx) painter.restore()
def __init__(self, destination, origins, parent=None): """Init class.""" super(Backuper, self).__init__(parent) self.setWindowTitle(__doc__) self.setWindowIcon( QIcon(QApplication.style().standardPixmap(QStyle.SP_DriveFDIcon))) self.setWindowFlags(Qt.FramelessWindowHint) self.setCancelButton(None) self._time, self._date = time.time(), datetime.now().isoformat()[:-7] self.destination, self.origins = destination, origins self.template = """<h3>Copia de Seguridad BackUp</h3><hr><table> <tr><td><b>Desde:</b></td> <td>{}</td> <tr><td><b>Hacia: </b></td> <td>{}</td> <tr> <tr><td><b>Tiempo de Inicio:</b></td> <td>{}</td> <tr><td><b>Tiempo Actual:</b></td> <td>{}</td> <tr> <tr><td><b>Tiempo Transcurrido:</b></td> <td>{}</td> <tr><td><b>Faltante:</b></td> <td>{}</td> <tr> <tr><td><b>Porcentaje:</b></td> <td>{}%</td></table><hr> <i>Por favor no toque nada hasta que termine, proceso trabajando</i>""" self.setStyleSheet(CSS_STYLE) self.show() self.center() self.setValue(0) self.setLabelText(self.template) self.make_backup()
def paint(self, painter, option, index): options = QStyleOptionViewItem(option) item = index.data(Qt.UserRole) if isinstance(item, (CommentItem, ChangeItem)): options.decorationAlignment = Qt.AlignHCenter self.initStyleOption(options,index) if options.widget is None: style = QApplication.style() else: style = options.widget.style() doc = QTextDocument() doc.setHtml(options.text) options.text = "" style.drawControl(QStyle.CE_ItemViewItem, options, painter) ctx = QAbstractTextDocumentLayout.PaintContext() # Highlighting text if item is selected #if (optionV4.state & QStyle::State_Selected) #ctx.palette.setColor(QPalette::Text, optionV4.palette.color(QPalette::Active, QPalette::HighlightedText)) textRect = style.subElementRect(QStyle.SE_ItemViewItemText, options) painter.save() painter.translate(textRect.topLeft()) painter.setClipRect(textRect.translated(-textRect.topLeft())) doc.documentLayout().draw(painter, ctx) painter.restore()
def __init__(self, parent, canvas): QToolBar.__init__(self, parent) self._canvas = canvas self.addAction(QApplication.style().standardIcon(QStyle.SP_DialogSaveButton), "Save", canvas.saveImg) self.addAction("Zoom +", canvas.zoomUp) self.addAction("Zoom -", canvas.zoomDown) self.addAction("Configure", canvas.configure)
def paint(self, painter, option, index): self.initStyleOption(option, index) # No idea why, but this cast is required if we want to have access to the V4 valuess option = QStyleOptionViewItem(option) if (index.column() == 1) and (option.state & QStyle.State_Selected): cboption = QStyleOptionComboBox() cboption.rect = option.rect # On OS X (with Qt4.6.0), adding State_Enabled to the flags causes the whole drawing to # fail (draw nothing), but it's an OS X only glitch. On Windows, it works alright. cboption.state |= QStyle.State_Enabled QApplication.style().drawComplexControl(QStyle.CC_ComboBox, cboption, painter) painter.setBrush(option.palette.text()) rect = QRect(option.rect) rect.setLeft(rect.left()+4) painter.drawText(rect, Qt.AlignLeft, option.text) else: super().paint(painter, option, index)
def getCheckBoxRect(self, option): """Calculate the size and position of the checkbox.""" cb_rect = QApplication.style().subElementRect( QStyle.SE_CheckBoxIndicator, QStyleOptionButton(), None) x = option.rect.x() + option.rect.width()/2 - cb_rect.width()/2 y = option.rect.y() + option.rect.height()/2 - cb_rect.height()/2 return QRect(QPoint(x, y), cb_rect.size())
def __init__(self, parent, canvas): QToolBar.__init__(self, parent) self._canvas = canvas self.addAction( QApplication.style().standardIcon(QStyle.SP_DialogSaveButton), "Save", canvas.saveImg) self.addAction("Zoom +", canvas.zoomUp) self.addAction("Zoom -", canvas.zoomDown) self.addAction("Configure", canvas.configure)
def __init__(self, parent=None): """ Constructor @param parent reference to the parent widget (QWidget) """ super(E5MainWindow, self).__init__(parent) self.defaultStyleName = QApplication.style().objectName()
def __init__(self, app, w_path): super(TorWarnDialog, self).__init__(None) self.app = app self.network = app.daemon.network self.config = app.config self.tor_detected = False self.setMinimumSize(600, 350) app_name = 'Zcash Electrum' if constants.net.TESTNET: app_name += ' Testnet' app_name += f' {ELECTRUM_VERSION}' w_basename = os.path.basename(w_path) self.setWindowTitle(f'{app_name} - {w_basename}') vbox = QVBoxLayout(self) vbox.setSpacing(10) hbox = QHBoxLayout() vbox.addLayout(hbox) w_icon = QApplication.style().standardIcon(QStyle.SP_MessageBoxWarning) self.w_icn_lbl = QLabel() self.w_icn_lbl.setPixmap(w_icon.pixmap(36)) self.w_lbl = QLabel(self.network.TOR_WARN_MSG_QT) self.w_lbl.setOpenExternalLinks(True) hbox.addWidget(self.w_icn_lbl) hbox.addWidget(self.w_lbl) hbox.setSpacing(10) hbox.addStretch(1) vbox.addStretch(1) self.tor_auto_on_cb = QCheckBox(self.network.TOR_AUTO_ON_MSG) self.tor_auto_on_cb.setChecked(self.config.get('tor_auto_on', True)) vbox.addWidget(self.tor_auto_on_cb) def use_tor_auto_on(b): self.config.set_key('tor_auto_on', b, True) if not b: self.config.set_key('proxy', None, True) self.tor_auto_on_cb.clicked.connect(use_tor_auto_on) self.no_tor_btn = QPushButton(_('Continue without Tor')) self.no_tor_btn.clicked.connect(self.continue_without_tor) vbox.addWidget(self.no_tor_btn) self.detect_btn = QPushButton(_('Detect Tor again')) self.detect_btn.clicked.connect(self.detect_tor_again) vbox.addWidget(self.detect_btn) self.close_w_btn = QPushButton(_('Close wallet')) self.close_w_btn.clicked.connect(self.close_wallet) vbox.addWidget(self.close_w_btn) self.ok_btn = QPushButton(_('OK')) self.ok_btn.hide() self.ok_btn.clicked.connect(self.on_ok) vbox.addWidget(self.ok_btn)
def hitText(self, point): """only change if text is clicked""" style = QStyle.SE_CheckBoxContents option = QStyleOptionButton() self.initStyleOption(option) ret = QApplication.style().subElementRect(style, option, self).contains(point) return ret
def __updateMaxmize(self): pWindow = self.window() if pWindow.isWindow() == True: bMaximize = pWindow.isMaximized() if bMaximize == 0: self.m_pMaximizeButton.setProperty("maximizeProperty", "restore") else: self.m_pMaximizeButton.setProperty("maximizeProperty", "maximize") self.m_pMaximizeButton.setStyle(QApplication.style())
def onMuteButtonClicked(self, btnChecked): self.muteClickedTime = time.time() if btnChecked: self.muteSignal.emit() self.muteButton.setText('Audio Disabled') self.muteButton.setIcon(QIcon(QApplication.style().standardIcon(QStyle.SP_MediaVolumeMuted))) else: self.unmuteSignal.emit() self.muteButton.setText('Audio Enabled') self.muteButton.setIcon(QIcon(QApplication.style().standardIcon(QStyle.SP_MediaVolume))) # if __name__ == "__main__": # logging.info("Starting application.") # app = QApplication(sys.argv) # mainWindow = MainWindow() # sys.exit(app.exec_())
def paint(self, painter, option, index): if index.column() == 2: button = QStyleOptionButton() r = option.rect # getting the rect of the cell x = r.left() y = r.top() w = r.width() h = r.height() button.rect = QRect(x, y, w, h) button.text = "X" button.state = QStyle.State_Enabled; QApplication.style().drawControl(QStyle.CE_PushButton, button, painter) else: QStyledItemDelegate.paint(self, painter, option, index)
def paint(self, painter, option, index): self.initStyleOption(option, index) # No idea why, but this cast is required if we want to have access to the V4 valuess option = QStyleOptionViewItem(option) if (index.column() == 1) and (option.state & QStyle.State_Selected): cboption = QStyleOptionComboBox() cboption.rect = option.rect # On OS X (with Qt4.6.0), adding State_Enabled to the flags causes the whole drawing to # fail (draw nothing), but it's an OS X only glitch. On Windows, it works alright. cboption.state |= QStyle.State_Enabled QApplication.style().drawComplexControl(QStyle.CC_ComboBox, cboption, painter) painter.setBrush(option.palette.text()) rect = QRect(option.rect) rect.setLeft(rect.left() + 4) painter.drawText(rect, Qt.AlignLeft, option.text) else: super().paint(painter, option, index)
def paint(self, QPainter, QStyleOptionViewItem, QModelIndex): opts = QStyleOptionProgressBar() opts.rect = QStyleOptionViewItem.rect opts.minimum = 0 opts.maximum = 100 percent = QModelIndex.model().data(QModelIndex, QtCore.Qt.DisplayRole) if not isinstance(percent, int): percent = 0 opts.progress = percent if percent == 0: opts.textVisible = False else: opts.textVisible = True opts.text = str(percent) + "%" QApplication.style().drawControl(QStyle.CE_ProgressBar, opts, QPainter)
def changeStyle(self, styleName): ''' :param styleName: :return: ''' QApplication.setStyle(QStyleFactory.create(styleName)) QApplication.setPalette(QApplication.style().standardPalette())
def apply_theme(self): """ Note: Call themes() and set_theme() before calling apply_theme(). """ # self.apply_qss() self.qt_gui_palette = QApplication.style().standardPalette() if self.theme_name == "default": qApp.setPalette(self.qt_gui_palette) return self.skin_meta: ThemeMetaData = self.themes()[self.theme_name] skin_file = Path(self.skin_meta.filename) if self.skin_meta.filename.endswith(".yaml"): with skin_file.open("r") as f: base16 = yaml.load(f.read()) self._qt_palette_per_base16(base16) else: parser = GWConfigParser() parser.parse_file(skin_file) base16 = {} # We'll load the Base16 section first (if there is one), because the # Skin section can refer to the base16 definitions. section = "Base16" if parser.has_section(section): for option, _ in parser.items(section): base16[option] = parser[section].getqcolor(option) if len(base16) != 16: raise GruntWurkConfigError( f"Expected 16 colors in the [Base16] section but only found {len(base16)}." ) self._qt_palette_per_base16(base16) section = "Skin" if parser.has_section(section): for option in parser.items(section): if option not in QPALETTE_SLUGS: LOG.warning( f"Skin theme '{self.theme_name}' refers to an element '{option}' that doesn't exist." ) self._qt_palette_per_conf(section, parser, base16) section = "Custom" if parser.has_section(section): for option in parser.items(section): if option not in self.custom_color_map: LOG.warning( f"Skin theme {self.theme_name} refers to an custom color '{option}' that doesn't exist." ) else: self.custom_color_map[option] = parser[ section].getcolor(option) LOG.info(f"Loaded skin theme '{self.theme_name}'") qApp.setPalette(self.qt_gui_palette)
def paint(self, painter, option, index): hasValue = True if (self.m_editorPrivate): property = self.m_editorPrivate.indexToProperty(index) if (property): hasValue = property.hasValue() opt = QStyleOptionViewItem(option) if ((self.m_editorPrivate and index.column() == 0) or not hasValue): property = self.m_editorPrivate.indexToProperty(index) if (property and property.isModified()): opt.font.setBold(True) opt.fontMetrics = QFontMetrics(opt.font) c = QColor() if (not hasValue and self.m_editorPrivate.markPropertiesWithoutValue()): c = opt.palette.color(QPalette.Dark) opt.palette.setColor(QPalette.Text, opt.palette.color(QPalette.BrightText)) else: c = self.m_editorPrivate.calculatedBackgroundColor( self.m_editorPrivate.indexToBrowserItem(index)) if (c.isValid() and (opt.features & QStyleOptionViewItem.Alternate)): c = c.lighter(112) if (c.isValid()): painter.fillRect(option.rect, c) opt.state &= ~QStyle.State_HasFocus if (index.column() == 1): item = self.m_editorPrivate.indexToItem(index) if (self.m_editedItem and (self.m_editedItem == item)): self.m_disablePainting = True super(QtPropertyEditorDelegate, self).paint(painter, opt, index) if (option.type): self.m_disablePainting = False opt.palette.setCurrentColorGroup(QPalette.Active) color = QApplication.style().styleHint(QStyle.SH_Table_GridLineColor, opt) painter.save() painter.setPen(QPen(color)) if (not self.m_editorPrivate or (not self.m_editorPrivate.lastColumn(index.column()) and hasValue)): if option.direction == Qt.LeftToRight: right = option.rect.right() else: right = option.rect.left() painter.drawLine(right, option.rect.y(), right, option.rect.bottom()) painter.restore()
def initToolBar(self): toolBar = self.addToolBar('ToolBar') style = QApplication.style() min_width = 64 btnFileNew = QToolButton(self) btnFileNew.setText('新建文档') btnFileNew.setMinimumWidth(min_width) btnFileNew.setIcon(style.standardIcon(QStyle.SP_FileIcon)) btnFileNew.setToolButtonStyle(Qt.ToolButtonTextUnderIcon) btnFileNew.clicked.connect(self.onFileNew) toolBar.addWidget(btnFileNew) btnFileOpen = QToolButton(self) btnFileOpen.setText('打开文档') btnFileOpen.setMinimumWidth(min_width) btnFileOpen.setIcon(style.standardIcon(QStyle.SP_DialogOpenButton)) btnFileOpen.setToolButtonStyle(Qt.ToolButtonTextUnderIcon) btnFileOpen.clicked.connect(self.onFileOpen) toolBar.addWidget(btnFileOpen) btnFileCloseAll = QToolButton(self) btnFileCloseAll.setText('关闭全部') btnFileCloseAll.setMinimumWidth(min_width) btnFileCloseAll.setIcon(style.standardIcon( QStyle.SP_DialogCloseButton)) btnFileCloseAll.setToolButtonStyle(Qt.ToolButtonTextUnderIcon) btnFileCloseAll.clicked.connect(self.onFileCloseAll) toolBar.addWidget(btnFileCloseAll) toolBar.addSeparator() btnEditCut = QToolButton(self) btnEditCut.setText('剪切') btnEditCut.setMinimumWidth(64) btnEditCut.setIcon(QIcon(':/ico/cut.png')) btnEditCut.setToolButtonStyle(Qt.ToolButtonTextUnderIcon) btnEditCut.clicked.connect(self.onEditCut) toolBar.addWidget(btnEditCut) btnEditCopy = QToolButton(self) btnEditCopy.setText('复制') btnEditCopy.setMinimumWidth(64) btnEditCopy.setIcon(QIcon(':/ico/copy.png')) btnEditCopy.setToolButtonStyle(Qt.ToolButtonTextUnderIcon) btnEditCopy.clicked.connect(self.onEditCopy) toolBar.addWidget(btnEditCopy) btnEditPaste = QToolButton(self) btnEditPaste.setText('粘贴') btnEditPaste.setMinimumWidth(64) btnEditPaste.setIcon(QIcon(':/ico/paste.png')) btnEditPaste.setToolButtonStyle(Qt.ToolButtonTextUnderIcon) btnEditPaste.clicked.connect(self.onEditPaste) toolBar.addWidget(btnEditPaste)
def paint(self, painter, option, index): if index.column() == 2: button = QStyleOptionButton() r = option.rect # getting the rect of the cell x = r.left() y = r.top() w = r.width() h = r.height() button.rect = QRect(x, y, w, h) button.text = "X" button.state = QStyle.State_Enabled QApplication.style().drawControl(QStyle.CE_PushButton, button, painter) else: QStyledItemDelegate.paint(self, painter, option, index)
def deleteRemoveThread(self): if self.removeThread: self.buttonRemoveKnot.setIcon(QApplication.style().standardIcon(QStyle.SP_TrashIcon)) for i in self.removeThread.labels: i.setParent(None) self.showError("The knot you wanted to remove has been succesfully annihilated", "Knot Deleted") if self.removeThread.deleted else self.showError("The knot you tried to remove encountered an error", "Deletion Error") if self.removeThread.isRunning(): self.removeThread.terminate() self.removeThread = None self.selected = None self.rootTree.update() self.update()
def sizeHint(self, option, index): menuopt = self._getMenuStyleOption(option, index) if option.widget is not None: style = option.widget.style() else: style = QApplication.style() return style.sizeFromContents( QStyle.CT_MenuItem, menuopt, menuopt.rect.size(), option.widget )
def get_checkbox_rect(self, option: QStyleOptionViewItem) -> QRect: check_box_style_option = QStyleOptionButton() check_box_rect = QApplication.style().subElementRect( QStyle.SE_CheckBoxIndicator, check_box_style_option, None) check_box_point = QPoint( option.rect.x() + option.rect.width() / 2 - check_box_rect.width() / 2, option.rect.y() + option.rect.height() / 2 - check_box_rect.height() / 2) return QRect(check_box_point, check_box_rect.size())
def __checkedStateChangedSlot(self): """ 复选框选中状态改变对应的槽函数 """ self.isChecked = self.checkBox.isChecked() # 发送信号 self.checkedStateChanged.emit(self, self.isChecked) # 更新属性和背景色 self.setProperty("isChecked", str(self.isChecked)) self.playlistNameLabel.setProperty("isChecked", str(self.isChecked)) self.playlistLenLabel.setProperty("isChecked", str(self.isChecked)) self.setStyle(QApplication.style())
def checkCurrentStyle(self): for action in self.styleActionGroup.actions(): styleName = action.data() candidate = QStyleFactory.create(styleName) if candidate is None: return if candidate.metaObject().className() == QApplication.style().metaObject().className(): action.trigger()
def __checkedStateChangedSlot(self): """ 复选框选中状态改变对应的槽函数 """ self.isChecked = self.checkBox.isChecked() # 发送信号 self.checkedStateChanged.emit(self, self.isChecked) # 更新属性和背景色 self.setProperty('isChecked', str(self.isChecked)) self.albumNameLabel.setProperty('isChecked', str(self.isChecked)) self.songerNameLabel.setProperty('isChecked', str(self.isChecked)) self.setStyle(QApplication.style())
def showAlbumInfoEditPanel(self): """ 显示专辑信息编辑面板 """ oldAlbumInfo = deepcopy(self.albumInfo) infoEditPanel = AlbumInfoEditPanel(self.albumInfo, self.window()) infoEditPanel.saveInfoSig.connect( lambda newAlbumInfo: self.__saveAlbumInfoSlot(oldAlbumInfo, newAlbumInfo) ) self.showAlbumInfoEditPanelSig.emit(infoEditPanel) infoEditPanel.setStyle(QApplication.style()) infoEditPanel.exec_()
def hitButton(self, point): """only change if checkbox is clicked""" style = QStyle.SE_CheckBoxIndicator option = QStyleOptionButton() self.initStyleOption(option) ret = QApplication.style().subElementRect(style, option, self).contains(point) # print(ret) return ret
def focusInEvent(self, e): """ 焦点进入时更换样式并取消提示文字 """ super().focusInEvent(e) # 必须有判断的一步,不然每次右击菜单执行完都会触发focusInEvent()导致菜单功能混乱 if self.property('noText') == 'true': self.clear() self.setProperty('noText', 'false') self.setStyle(QApplication.style()) self.pencilPic.setPixmap( QPixmap(r'resource\images\createPlaylistPanel\pencil_50_50.png'))
def __init__(self): super().__init__() self.setWindowTitle('设置窗口风格') horizontalLayout = QHBoxLayout() self.styleLabel = QLabel('设置窗口风格:') self.styleComboBox = QComboBox() self.styleComboBox.addItems(QStyleFactory.keys()) # 获取当前窗口的风格 print(QApplication.style().objectName()) index = self.styleComboBox.findText(QApplication.style().objectName(), QtCore.Qt.MatchFixedString) self.styleComboBox.setCurrentIndex(index) self.styleComboBox.activated[str].connect(self.handleStyleChanged) horizontalLayout.addWidget(self.styleLabel) horizontalLayout.addWidget(self.styleComboBox) self.setLayout(horizontalLayout)
def __init__(self, parent=None): super(QuickInstructions, self).__init__(parent) # self.setAttribute(Qt.WA_DeleteOnClose) # Deletes instance on window close self.setWindowTitle('pyIMD :: Quick instructions') self.display_on_startup = 2 self.resize(400, 370) self.setWindowIcon( QtGui.QIcon( resource_path( os.path.join( os.path.join("ui", "icons", "pyIMD_logo_icon.ico"))))) grid = QGridLayout() grid.setContentsMargins(5, 5, 5, 5) ok = QPushButton('Ok') ok.setIcon(QApplication.style().standardIcon( QStyle.SP_DialogApplyButton)) ok.setMaximumWidth(100) ok.clicked.connect(self.close) self.chk = QCheckBox('Display quick instructions at startup') self.chk.setFont(QFont('Arial', 9, QFont.Bold)) self.chk.setChecked(1) self.chk.clicked.connect(self.on_display_qi) self.quick_instructions = QTextEdit(self) self.quick_instructions.setText( '<h3>Quick Instructions</h3> ' 'Edit the settings first according to your experimental setup. Second select ' 'the directory containing your experimental data and determine the file name ' 'to measurement relationship as well as the measurement mode the data was ' 'recorded with.' '<br><br>Controls:' '<ul>' '<li><b>Ctrl+N (Cmd+N):</b> Create a new pyIMD project.' '</li>' '<li><b>Ctrl+O (Cmd+O):</b> Open an existing pyIMD project' '</li>' '<li><b>Ctrl+S (Cmd+S):</b> Save the current pyIMD project' '</li>' '<li><b>Ctrl+P (Cmd+P):</b> Open the settings dialog to change the project ' 'parameters</li></ul>' 'Hints:' '<ul><li>Create a pyIMD project for all your experiments first and save ' 'the pyIMD projects before running them individually. The projects can then ' 'be run sequentially using the batch mode (Batch processing tab).' '</li>' '<li>Select multiple data files holding the Ctrl button during selection after' 'clicking on <i>Select directory</i> or Ctrl+N.</li><' '</ul>' 'You can open this window any time from the Help menu.</ul>') self.quick_instructions.setReadOnly(1) self.quick_instructions.setFont(QFont('Arial', 9)) grid.addWidget(self.quick_instructions, 0, 0, 1, 0) grid.addWidget(ok, 1, 1) grid.addWidget(self.chk, 1, 0) self.setLayout(grid)
def __init__(self, parent=None): super(QuickInstructions, self).__init__(parent) # self.setAttribute(Qt.WA_DeleteOnClose) # Deletes instance on window close self.setWindowTitle('pyPOCQuant :: Quick instructions') self.setWindowFlags(Qt.WindowStaysOnTopHint) self._settings = QSettings("CSB & SCF", "pyPOCQuantUI") self.resize(400, 370) # self.setWindowIcon(QtGui.QIcon(resource_path(os.path.join(os.path.join("ui", "icons", # "icon.ico"))))) grid = QGridLayout() grid.setContentsMargins(5, 5, 5, 5) ok = QPushButton('Ok') ok.setIcon(QApplication.style().standardIcon( QStyle.SP_DialogApplyButton)) ok.setMaximumWidth(100) ok.clicked.connect(self.close) self.chk = QCheckBox('Display quick instructions at startup') self.chk.setFont(QFont('Arial', 9, QFont.Bold)) self.chk.setChecked( self._settings.value("quickstart/show_on_start", True, type=bool)) self.chk.clicked.connect(self.on_display_qi) self.quick_instructions = QTextEdit(self) self.quick_instructions.setText( '<h3>Quick Instructions</h3> ' 'Start by selecting the input folder where you have your images stored. ' 'Second select an image for display by clicking on the name in the list. ' 'Continue by drawing the sensor outline first and then the POCT outline.' 'Test the parameters by hitting the test button.' '<br><br>Controls:' '<ul>' '<li><b>Ctrl+N (Cmd+I):</b> Select the input dir' '</li>' '<li><b>Ctrl+O (Cmd+O):</b> Open an existing pyPOCQuant config' '</li>' '<li><b>Ctrl+S (Cmd+S):</b> Save the current pyPOCQuant config' '</li>' '<li><b>Ctrl+L (Cmd+L):</b> Show/hide pyPOCQuant log' '</li>' '</ul>' 'Hints:' '<ul><li>The image can be rotated, mirrored and zoomed if needed.' '</li>' '<li>Start with drawing a rectangle around the sensor (area with the bands)' 'Then fine tune the relative band positions (draggable lines).</li><' '</ul>' 'You can open this window any time from the Help menu.</ul>') self.quick_instructions.setReadOnly(1) self.quick_instructions.setFont(QFont('Arial', 9)) grid.addWidget(self.quick_instructions, 0, 0, 1, 0) grid.addWidget(ok, 1, 1) grid.addWidget(self.chk, 1, 0) self.setLayout(grid)
def __setWidgetEnable(self, isEnable: bool): """ 设置编辑框是否启用 """ self.albumCover.setEnabled(isEnable) self.saveButton.setEnabled(isEnable) self.tconLineEdit.setEnabled(isEnable) self.albumNameLineEdit.setEnabled(isEnable) self.albumSongerLineEdit.setEnabled(isEnable) for songInfoWidget in self.songInfoWidget_list: songInfoWidget.setLineEditEnable(isEnable) # 更新样式 self.setStyle(QApplication.style())
def fixComboBoxDropDownListSizeAdjustemnt(self, cb): scroll = 0 if cb.count() <= cb.maxVisibleItems() else QApplication.style().pixelMetric(QStyle.PM_ScrollBarExtent) iconWidth = cb.iconSize().width() max = 0 for i in range(cb.count()): width = cb.view().fontMetrics().width(cb.itemText(i)) if max < width: max = width QMessageBox.information(self, "info", "scroll: {0}, max: {1}, icon: {2}".format(scroll, max, iconWidth))
def addKnot(self): if self.entryAddKnot.text(): if not self.addThread: self.buttonAddKnot.setIcon(QApplication.style().standardIcon(QStyle.SP_DialogCancelButton)) self.addThread = visualAddThread(self, int(self.entryAddKnot.text())) self.addThread.finished.connect(self.deleteAddThread) self.addThread.start() else: self.deleteAddThread() else: self.showError("You have to enter a valid value to insert", "Insertion Error")
def startSearch(self): if self.entryVisualizeKnot.text(): if not self.searchThread: self.buttonVisualizeStartPause.setIcon(QApplication.style().standardIcon(QStyle.SP_MediaStop)) self.searchThread = visualSearchThread(self, int(self.entryVisualizeKnot.text())) self.searchThread.finished.connect(self.deleteSearchThread) self.searchThread.start() else: self.deleteSearchThread() else: self.showError("You have to enter a valid value to search for", "Search Error")
def checkCurrentStyle(self): for action in self.styleActionGroup.actions(): styleName = action.data() candidate = QStyleFactory.create(styleName) if candidate is None: return if candidate.metaObject().className() == QApplication.style( ).metaObject().className(): action.trigger()
def paintEvent(self, event): style = QApplication.style() opt = QStyleOptionComboBox() opt.rect = self.rect() self.initStyleOption(opt) painter = QPainter(self) painter.save() style.drawComplexControl(QStyle.CC_ComboBox, opt, painter) opt.currentText = self._encoder_path() style.drawControl(QStyle.CE_ComboBoxLabel, opt, painter) painter.restore()
def initUI(self): # Look and feel antiAliasedFont = QApplication.font() antiAliasedFont.setStyleStrategy(QFont.PreferAntialias) QApplication.setFont(antiAliasedFont) self.setWindowTitle('Open Chess') path = constants.RESOURCES_PATH + '/icon.png' self.setWindowIcon(QIcon(path)) # Geometry """This will make the window the correct aspect ratio""" screenGeo = QDesktopWidget().availableGeometry() idealWidth = constants.IDEAL_RESOLUTION['width'] idealHeight = constants.IDEAL_RESOLUTION['height'] # TODO: maybe there is a good way to get this value? guessedFrame = 2 titlebarHeight = QApplication.style().pixelMetric( QStyle.PM_TitleBarHeight) + guessedFrame widthDisparity = screenGeo.width() - idealWidth heightDisparity = screenGeo.height() - idealHeight if widthDisparity < 0 and widthDisparity < heightDisparity: width = idealWidth + widthDisparity ratio = float(idealHeight) / idealWidth height = int(ratio * (idealWidth + widthDisparity)) self.setGeometry(0, 0, width - guessedFrame * 2, height - titlebarHeight) elif heightDisparity < 0 and heightDisparity < widthDisparity: ratio = float(idealWidth) / idealHeight width = int(ratio * (idealHeight + heightDisparity)) height = idealHeight + heightDisparity self.setGeometry(0, 0, width - guessedFrame * 2, height - titlebarHeight) else: self.setGeometry(0, 0, idealWidth, idealHeight) print("window geometry is", self.geometry()) # Widget self.centralWidget = CentralWidget(self) self.setCentralWidget(self.centralWidget) self.createActions() self.createMenus() # Center the window on the desktop # TODO: Add option for setting startup xy and saving layout in general # qr = self.frameGeometry() # cp = QDesktopWidget().geometry().center() # qr.moveCenter(cp) frameGeo = self.geometry() frameGeo.setHeight(frameGeo.height() + titlebarHeight + guessedFrame) frameGeo.setWidth(frameGeo.width() + guessedFrame * 2) self.move(QDesktopWidget().screenGeometry().center() - frameGeo.center())
def createQApplication(app_name = 'Back In Time'): global qapp try: return qapp except NameError: pass qapp = QApplication(sys.argv + ['-title', app_name]) if os.geteuid() == 0 and \ qapp.style().objectName().lower() == 'windows' and \ 'GTK+' in QStyleFactory.keys(): qapp.setStyle('GTK+') return qapp
def __init__(self, *args, **kwargs): super(MainWindow, self).__init__(*args, **kwargs) self.webView = QWebView(self) self.webView.settings().setAttribute(self.webView.settings().globalSettings().DeveloperExtrasEnabled, True) self.webView.settings().setUserStyleSheetUrl(QUrl.fromUserInput(os.path.join(app_folder, "style.css"))) self.webView.loadFinished.connect(self.jsHack) self.setCentralWidget(self.webView) # Main toolbar self.toolBar = QToolBar(self) self.toolBar.setContextMenuPolicy(Qt.CustomContextMenu) self.addToolBar(Qt.LeftToolBarArea, self.toolBar) page = self.webView.page() backAction = page.action(page.Back) backAction.setShortcut("Alt+Left") self.toolBar.addAction(backAction) nextAction = page.action(page.Forward) nextAction.setShortcut("Alt+Right") self.toolBar.addAction(nextAction) reloadAction = page.action(page.Reload) reloadAction.setShortcuts(["Ctrl+R", "F5"]) self.toolBar.addAction(reloadAction) stopAction = page.action(page.Stop) stopAction.setShortcut("Esc") self.toolBar.addAction(stopAction) self.toolBar.addSeparator() style = QApplication.style() self.uploadAction = QAction(self, text="Upload", icon=style.standardIcon(style.SP_ArrowUp)) self.uploadAction.setShortcut("Alt+Up") self.uploadAction.triggered.connect(self.upload) self.toolBar.addAction(self.uploadAction) self.setGitHubSiteAction = QAction(self, text="Set Page", icon=style.standardIcon(style.SP_FileIcon)) self.setGitHubSiteAction.setShortcut("Ctrl+L") self.setGitHubSiteAction.triggered.connect(self.setGitHubSite) self.toolBar.addAction(self.setGitHubSiteAction) self.setGitDirectoryAction = QAction(self, text="Set Directory", icon=style.standardIcon(style.SP_DirIcon)) self.setGitDirectoryAction.setShortcut("Ctrl+O") self.setGitDirectoryAction.triggered.connect(self.setGitDirectory) self.toolBar.addAction(self.setGitDirectoryAction) self.webView.load(QUrl.fromUserInput(settings.value("settings/GitUrl")))
def getCheckBoxRect(self, option): """ Get rect for checkbox centered in option.rect. """ # Get size of a standard checkbox. opts = QStyleOptionButton() checkBoxRect = QApplication.style().subElementRect(QStyle.SE_CheckBoxIndicator, opts, None) # Center checkbox in option.rect. x = option.rect.x() y = option.rect.y() w = option.rect.width() h = option.rect.height() checkBoxTopLeftCorner = QPoint(x + w / 2 - checkBoxRect.width() / 2, y + h / 2 - checkBoxRect.height() / 2) return QRect(checkBoxTopLeftCorner, checkBoxRect.size())
def paint(self, painter, option, index): """Paint a checkbox without the label.""" # print(index.data()) # checked = True check_box_style_option = QStyleOptionButton() if int(index.flags() & Qt.ItemIsEditable) > 0: check_box_style_option.state |= QStyle.State_Enabled else: check_box_style_option.state |= QStyle.State_ReadOnly if bool(index.data()) is True: check_box_style_option.state |= QStyle.State_On else: check_box_style_option.state |= QStyle.State_Off check_box_style_option.rect = self.getCheckBoxRect(option) check_box_style_option.state |= QStyle.State_Enabled QApplication.style().drawControl(QStyle.CE_CheckBox, check_box_style_option, painter)
def createQApplication(app_name = 'Back In Time'): global qapp try: return qapp except NameError: pass if StrictVersion(QT_VERSION_STR) >= StrictVersion('5.6') and \ hasattr(Qt, 'AA_EnableHighDpiScaling'): QApplication.setAttribute(Qt.AA_EnableHighDpiScaling) qapp = QApplication(sys.argv + ['-title', app_name]) if os.geteuid() == 0 and \ qapp.style().objectName().lower() == 'windows' and \ 'GTK+' in QStyleFactory.keys(): qapp.setStyle('GTK+') return qapp
def paint(self, painter, option, index): hasValue = True if (self.m_editorPrivate): property = self.m_editorPrivate.indexToProperty(index) if (property): hasValue = property.hasValue() opt = QStyleOptionViewItem(option) if ((self.m_editorPrivate and index.column() == 0) or not hasValue): property = self.m_editorPrivate.indexToProperty(index) if (property and property.isModified()): opt.font.setBold(True) opt.fontMetrics = QFontMetrics(opt.font) c = QColor() if (not hasValue and self.m_editorPrivate.markPropertiesWithoutValue()): c = opt.palette.color(QPalette.Dark) opt.palette.setColor(QPalette.Text, opt.palette.color(QPalette.BrightText)) else: c = self.m_editorPrivate.calculatedBackgroundColor(self.m_editorPrivate.indexToBrowserItem(index)) if (c.isValid() and (opt.features & QStyleOptionViewItem.Alternate)): c = c.lighter(112) if (c.isValid()): painter.fillRect(option.rect, c) opt.state &= ~QStyle.State_HasFocus if (index.column() == 1): item = self.m_editorPrivate.indexToItem(index) if (self.m_editedItem and (self.m_editedItem == item)): self.m_disablePainting = True super(QtPropertyEditorDelegate, self).paint(painter, opt, index) if (option.type): self.m_disablePainting = False opt.palette.setCurrentColorGroup(QPalette.Active) color = QApplication.style().styleHint(QStyle.SH_Table_GridLineColor, opt) painter.save() painter.setPen(QPen(color)) if (not self.m_editorPrivate or (not self.m_editorPrivate.lastColumn(index.column()) and hasValue)): if option.direction == Qt.LeftToRight: right = option.rect.right() else: right = option.rect.left() painter.drawLine(right, option.rect.y(), right, option.rect.bottom()) painter.restore()
def __init__(self, parent, remove_text, remove_method, add_text, add_method): QWidget.__init__(self, parent) layout = QHBoxLayout() remove_button = QPushButton(remove_text, self) remove_button.setIcon(QApplication.style().standardIcon(QStyle.SP_TrashIcon)) remove_button.clicked.connect(remove_method) layout.addWidget(remove_button) layout.setContentsMargins(8, 0, 8, 0) horizontal_spacer = QSpacerItem(50, 20, QSizePolicy.Expanding, QSizePolicy.Minimum) layout.addItem(horizontal_spacer) add_button = QPushButton(add_text, self) add_button.clicked.connect(add_method) layout.addWidget(add_button) self.setLayout(layout)
def __init__(self, parent=None, **kwargs): limits = kwargs.pop('limits', None) label = kwargs.pop('label', None) delete = kwargs.pop('delete', True) super().__init__(parent, **kwargs) minf, maxf = -sys.float_info.max, sys.float_info.max if label: self.addWidget(QLabel(label)) self.lowlime = SetXDoubleSpinBox(decimals=2, minimum=minf, maximum=maxf, singleStep=0.5, value=limits[0], maximumWidth=75) self.highlime = SetXDoubleSpinBox(decimals=2, minimum=minf, maximum=maxf, singleStep=0.5, value=limits[1], maximumWidth=75) self.lowlime.setValue(limits[0]) self.highlime.setValue(limits[1]) self.addWidget(self.lowlime) self.addWidget(self.highlime) if delete: self.button = QPushButton( QApplication.style().standardIcon(QStyle.SP_DockWidgetCloseButton), "") self.addWidget(self.button) self.button.clicked.connect(self.selfDelete) self.lowlime.valueChanged[float].connect(self.limitChanged) self.highlime.valueChanged[float].connect(self.limitChanged) self.lowlime.editingFinished.connect(self.editFinished) self.highlime.editingFinished.connect(self.editFinished) self.lowlime.focusIn = self.focusInChild self.highlime.focusIn = self.focusInChild self.line1 = MovableVline(position=limits[0], label=label + " - Low") self.line1.sigMoved.connect(self.lineLimitChanged) self.line2 = MovableVline(position=limits[1], label=label + " - High") self.line2.sigMoved.connect(self.lineLimitChanged) self.line1.sigMoveFinished.connect(self.editFinished) self.line2.sigMoveFinished.connect(self.editFinished)
def __init__(self, parent=None): super(StyleSheetEditor, self).__init__(parent) self.ui = Ui_StyleSheetEditor() self.ui.setupUi(self) regExp = QRegExp(r'.(.*)\+?Style') defaultStyle = QApplication.style().metaObject().className() if regExp.exactMatch(defaultStyle): defaultStyle = regExp.cap(1) self.ui.styleCombo.addItems(QStyleFactory.keys()) self.ui.styleCombo.setCurrentIndex( self.ui.styleCombo.findText(defaultStyle, Qt.MatchContains)) self.ui.styleSheetCombo.setCurrentIndex( self.ui.styleSheetCombo.findText('Coffee')) self.loadStyleSheet('Coffee')
def __init__(self, parent=None): super(TrayIcon, self).__init__(parent) # Подключим слоты для реакции на # Нажатие кнопки по значку в панеле управления self.activated.connect(self.icon_activated_slot) # Нажатие по сообщению self.messageClicked.connect(self.message_clicked_slot) # Покажем одну из стандартных иконок self.setIcon(QApplication.style().standardIcon(QStyle.SP_DriveDVDIcon)) self._counter = 0 # Создаём таймер и присваиваем в локальную переменную класса self._timer = QTimer() # Задаём интервал в милисекундах self._timer.setInterval(1000) # Подсоединяем слот, куда таймер будет слать сообщения self._timer.timeout.connect(self.recurring_timer) self._timer.start() self.create_menu()