def paint(self, painter, option, index): options = QStyleOptionViewItem(option) row_obj = index.data(Qt.DisplayRole) self.initStyleOption(options, index) # print(option.rect.width()) style = QApplication.style( ) if options.widget is None else options.widget.style() doc = QTextDocument() doc.setHtml(row_obj.to_html()) doc.setTextWidth(option.rect.width() - 10) # doc.setPageSize(300) # print(doc.loadResource(3)) options.text = "" style.drawControl(QStyle.CE_ItemViewItem, options, painter) ctx = QAbstractTextDocumentLayout.PaintContext() text_rect = style.subElementRect(QStyle.SE_ItemViewItemText, options) painter.save() painter.translate(text_rect.topLeft()) painter.setClipRect(text_rect.translated(-text_rect.topLeft())) doc.documentLayout().draw(painter, ctx) painter.restore()
def main(argv=[]): app = QApplication(argv) w = ToolBox() style = app.style() icon = QIcon(style.standardIcon(QStyle.SP_FileIcon)) p1 = QLabel("A Label") p2 = QListView() p3 = QLabel("Another\nlabel") p4 = QSpinBox() i1 = w.addItem(p1, "Tab 1", icon) i2 = w.addItem(p2, "Tab 2", icon, "The second tab") i3 = w.addItem(p3, "Tab 3") i4 = w.addItem(p4, "Tab 4") p6 = QTextBrowser() p6.setHtml( "<h1>Hello Visitor</h1>" "<p>Are you interested in some of our wares?</p>" ) w.insertItem(2, p6, "Dear friend") w.show() return app.exec_()
def pixmap(self, size, mode, state): # type: (QSize, QIcon.Mode, QIcon.State) -> QPixmap if not self.__generator.isValid(): return QPixmap() dsize = self.__generator.defaultSize() # type: QSize if not dsize.isNull(): dsize.scale(size, Qt.KeepAspectRatio) size = dsize key = "{}.SVGIconEngine/{}/{}x{}".format(__name__, self.__cache_id, size.width(), size.height()) pm = QPixmapCache.find(key) if pm is None or pm.isNull(): pm = QPixmap(size) pm.fill(Qt.transparent) painter = QPainter(pm) try: self.__generator.render( painter, QRectF(0, 0, size.width(), size.height())) finally: painter.end() QPixmapCache.insert(key, pm) style = QApplication.style() if style is not None: opt = QStyleOption() opt.palette = QApplication.palette() pm = style.generatedIconPixmap(mode, pm, opt) return pm
def pixmap(self, size, mode, state): # type: (QSize, QIcon.Mode, QIcon.State) -> QPixmap if not self.__generator.isValid(): return QPixmap() dsize = self.__generator.defaultSize() # type: QSize if not dsize.isNull(): dsize.scale(size, Qt.KeepAspectRatio) size = dsize key = "{}.SVGIconEngine/{}/{}x{}".format( __name__, self.__cache_id, size.width(), size.height() ) pm = QPixmapCache.find(key) if pm is None or pm.isNull(): pm = QPixmap(size) pm.fill(Qt.transparent) painter = QPainter(pm) try: self.__generator.render( painter, QRectF(0, 0, size.width(), size.height())) finally: painter.end() QPixmapCache.insert(key, pm) style = QApplication.style() if style is not None: opt = QStyleOption() opt.palette = QApplication.palette() pm = style.generatedIconPixmap(mode, pm, opt) return pm
def sizeHint(self, option: QStyleOptionViewItem, index: QModelIndex) -> QSize: widget = option.widget template = self.template(-10**self.ndigits, self.ndecimals) span = self.spanData(index) if span is not None: vmin, vmax = span t1 = self.template(vmin, self.ndecimals) t2 = self.template(vmax, self.ndecimals) template = max((t1, t2), key=len) style = widget.style() if widget is not None else QApplication.style() # Keep ref to style wrapper. This is ugly, wrong but the wrapping of # C++ QStyle instance takes ~5% unless the wrapper already exists. self.__style = style opt = QStyleOptionViewItem(option) opt.features |= QStyleOptionViewItem.HasDisplay sh = QSize() key = option.font.key(), template if key not in self.__sh_cache: for d in map(str, range(10)): opt.text = template.replace("X", d) sh_ = style.sizeFromContents(QStyle.CT_ItemViewItem, opt, QSize(), widget) sh = sh.expandedTo(sh_) self.__sh_cache[key] = sh else: sh = self.__sh_cache[key] return QSize(sh)
def paint(self, painter, option, index): dist = self.distribution(index) if dist is None or self.colors is None: super().paint(painter, option, index) return if option.widget is not None: style = option.widget.style() else: style = QApplication.style() self.initStyleOption(option, index) text = option.text metrics = option.fontMetrics margin = style.pixelMetric(QStyle.PM_FocusFrameHMargin, option, option.widget) + 1 bottommargin = min(margin, 1) rect = option.rect.adjusted(margin, margin, -margin, -bottommargin) textrect = style.subElementRect(QStyle.SE_ItemViewItemText, option, option.widget) # Are the margins included in the subElementRect?? -> No! textrect = textrect.adjusted(margin, margin, -margin, -bottommargin) text = option.fontMetrics.elidedText(text, option.textElideMode, textrect.width()) spacing = max(metrics.leading(), 1) distheight = rect.height() - metrics.height() - spacing distheight = numpy.clip(distheight, 2, metrics.height()) painter.save() painter.setClipRect(option.rect) painter.setFont(option.font) painter.setRenderHint(QPainter.Antialiasing) style.drawPrimitive(QStyle.PE_PanelItemViewRow, option, painter, option.widget) style.drawPrimitive(QStyle.PE_PanelItemViewItem, option, painter, option.widget) if option.state & QStyle.State_Selected: color = option.palette.highlightedText().color() else: color = option.palette.text().color() painter.setPen(QPen(color)) textrect = textrect.adjusted(0, 0, 0, -distheight - spacing) distrect = QRect(textrect.bottomLeft() + QPoint(0, spacing), QSize(rect.width(), distheight)) painter.setPen(QPen(Qt.lightGray, 0.3)) self.drawDistBar(painter, distrect, dist) painter.restore() if text: style.drawItemText(painter, textrect, option.displayAlignment, option.palette, option.state & QStyle.State_Enabled, text)
def __init__(self): super().__init__() self.data = None self.extra_data = None self.extra_data = None self.model = itemmodels.VariableListModel() self.model_unique_with_id = itemmodels.VariableListModel() self.extra_model_unique = itemmodels.VariableListModel() self.extra_model_unique_with_id = itemmodels.VariableListModel() box = gui.hBox(self.controlArea, box=None) self.infoBoxData = gui.label( box, self, self.dataInfoText(None), box="Data") self.infoBoxExtraData = gui.label( box, self, self.dataInfoText(None), box="Extra Data") grp = gui.radioButtonsInBox( self.controlArea, self, "merging", box="Merging", callback=self.change_merging) self.attr_boxes = [] radio_width = \ QApplication.style().pixelMetric(QStyle.PM_ExclusiveIndicatorWidth) def add_option(label, pre_label, between_label, merge_type, model, extra_model): gui.appendRadioButton(grp, label) vbox = gui.vBox(grp) box = gui.hBox(vbox) box.layout().addSpacing(radio_width) self.attr_boxes.append(box) gui.widgetLabel(box, pre_label) model[:] = [getattr(self, 'attr_{}_data'.format(merge_type))] extra_model[:] = [getattr(self, 'attr_{}_extra'.format(merge_type))] cb = gui.comboBox(box, self, 'attr_{}_data'.format(merge_type), contentsLength=12, callback=self._invalidate, model=model) cb.setSizePolicy(QSizePolicy.MinimumExpanding, QSizePolicy.Fixed) cb.setFixedWidth(190) gui.widgetLabel(box, between_label) cb = gui.comboBox(box, self, 'attr_{}_extra'.format(merge_type), contentsLength=12, callback=self._invalidate, model=extra_model) cb.setSizePolicy(QSizePolicy.MinimumExpanding, QSizePolicy.Fixed) cb.setFixedWidth(190) vbox.layout().addSpacing(6) add_option("Append columns from Extra Data", "by matching", "with", "augment", self.model, self.extra_model_unique) add_option("Find matching rows", "where", "equals", "merge", self.model_unique_with_id, self.extra_model_unique_with_id) add_option("Concatenate tables, merge rows", "where", "equals", "combine", self.model_unique_with_id, self.extra_model_unique_with_id) self.set_merging()
def __init__(self): super().__init__() self.data = None self.extra_data = None self.extra_data = None self.model = itemmodels.VariableListModel() self.model_unique_with_id = itemmodels.VariableListModel() self.extra_model_unique = itemmodels.VariableListModel() self.extra_model_unique_with_id = itemmodels.VariableListModel() box = gui.hBox(self.controlArea, box=None) self.infoBoxData = gui.label( box, self, self.dataInfoText(None), box="Data") self.infoBoxExtraData = gui.label( box, self, self.dataInfoText(None), box="Extra Data") grp = gui.radioButtonsInBox( self.controlArea, self, "merging", box="Merging", callback=self.change_merging) self.attr_boxes = [] radio_width = \ QApplication.style().pixelMetric(QStyle.PM_ExclusiveIndicatorWidth) def add_option(label, pre_label, between_label, merge_type, model, extra_model): gui.appendRadioButton(grp, label) vbox = gui.vBox(grp) box = gui.hBox(vbox) box.layout().addSpacing(radio_width) self.attr_boxes.append(box) gui.widgetLabel(box, pre_label) model[:] = [getattr(self, 'attr_{}_data'.format(merge_type))] extra_model[:] = [getattr(self, 'attr_{}_extra'.format(merge_type))] cb = gui.comboBox(box, self, 'attr_{}_data'.format(merge_type), callback=self._invalidate, model=model) cb.setSizePolicy(QSizePolicy.MinimumExpanding, QSizePolicy.Fixed) cb.setFixedWidth(190) gui.widgetLabel(box, between_label) cb = gui.comboBox(box, self, 'attr_{}_extra'.format(merge_type), callback=self._invalidate, model=extra_model) cb.setSizePolicy(QSizePolicy.MinimumExpanding, QSizePolicy.Fixed) cb.setFixedWidth(190) vbox.layout().addSpacing(6) add_option("Append columns from Extra Data", "by matching", "with", "augment", self.model, self.extra_model_unique) add_option("Find matching rows", "where", "equals", "merge", self.model_unique_with_id, self.extra_model_unique_with_id) add_option("Concatenate tables, merge rows", "where", "equals", "combine", self.model_unique_with_id, self.extra_model_unique_with_id) self.set_merging()
def sizeHint(self, option, index): # type: (QStyleOptionViewItem, QModelIndex) -> QSize opt = QStyleOptionViewItem(option) self.initStyleOption(option, index) opt.features |= QStyleOptionViewItem.HasDecoration widget = option.widget style = widget.style() if widget is not None else QApplication.style() sh = style.sizeFromContents( QStyle.CT_ItemViewItem, opt, QSize(), widget) return sh
def qgraphicsitem_style(item: QGraphicsItem) -> QStyle: if item.isWidget(): return item.style() parent = item.parentWidget() if parent is not None: return parent.style() scene = item.scene() if scene is not None: return scene.style() return QApplication.style()
def sizeHint(self, option, index): # type: (QStyleOptionViewItem, QModelIndex) -> QSize opt = QStyleOptionViewItem(option) self.initStyleOption(option, index) opt.features |= QStyleOptionViewItem.HasDecoration widget = option.widget style = widget.style() if widget is not None else QApplication.style() sh = style.sizeFromContents( QStyle.CT_ItemViewItem, opt, QSize(), widget) return sh
def sizeHint(self, option, index): # reimplemented sh = super().sizeHint(option, index) if option.widget is not None: style = option.widget.style() else: style = QApplication.style() margin = style.pixelMetric( QStyle.PM_FocusFrameHMargin, option, option.widget) + 1 metrics = option.fontMetrics height = sh.height() + metrics.leading() + 2 * margin return QSize(sh.width(), height)
def sizeHint(self, option, index): # reimplemented sh = super().sizeHint(option, index) if option.widget is not None: style = option.widget.style() else: style = QApplication.style() margin = style.pixelMetric(QStyle.PM_FocusFrameHMargin, option, option.widget) + 1 metrics = option.fontMetrics height = sh.height() + metrics.leading() + 2 * margin return QSize(sh.width(), height)
def paint(self, painter: QPainter, option: QStyleOptionViewItem, index: QModelIndex) -> None: opt = QStyleOptionViewItem(option) self.initStyleOption(opt, index) widget = option.widget style = QApplication.style() if widget is None else widget.style() # Keep ref to style wrapper. This is ugly, wrong but the wrapping of # C++ QStyle instance takes ~5% unless the wrapper already exists. self.__style = style text = opt.text opt.text = "" style.drawControl(QStyle.CE_ItemViewItem, opt, painter, widget) trect = style.subElementRect(QStyle.SE_ItemViewItemText, opt, widget) opt.text = text self.drawViewItemText(style, painter, opt, trect)
def main(argv=[]): app = QApplication(argv) toolbox = ToolGrid(columns=3) icon = app.style().standardIcon(QStyle.SP_FileIcon) actions = [ QAction("A", None, icon=icon), QAction("B", None, icon=icon), QAction("This one is longer.", icon=icon), QAction("Not done yet!", icon=icon), QAction("The quick brown fox ... does something I guess", icon=icon), ] toolbox.addActions(actions) toolbox.show() return app.exec()
def paint( self, painter: QPainter, option: QStyleOptionViewItem, index: QModelIndex ) -> None: opt = QStyleOptionViewItem(option) self.initStyleOption(opt, index) widget = option.widget style = QApplication.style() if widget is None else widget.style() self.__style = style text = opt.text opt.text = "" style.drawControl(QStyle.CE_ItemViewItem, opt, painter, widget) textrect = style.subElementRect( QStyle.SE_ItemViewItemText, opt, widget) ratio = self.barFillRatioData(index) if ratio is not None and 0. <= ratio <= 1.: color = self.barColorData(index) if color is None: color = self.color if not color.isValid(): color = opt.palette.color(QPalette.Foreground) rect = option.rect pw = self.penWidth hmargin = 3 + pw / 2 # + half pen width for the round line cap vmargin = 1 textoffset = pw + vmargin * 2 baseline = rect.bottom() - textoffset / 2 width = (rect.width() - 2 * hmargin) * ratio painter.save() painter.setRenderHint(QPainter.Antialiasing) pen = self.__pen pen.setColor(color) pen.setWidth(pw) painter.setPen(pen) line = self.__line left = rect.left() + hmargin line.setLine(left, baseline, left + width, baseline) painter.drawLine(line) painter.restore() textrect.adjust(0, 0, 0, -textoffset) opt.text = text self.drawViewItemText(style, painter, opt, textrect)
def editorEvent(self, event, model, option, index): flags = model.flags(index) if not flags & Qt.ItemIsUserCheckable or \ not option.state & QStyle.State_Enabled or \ not flags & Qt.ItemIsEnabled: return False checkstate = model.data(index, Qt.CheckStateRole) if checkstate is None: return False widget = option.widget style = widget.style() if widget else QApplication.style() if event.type() in { QEvent.MouseButtonPress, QEvent.MouseButtonRelease, QEvent.MouseButtonDblClick }: pos = event.pos() opt = QStyleOptionViewItem(option) self.initStyleOption(opt, index) rect = style.subElementRect(QStyle.SE_ItemViewItemCheckIndicator, opt, widget) if event.button() != Qt.LeftButton or not rect.contains(pos): return False if event.type() in { QEvent.MouseButtonPress, QEvent.MouseButtonDblClick }: return True elif event.type() == QEvent.KeyPress: if event.key() != Qt.Key_Space and event.key() != Qt.Key_Select: return False else: return False if model.flags(index) & Qt.ItemIsTristate: checkstate = (checkstate + 1) % 3 else: checkstate = \ Qt.Unchecked if checkstate == Qt.Checked else Qt.Checked return model.setData(index, checkstate, Qt.CheckStateRole)
def editorEvent(self, event, model, option, index): # type: (QEvent, QAbstractItemModel, QStyleOptionViewItem, QModelIndex) -> bool """ Reimplemented. """ flags = model.flags(index) if not flags & Qt.ItemIsUserCheckable or \ not option.state & QStyle.State_Enabled or \ not flags & Qt.ItemIsEnabled: return False checkstate = model.data(index, Qt.CheckStateRole) if checkstate is None: return False widget = option.widget style = widget.style() if widget is not None else QApplication.style() if event.type() in { QEvent.MouseButtonPress, QEvent.MouseButtonRelease, QEvent.MouseButtonDblClick }: pos = event.pos() opt = QStyleOptionViewItem(option) self.initStyleOption(opt, index) rect = style.subElementRect(QStyle.SE_ItemViewItemCheckIndicator, opt, widget) if event.button() != Qt.LeftButton or not rect.contains(pos): return False if event.type() in { QEvent.MouseButtonPress, QEvent.MouseButtonDblClick }: return True elif event.type() == QEvent.KeyPress: if event.key() != Qt.Key_Space and event.key() != Qt.Key_Select: return False else: return False checkstate = self.nextCheckState(checkstate, index) return model.setData(index, checkstate, Qt.CheckStateRole)
def editorEvent(self, event, model, option, index): flags = model.flags(index) if not flags & Qt.ItemIsUserCheckable or \ not option.state & QStyle.State_Enabled or \ not flags & Qt.ItemIsEnabled: return False checkstate = model.data(index, Qt.CheckStateRole) if checkstate is None: return False widget = option.widget style = widget.style() if widget else QApplication.style() if event.type() in {QEvent.MouseButtonPress, QEvent.MouseButtonRelease, QEvent.MouseButtonDblClick}: pos = event.pos() opt = QStyleOptionViewItem(option) self.initStyleOption(opt, index) rect = style.subElementRect( QStyle.SE_ItemViewItemCheckIndicator, opt, widget) if event.button() != Qt.LeftButton or not rect.contains(pos): return False if event.type() in {QEvent.MouseButtonPress, QEvent.MouseButtonDblClick}: return True elif event.type() == QEvent.KeyPress: if event.key() != Qt.Key_Space and event.key() != Qt.Key_Select: return False else: return False if model.flags(index) & Qt.ItemIsTristate: checkstate = (checkstate + 1) % 3 else: checkstate = \ Qt.Unchecked if checkstate == Qt.Checked else Qt.Checked return model.setData(index, checkstate, Qt.CheckStateRole)
def editorEvent(self, event, model, option, index): # type: (QEvent, QAbstractItemModel, QStyleOptionViewItem, QModelIndex) -> bool """ Reimplemented. """ flags = model.flags(index) if not flags & Qt.ItemIsUserCheckable or \ not option.state & QStyle.State_Enabled or \ not flags & Qt.ItemIsEnabled: return False checkstate = model.data(index, Qt.CheckStateRole) if checkstate is None: return False widget = option.widget style = widget.style() if widget is not None else QApplication.style() if event.type() in {QEvent.MouseButtonPress, QEvent.MouseButtonRelease, QEvent.MouseButtonDblClick}: pos = event.pos() opt = QStyleOptionViewItem(option) self.initStyleOption(opt, index) rect = style.subElementRect( QStyle.SE_ItemViewItemCheckIndicator, opt, widget) if event.button() != Qt.LeftButton or not rect.contains(pos): return False if event.type() in {QEvent.MouseButtonPress, QEvent.MouseButtonDblClick}: return True elif event.type() == QEvent.KeyPress: if event.key() != Qt.Key_Space and event.key() != Qt.Key_Select: return False else: return False checkstate = self.nextCheckState(checkstate, index) return model.setData(index, checkstate, Qt.CheckStateRole)
def paint(self, painter, option, index): options, doc = self._prepare_text_document(option, index) style = (QApplication.style() if options.widget is None else options.widget.style()) options.text = "" # Note: We need to pass the options widget as an argument of # drawControl to make sure the delegate is painted with a style # consistent with the widget in which it is used. # See spyder-ide/spyder#10677. style.drawControl(QStyle.CE_ItemViewItem, options, painter, options.widget) ctx = QAbstractTextDocumentLayout.PaintContext() textRect = style.subElementRect(QStyle.SE_ItemViewItemText, options, None) painter.save() painter.translate(textRect.topLeft() + QPoint(0, -3)) doc.documentLayout().draw(painter, ctx) painter.restore()
def pixmap(self, size, mode, state): # type: (QSize, QIcon.Mode, QIcon.State) -> QPixmap if not self.__generator.isValid(): return QPixmap() dsize = self.__generator.defaultSize() # type: QSize if not dsize.isNull(): dsize.scale(size, Qt.KeepAspectRatio) size = dsize pm = QPixmap(size) pm.fill(Qt.transparent) painter = QPainter(pm) try: self.__generator.render(painter, QRectF(0, 0, size.width(), size.height())) finally: painter.end() style = QApplication.style() if style is not None: opt = QStyleOption() opt.palette = QApplication.palette() pm = style.generatedIconPixmap(mode, pm, opt) return pm
def message_icon(message, style=None): # type: (Message, Optional[QStyle]) -> QIcon """ Return the resolved icon for the message. If `message.icon` is a valid icon then it is used. Otherwise the appropriate style icon is used based on the `message.severity` Parameters ---------- message : Message style : Optional[QStyle] Returns ------- icon : QIcon """ if style is None and QApplication.instance() is not None: style = QApplication.style() if message.icon.isNull(): icon = style.standardIcon(standard_pixmap(message.severity)) else: icon = message.icon return icon
def message_icon(message, style=None): # type: (Message, Optional[QStyle]) -> QIcon """ Return the resolved icon for the message. If `message.icon` is a valid icon then it is used. Otherwise the appropriate style icon is used based on the `message.severity` Parameters ---------- message : Message style : Optional[QStyle] Returns ------- icon : QIcon """ if style is None and QApplication.instance() is not None: style = QApplication.style() if message.icon.isNull(): icon = style.standardIcon(standard_pixmap(message.severity)) else: icon = message.icon return icon
def pixmap(self, size, mode, state): # type: (QSize, QIcon.Mode, QIcon.State) -> QPixmap if not self.__generator.isValid(): return QPixmap() dsize = self.__generator.defaultSize() # type: QSize if not dsize.isNull(): dsize.scale(size, Qt.KeepAspectRatio) size = dsize pm = QPixmap(size) pm.fill(Qt.transparent) painter = QPainter(pm) try: self.__generator.render( painter, QRectF(0, 0, size.width(), size.height())) finally: painter.end() style = QApplication.style() if style is not None: opt = QStyleOption() opt.palette = QApplication.palette() pm = style.generatedIconPixmap(mode, pm, opt) return pm
def __init__(self, data): icon = QApplication.style().standardIcon(QStyle.SP_MessageBoxWarning) F = self.DataField def _finished(*, key=(data.get(F.MODULE), data.get(F.WIDGET_MODULE)), filename=data.get(F.WIDGET_SCHEME)): self._cache.add(key) try: os.remove(filename) except Exception: pass super().__init__(None, Qt.Window, modal=True, sizeGripEnabled=True, windowIcon=icon, windowTitle='Unexpected Error', finished=_finished) self._data = data layout = QVBoxLayout(self) self.setLayout(layout) labels = QWidget(self) labels_layout = QHBoxLayout(self) labels.setLayout(labels_layout) labels_layout.addWidget(QLabel(pixmap=icon.pixmap(50, 50))) labels_layout.addWidget( QLabel('The program encountered an unexpected error. Please<br>' 'report it anonymously to the developers.<br><br>' 'The following data will be reported:')) labels_layout.addStretch(1) layout.addWidget(labels) font = QFont('Monospace', 10) font.setStyleHint(QFont.Monospace) font.setFixedPitch(True) textbrowser = QTextBrowser(self, font=font, openLinks=False, lineWrapMode=QTextBrowser.NoWrap, anchorClicked=QDesktopServices.openUrl) layout.addWidget(textbrowser) def _reload_text(): add_scheme = cb.isChecked() settings.setValue('error-reporting/add-scheme', add_scheme) lines = ['<table>'] for k, v in data.items(): if k.startswith('_'): continue _v, v = v, escape(str(v)) if k == F.WIDGET_SCHEME: if not add_scheme: continue v = '<a href="{}">{}</a>'.format( urljoin('file:', pathname2url(_v)), v) if k in (F.STACK_TRACE, F.LOCALS): v = v.replace('\n', '<br>').replace(' ', ' ') lines.append( '<tr><th align="left">{}:</th><td>{}</td></tr>'.format( k, v)) lines.append('</table>') textbrowser.setHtml(''.join(lines)) settings = QSettings() cb = QCheckBox('Include workflow (data will NOT be transmitted)', self, checked=settings.value('error-reporting/add-scheme', True, type=bool)) cb.stateChanged.connect(_reload_text) _reload_text() layout.addWidget(cb) buttons = QWidget(self) buttons_layout = QHBoxLayout(self) buttons.setLayout(buttons_layout) buttons_layout.addWidget( QPushButton('Send Report (Thanks!)', default=True, clicked=self.accept)) buttons_layout.addWidget( QPushButton("Don't Send", default=False, clicked=self.reject)) layout.addWidget(buttons)
def __init__(self): super().__init__() self.data = None self.extra_data = None self.extra_data = None self.model = itemmodels.VariableListModel() self.model_unique_with_id = itemmodels.VariableListModel() self.extra_model_unique = itemmodels.VariableListModel() self.extra_model_unique_with_id = itemmodels.VariableListModel() box = gui.hBox(self.controlArea, box=None) self.infoBoxData = gui.label(box, self, self.dataInfoText(None), box="数据") self.infoBoxExtraData = gui.label(box, self, self.dataInfoText(None), box="额外数据") grp = gui.radioButtonsInBox(self.controlArea, self, "merging", box="合并", callback=self.change_merging) self.attr_boxes = [] radio_width = \ QApplication.style().pixelMetric(QStyle.PM_ExclusiveIndicatorWidth) def add_option(label, pre_label, between_label, merge_type, model, extra_model): gui.appendRadioButton(grp, label) vbox = gui.vBox(grp) box = gui.hBox(vbox) box.layout().addSpacing(radio_width) self.attr_boxes.append(box) gui.widgetLabel(box, pre_label) model[:] = [getattr(self, 'attr_{}_data'.format(merge_type))] extra_model[:] = [ getattr(self, 'attr_{}_extra'.format(merge_type)) ] cb = gui.comboBox(box, self, 'attr_{}_data'.format(merge_type), contentsLength=12, callback=self._invalidate, model=model) cb.setSizePolicy(QSizePolicy.MinimumExpanding, QSizePolicy.Fixed) cb.setFixedWidth(190) gui.widgetLabel(box, between_label) cb = gui.comboBox(box, self, 'attr_{}_extra'.format(merge_type), contentsLength=12, callback=self._invalidate, model=extra_model) cb.setSizePolicy(QSizePolicy.MinimumExpanding, QSizePolicy.Fixed) cb.setFixedWidth(190) vbox.layout().addSpacing(6) add_option("添加额外的数据列", "通过匹配", "和", "augment", self.model, self.extra_model_unique) add_option("查找匹配行", "where", "equals", "merge", self.model_unique_with_id, self.extra_model_unique_with_id) add_option("连接表格,合并行", "where", "equals", "combine", self.model_unique_with_id, self.extra_model_unique_with_id) self.set_merging() gui.auto_commit(self.controlArea, self, "auto_apply", "应用", box=False)
def __init__(self, data): icon = QApplication.style().standardIcon(QStyle.SP_MessageBoxWarning) F = self.DataField def _finished(*, key=(data.get(F.MODULE), data.get(F.WIDGET_MODULE)), filename=data.get(F.WIDGET_SCHEME)): self._cache.add(key) try: os.remove(filename) except Exception: pass super().__init__(None, Qt.Window, modal=True, sizeGripEnabled=True, windowIcon=icon, windowTitle='Unexpected Error', finished=_finished) self._data = data layout = QVBoxLayout(self) self.setLayout(layout) labels = QWidget(self) labels_layout = QHBoxLayout(self) labels.setLayout(labels_layout) labels_layout.addWidget(QLabel(pixmap=icon.pixmap(50, 50))) labels_layout.addWidget(QLabel( 'The program encountered an unexpected error. Please<br>' 'report it anonymously to the developers.<br><br>' 'The following data will be reported:')) labels_layout.addStretch(1) layout.addWidget(labels) font = QFont('Monospace', 10) font.setStyleHint(QFont.Monospace) font.setFixedPitch(True) textbrowser = QTextBrowser(self, font=font, openLinks=False, lineWrapMode=QTextBrowser.NoWrap, anchorClicked=QDesktopServices.openUrl) layout.addWidget(textbrowser) def _reload_text(): add_scheme = cb.isChecked() settings.setValue('error-reporting/add-scheme', add_scheme) lines = ['<table>'] for k, v in data.items(): if k.startswith('_'): continue _v, v = v, escape(str(v)) if k == F.WIDGET_SCHEME: if not add_scheme: continue v = '<a href="{}">{}</a>'.format(urljoin('file:', pathname2url(_v)), v) if k in (F.STACK_TRACE, F.LOCALS): v = v.replace('\n', '<br>').replace(' ', ' ') lines.append('<tr><th align="left">{}:</th><td>{}</td></tr>'.format(k, v)) lines.append('</table>') textbrowser.setHtml(''.join(lines)) settings = QSettings() cb = QCheckBox( 'Include workflow (data will NOT be transmitted)', self, checked=settings.value('error-reporting/add-scheme', True, type=bool)) cb.stateChanged.connect(_reload_text) _reload_text() layout.addWidget(cb) buttons = QWidget(self) buttons_layout = QHBoxLayout(self) buttons.setLayout(buttons_layout) buttons_layout.addWidget( QPushButton('Send Report (Thanks!)', default=True, clicked=self.accept)) buttons_layout.addWidget(QPushButton("Don't Send", default=False, clicked=self.reject)) layout.addWidget(buttons)
def paint(self, painter, option, index): dist = self.distribution(index) if dist is None or self.__colors is None: return super().paint(painter, option, index) if not numpy.isfinite(numpy.sum(dist)): return super().paint(painter, option, index) nvalues = len(dist) if len(self.__colors) < nvalues: colors = colorpalette.ColorPaletteGenerator(nvalues) colors = [colors[i] for i in range(nvalues)] else: colors = self.__colors if option.widget is not None: style = option.widget.style() else: style = QApplication.style() self.initStyleOption(option, index) text = option.text metrics = option.fontMetrics margin = style.pixelMetric( QStyle.PM_FocusFrameHMargin, option, option.widget) + 1 bottommargin = min(margin, 1) rect = option.rect.adjusted(margin, margin, -margin, -bottommargin) textrect = style.subElementRect( QStyle.SE_ItemViewItemText, option, option.widget) # Are the margins included in the subElementRect?? -> No! textrect = textrect.adjusted(margin, margin, -margin, -bottommargin) text = option.fontMetrics.elidedText( text, option.textElideMode, textrect.width()) spacing = max(metrics.leading(), 1) distheight = rect.height() - metrics.height() - spacing distheight = numpy.clip(distheight, 2, metrics.height()) painter.save() painter.setClipRect(option.rect) painter.setFont(option.font) painter.setRenderHint(QPainter.Antialiasing) style.drawPrimitive( QStyle.PE_PanelItemViewRow, option, painter, option.widget) style.drawPrimitive( QStyle.PE_PanelItemViewItem, option, painter, option.widget) if option.state & QStyle.State_Selected: color = option.palette.highlightedText().color() else: color = option.palette.text().color() painter.setPen(QtGui.QPen(color)) textrect = textrect.adjusted(0, 0, 0, -distheight - spacing) distrect = QtCore.QRect( textrect.bottomLeft() + QtCore.QPoint(0, spacing), QtCore.QSize(rect.width(), distheight) ) painter.setPen(QtGui.QPen(Qt.lightGray, 0.3)) drawDistBar(painter, distrect, dist, colors) painter.restore() if text: style.drawItemText( painter, textrect, option.displayAlignment, option.palette, option.state & QStyle.State_Enabled, text)