def setColumnLinks(self, column, links): font = QFont() font.setUnderline(True) for i, link in enumerate(links): self._roleData[gui.LinkRole][i][column] = link self._roleData[Qt.FontRole][i][column] = font self._roleData[Qt.ForegroundRole][i][column] = QColor(Qt.blue)
def splash_screen(): """ """ pm = QPixmap( pkg_resources.resource_filename( __name__, "icons/orange-splash-screen.png") ) version = QCoreApplication.applicationVersion() size = 21 if len(version) < 5 else 16 font = QFont("Helvetica") font.setPixelSize(size) font.setBold(True) font.setItalic(True) font.setLetterSpacing(QFont.AbsoluteSpacing, 2) metrics = QFontMetrics(font) br = metrics.boundingRect(version).adjusted(-5, 0, 5, 0) br.moveCenter(QPoint(436, 224)) p = QPainter(pm) p.setRenderHint(QPainter.Antialiasing) p.setRenderHint(QPainter.TextAntialiasing) p.setFont(font) p.setPen(QColor("#231F20")) p.drawText(br, Qt.AlignCenter, version) p.end() return pm, QRect(88, 193, 200, 20)
def data(self, index, role=Qt.DisplayRole): # pylint: disable=missing-docstring # Only valid for the first column row = index.row() if role == Qt.DisplayRole or role == Qt.EditRole: return self.variables[row].name if role == Qt.FontRole: font = QFont() font.setBold(True) return font if role == Qt.TextAlignmentRole: return Qt.AlignRight | Qt.AlignVCenter
def __init__(self): super().__init__() self.results = None self.classifier_names = [] self.colors = [] self._curve_data = {} box = gui.vBox(self.controlArea, "Plot") tbox = gui.vBox(box, "Target Class") tbox.setFlat(True) self.target_cb = gui.comboBox( tbox, self, "target_index", callback=self._on_target_changed, contentsLength=8) cbox = gui.vBox(box, "Classifiers") cbox.setFlat(True) self.classifiers_list_box = gui.listBox( cbox, self, "selected_classifiers", "classifier_names", selectionMode=QtWidgets.QListView.MultiSelection, callback=self._on_classifiers_changed) gui.checkBox(box, self, "display_convex_hull", "Show lift convex hull", callback=self._replot) self.plotview = pg.GraphicsView(background="w") self.plotview.setFrameStyle(QtWidgets.QFrame.StyledPanel) self.plot = pg.PlotItem(enableMenu=False) self.plot.setMouseEnabled(False, False) self.plot.hideButtons() pen = QPen(self.palette().color(QPalette.Text)) tickfont = QFont(self.font()) tickfont.setPixelSize(max(int(tickfont.pixelSize() * 2 // 3), 11)) axis = self.plot.getAxis("bottom") axis.setTickFont(tickfont) axis.setPen(pen) axis.setLabel("P Rate") axis = self.plot.getAxis("left") axis.setTickFont(tickfont) axis.setPen(pen) axis.setLabel("TP Rate") self.plot.showGrid(True, True, alpha=0.1) self.plot.setRange(xRange=(0.0, 1.0), yRange=(0.0, 1.0), padding=0.05) self.plotview.setCentralItem(self.plot) self.mainArea.layout().addWidget(self.plotview)
def font_resize(font, factor, minsize=None, maxsize=None): font = QFont(font) fontinfo = QFontInfo(font) size = fontinfo.pointSizeF() * factor if minsize is not None: size = max(size, minsize) if maxsize is not None: size = min(size, maxsize) font.setPointSizeF(size) return font
def data(self, index, role): if role == self.IsSelected: return self.is_selected(index) elif role == Qt.FontRole: font = QFont() font.setBold(self.is_selected(index)) return font elif role == self.SortRole: if self.is_selected(index): return self.selected_vars.index(self[index.row()]) else: return len(self.selected_vars) + index.row() else: return super().data(index, role)
def __init__(self, form=None, parent=None): "Create and display the GUI, but do not start it." self.result = None self.form = form log.info("Creating GUI object") super().__init__(parent=parent) self.ui_font = QFont("Microsoft Sans Serif", 12, QFont.Bold) self.body_font = QFont("Cooper", 48, QFont.Bold) self.setFont(self.ui_font) self.app_title = "JSON Forms" self.initUI() self.tr_thread = TimerThread(self) self.tr_thread.start() self.show()
def set_column_links(self): domain = self._data.domain ref_col = domain.metas.index( domain[HeaderLabels[HeaderIndex.REFERENCE]]) font = QFont() font.setUnderline(True) color = QColor(Qt.blue) for i, row in enumerate(self.source): link = row[HeaderLabels[HeaderIndex.URL]].value if len(link) and 'http' in link: self._roleData[gui.LinkRole][i][ref_col] = link self._roleData[Qt.FontRole][i][ref_col] = font self._roleData[Qt.ForegroundRole][i][ref_col] = color
def effective_point_size_for_width( font: QFont, width: float, width_for_font: Callable[[QFont], float], step=1.0, minsize=1., ) -> float: start = max(QFontInfo(font).pointSizeF(), minsize) font.setPointSizeF(start) fix = 0 while width_for_font(font) > width and start - (fix + step) >= minsize: fix += step font.setPointSizeF(start - fix) return QFontInfo(font).pointSizeF()
def createButton(self, action, background="light-orange"): """Create a tool button for action. """ button = WelcomeActionButton(self) button.setDefaultAction(action) button.setText(action.iconText()) button.setIcon(decorate_welcome_icon(action.icon(), background)) button.setToolTip(action.toolTip()) button.setFixedSize(100, 100) button.setToolButtonStyle(Qt.ToolButtonTextUnderIcon) font = QFont(button.font()) font.setPointSize(13) button.setFont(font) return button
def setColumnLinks(self): font = QFont() font.setUnderline(True) for i, link in enumerate(self._data): self._roleData[gui.LinkRole][i][0] = gene.NCBI_DETAIL_LINK.format( self._roleData[Qt.DisplayRole][i][0]) self._roleData[Qt.FontRole][i][0] = font self._roleData[Qt.ForegroundRole][i][0] = QColor(Qt.blue) self._roleData[ gui.LinkRole][i][1] = gene.ENSEMBL_DETAIL_LINK.format( self._roleData[Qt.DisplayRole][i][1]) self._roleData[Qt.FontRole][i][1] = font self._roleData[Qt.ForegroundRole][i][1] = QColor(Qt.blue)
def documentForScript(self, script=0): if not isinstance(script, Script): script = self.libraryList[script] if script not in self._cachedDocuments: doc = QTextDocument(self) doc.setDocumentLayout(QPlainTextDocumentLayout(doc)) doc.setPlainText(script.script) doc.setDefaultFont(QFont(self.defaultFont)) doc.highlighter = PygmentsHighlighter(doc) doc.highlighter.set_style(self.pygments_style_class) doc.setDefaultFont( QFont(self.defaultFont, pointSize=self.defaultFontSize)) doc.modificationChanged[bool].connect(self.onModificationChanged) doc.setModified(False) self._cachedDocuments[script] = doc return self._cachedDocuments[script]
def update_axes_ticks_font(items: List[pg.AxisItem], **settings: _SettingType): for item in items: font = item.style["tickFont"] or QFont() # remove when contained in setTickFont() - version 0.11.0 item.style['tickFont'] = font item.setTickFont(Updater.change_font(font, settings))
def __init__(self, parent=None, orientation=Qt.Vertical, domain=None, items=None, bg_color=QColor(232, 232, 232, 196), font=None, color_indicator_cls=LegendItemSquare, **kwargs): super().__init__(parent, **kwargs) self._layout = None self.orientation = orientation self.bg_color = QBrush(bg_color) self.color_indicator_cls = color_indicator_cls # Set default font if none is given if font is None: self.font = QFont() self.font.setPointSize(10) else: self.font = font self.setFlags(QGraphicsWidget.ItemIsMovable | QGraphicsItem.ItemIgnoresTransformations) self._setup_layout() if domain is not None: self.set_domain(domain) elif items is not None: self.set_items(items)
def __init__(self, parent: Optional[QGraphicsItem] = None, items: Iterable[str] = (), alignment: Union[Qt.AlignmentFlag, Qt.Alignment] = Qt.AlignLeading, orientation: Qt.Orientation = Qt.Vertical, autoScale=False, **kwargs: Any) -> None: self.__items: List[str] = [] self.__textitems: List[QGraphicsSimpleTextItem] = [] self.__group: Optional[QGraphicsItemGroup] = None self.__spacing = 0 self.__alignment = Qt.AlignmentFlag(alignment) self.__orientation = orientation self.__autoScale = autoScale # The effective font when autoScale is in effect self.__effectiveFont = QFont() self.__widthCache = {} sizePolicy = kwargs.pop("sizePolicy", None) # type: Optional[QSizePolicy] super().__init__(None, **kwargs) self.setFlag(QGraphicsWidget.ItemClipsChildrenToShape, True) sp = QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Preferred) sp.setWidthForHeight(True) self.setSizePolicy(sp) if sizePolicy is not None: self.setSizePolicy(sizePolicy) if parent is not None: self.setParentItem(parent) if items is not None: self.setItems(items)
def _create_layout(self): box = gui.widgetBox(self.mainArea, 'RMSE') BOLD_FONT = QFont() BOLD_FONT.setWeight(QFont.DemiBold) widget = self class HereTableWidget(QTableWidget): def __init__(self, parent): super().__init__(parent) parent.layout().addWidget(self) self.setHorizontalScrollMode(self.ScrollPerPixel) self.setVerticalScrollMode(self.ScrollPerPixel) def update_table(self, fusers, relations): self.clear() self.setRowCount(0) self.setColumnCount(len(fusers)) self.setHorizontalHeaderLabels([fuser[0].name for fuser in fusers.values()]) for id, relation in relations.items(): row = self.rowCount() self.insertRow(row) if not np.ma.is_masked(relation.data): widget.warning(id, 'Relation "{}" has no missing values ' '(mask)'.format(relation_str(relation))) rmses = [] for fuser in fusers.values(): rep_rmse = [] for fuserfit in fuser: if not fuserfit.can_complete(relation): break completion = fuserfit.complete(relation) rep_rmse.append(RMSE(relation.data, completion)) rmses.append(np.mean(rep_rmse) if rep_rmse else None) try: min_rmse = min(e for e in rmses if e is not None) except ValueError: continue # No fuser could complete this relation for col, rmse in enumerate(rmses): if rmse is None: continue item = QTableWidgetItem('{:.05f}'.format(rmse)) item.setFlags(Qt.ItemIsEnabled) if rmse == min_rmse and len(rmses) > 1: item.setFont(BOLD_FONT) self.setItem(row, col, item) self.setVerticalHeaderLabels([relation_str(i) for i in relations.values()]) self.resizeColumnsToContents() self.resizeRowsToContents() self.table = HereTableWidget(box)
def __init__(self, master): super().__init__(master) self.reg_line_label_font = QFont() self.reg_line_settings = { Updater.WIDTH_LABEL: self.DEFAULT_LINE_WIDTH, Updater.ALPHA_LABEL: self.DEFAULT_LINE_ALPHA, Updater.STYLE_LABEL: Updater.DEFAULT_LINE_STYLE, }
def test_widget(self): w = HeatmapGridWidget() self.scene.addItem(w) for p in self._Data.values(): w.setHeatmaps(p) w.headerGeometry() w.footerGeometry() # Trigger the change events. p = QPalette() p.setColor(QPalette.All, QPalette.Text, Qt.red) w.setPalette(p) f = QFont() f.setPointSizeF(19.5) w.setFont(f)
def __init__(self, parent): self.value_label_font = Updater.change_font( QFont(), VariableItem.VALUE_FONT_SETTING) self.label_len_setting = { self.LABEL_LENGTH: VariableItem.MAX_LABEL_LEN } super().__init__() self.master: FeaturesPlot = parent
def _init_table(self, nclasses): item = self._item(0, 2) item.setData("Predicted", Qt.DisplayRole) item.setTextAlignment(Qt.AlignCenter) item.setFlags(Qt.NoItemFlags) self._set_item(0, 2, item) item = self._item(2, 0) item.setData("Actual", Qt.DisplayRole) item.setTextAlignment(Qt.AlignHCenter | Qt.AlignBottom) item.setFlags(Qt.NoItemFlags) self.tableview.setItemDelegateForColumn(0, gui.VerticalItemDelegate()) self._set_item(2, 0, item) self.tableview.setSpan(0, 2, 1, nclasses) self.tableview.setSpan(2, 0, nclasses, 1) font = self.tablemodel.invisibleRootItem().font() bold_font = QFont(font) bold_font.setBold(True) for i in (0, 1): for j in (0, 1): item = self._item(i, j) item.setFlags(Qt.NoItemFlags) self._set_item(i, j, item) for p, label in enumerate(self.headers): for i, j in ((1, p + 2), (p + 2, 1)): item = self._item(i, j) item.setData(label, Qt.DisplayRole) item.setFont(bold_font) item.setTextAlignment(Qt.AlignRight | Qt.AlignVCenter) item.setFlags(Qt.ItemIsEnabled) if p < len(self.headers) - 1: item.setData("br"[j == 1], BorderRole) item.setData(QColor(192, 192, 192), BorderColorRole) self._set_item(i, j, item) hor_header = self.tableview.horizontalHeader() if len(' '.join(self.headers)) < 120: hor_header.setSectionResizeMode(QHeaderView.ResizeToContents) else: hor_header.setDefaultSectionSize(60) self.tablemodel.setRowCount(nclasses + 3) self.tablemodel.setColumnCount(nclasses + 3)
def __width_for_font(self, font: QFont) -> float: """Return item width for the font""" key = font.key() if key in self.__widthCache: return self.__widthCache[key] fm = QFontMetricsF(font) width = max((fm.width(text) for text in self.__items), default=0) self.__widthCache[key] = width return width
class FakeSignatureMixin: def __init__(self, parent, highlighting_scheme, font): super().__init__(parent) self.highlighting_scheme = highlighting_scheme self.setFont(font) self.bold_font = QFont(font) self.bold_font.setBold(True) self.indentation_level = 0 self._char_4_width = QFontMetrics(font).horizontalAdvance('4444') def setIndent(self, margins_width): self.setContentsMargins( max( 0, round(margins_width) + ((self.indentation_level - 1) * self._char_4_width)), 0, 0, 0)
def paintEvent(self, e): """ :param e: :return: """ self._is_painting = True super(EventsWidget, self).paintEvent(e) painter = QPainter() painter.begin(self) painter.setRenderHint(QPainter.Antialiasing) painter.setFont(QFont('Decorative', 8)) slider_pos = self._scroll.sliderPosition() start = slider_pos * self._scale end = start + self.width() * self._scale for i, track in enumerate(self._tracks): if self._break_draw: break track.draw_events(painter, start, end, track_index=i, left_shift=-self._scroll.sliderPosition(), scale=self._scale) # Draw only from pixel start to end painter.setPen(QtCore.Qt.DashLine) painter.setOpacity(0.3) # print('Draw', start, end, self._scale, self._scroll.sliderPosition(), self.width()) # Draw vertical lines for x in range(start - (start % (100 * self._scale)), end, 100 * self._scale): x2draw = (x - slider_pos * self._scale) // self._scale painter.drawLine(x2draw, 20, x2draw, self.height()) string = str(x) boundtext = painter.boundingRect(QtCore.QRectF(), string) painter.drawText(x2draw - boundtext.width() / 2, 15, string) for index, track in enumerate(self._tracks): top = self.which_top(index) # print(top) painter.drawLine(0, top, self.width(), top) painter.drawText(10, top + 15, track.title) painter.setOpacity(1.0) self._pointer.draw(painter, left_shift=-slider_pos, scale=self._scale) # Draw the time pointer painter.end() self._break_draw = False self._is_painting = False
def splash_screen(): # type: () -> Tuple[QPixmap, QRect] """ Return a splash screen pixmap and an text area within it. The text area is used for displaying text messages during application startup. The default implementation returns a bland rectangle splash screen. Returns ------- t : Tuple[QPixmap, QRect] A QPixmap and a rect area within it. """ path = pkg_resources.resource_filename( __name__, "icons/orange-canvas-core-splash.svg") pm = QPixmap(path) version = QCoreApplication.applicationVersion() if version: version_parsed = LooseVersion(version) version_comp = version_parsed.version version = ".".join(map(str, version_comp[:2])) size = 21 if len(version) < 5 else 16 font = QFont() font.setPixelSize(size) font.setBold(True) font.setItalic(True) font.setLetterSpacing(QFont.AbsoluteSpacing, 2) metrics = QFontMetrics(font) br = metrics.boundingRect(version).adjusted(-5, 0, 5, 0) br.moveBottomRight(QPoint(pm.width() - 15, pm.height() - 15)) p = QPainter(pm) p.setRenderHint(QPainter.Antialiasing) p.setRenderHint(QPainter.TextAntialiasing) p.setFont(font) p.setPen(QColor("#231F20")) p.drawText(br, Qt.AlignCenter, version) p.end() textarea = QRect(15, 15, 170, 20) return pm, textarea
def __init__(self, parent, label: str): self.__name: str = None self.__value: Optional[str] = None self.__name_item = QGraphicsSimpleTextItem() self.__value_item = QGraphicsSimpleTextItem() font = Updater.change_font(QFont(), self.VALUE_FONT_SETTING) self.__value_item.setFont(font) self.__max_len = self.MAX_LABEL_LEN super().__init__(parent) self._set_data(label)
def paintEvent(self, e): # call the base implementation to paint normal interface super(GaugeWidgetVertical, self).paintEvent(e) draw = QPainter() draw.begin(self) window_with = self.width() - 1 diff = (self._higher - self._lower) * self.scale try: self._step = float(self.height()) / float(diff) except ZeroDivisionError: self._step = 0 y_start = self.height() - (self._minVal - self._lower) * self._step * self.scale y_end = self.height() - (self._maxVal - self._lower) * self._step * self.scale draw.setOpacity(1.0) draw.setBrush(QtCore.Qt.NoBrush) draw.setPen(QColor(200, 200, 255)) b = int(self.height() / 5) e = int(self.height() - (self.height() / 5) + 1) s = int(self.height() / 5) for i in range(b, e, s): draw.drawLine(0, i, window_with, i) draw.setBrush(QColor(33, 133, 208)) draw.setPen(QColor(33, 133, 208)) draw.setOpacity(0.7) draw.drawRect(0, y_start, window_with, y_end - y_start) draw.setFont(QFont('Decorative', 8)) draw.setPen(QColor(30, 30, 30)) draw.drawText( 3, self.height() - 3, str(self._lower) if self._use_float else str( int(round(self._lower)))) draw.drawText( 3, 10, str(self._higher) if self._use_float else str( int(round(self._higher)))) draw.drawText( 3, y_start + 11, str(self._minVal) if self._use_float else str( int(round(self._minVal)))) draw.drawText( 3, y_end - 4, str(self._maxVal) if self._use_float else str( int(round(self._maxVal)))) draw.end()
def font_from_dict(font_dict, font=None): if font is None: font = QFont() else: font = QFont(font) if "family" in font_dict: font.setFamily(font_dict["family"]) if "size" in font_dict: font.setPixelSize(font_dict["size"]) return font
def _updateFontSize(self): crect = self.contentsRect() if self.orientation() == Qt.Vertical: h = crect.height() else: h = crect.width() n = self.count() if n == 0: return if self.scene() is not None: maxfontsize = self.scene().font().pointSize() else: maxfontsize = QApplication.instance().font().pointSize() lineheight = max(1., h / n) fontsize = min(self._point_size(lineheight), maxfontsize) font_ = QFont() font_.setPointSize(fontsize) self.setFont(font_)
def paintEvent(self, event): """ Paint event :param event: """ super(TimelineWidget, self).paintEvent(event) painter = QPainter() painter.begin(self) painter.setRenderHint(QPainter.Antialiasing) painter.setFont(QFont('Decorative', 8)) # find the start and end X coordinate to draw start = self.scrollbar.sliderPosition() end = start + self.parent().width() + 50 # Draw graphs ########################################################## if len(self._graphs) > 0: painter.setPen(QtCore.Qt.black) middle = self.height() // 2 painter.setOpacity(0.1) painter.drawLine(start, middle, end, middle) for chart in self._graphs: chart.draw(painter, start, end, 0, self.height()) # End draw graph ####################################################### for track in self.tracks: track.draw_title(painter, start, end) self.__draw_track_lines(painter, start, end) if self._selected_track is not None: self._selected_track.draw_background(painter, start, end) for track in self.tracks: track.draw_events(painter, start, end) # Draw the selected element if self._selected != None: painter.setBrush(QColor(255, 0, 0)) self._selected.draw(painter, showvalues=True) # Draw the time pointer self._pointer.draw(painter, highlight=self._creating_event) painter.end() if not hasattr(self, '_is_refreshing'): self._is_refreshing = True self.update() else: del self._is_refreshing
def __init__(self): def update_font_family(**settings): for label in self.initial_settings[self.LABELS_BOX]: if label != self.FONT_FAMILY_LABEL: setter = self._setters[self.LABELS_BOX][label] setter(**settings) def update_title(**settings): Updater.update_plot_title_font(self.title_item, **settings) def update_label(**settings): self.label_font = Updater.change_font(self.label_font, settings) Updater.update_label_font(self.labels, self.label_font) def update_axes_titles(**settings): Updater.update_axes_titles_font(self.axis_items, **settings) def update_axes_ticks(**settings): Updater.update_axes_ticks_font(self.axis_items, **settings) def update_legend(**settings): self.legend_settings.update(**settings) Updater.update_legend_font(self.legend_items, **settings) def update_title_text(**settings): Updater.update_plot_title_text(self.title_item, settings[self.TITLE_LABEL]) def update_axis(axis, **settings): Updater.update_axis_title_text(self.getAxis(axis), settings[self.TITLE_LABEL]) self.label_font = QFont() self.legend_settings = {} self._setters = { self.LABELS_BOX: { self.FONT_FAMILY_LABEL: update_font_family, self.TITLE_LABEL: update_title, self.LABEL_LABEL: update_label, self.AXIS_TITLE_LABEL: update_axes_titles, self.AXIS_TICKS_LABEL: update_axes_ticks, self.LEGEND_LABEL: update_legend, }, self.ANNOT_BOX: { self.TITLE_LABEL: update_title_text, self.X_AXIS_LABEL: lambda **kw: update_axis("bottom", **kw), self.Y_AXIS_LABEL: lambda **kw: update_axis("left", **kw), } } self.update_setters() self._check_setters()
def qfont_scaled(font, factor): scaled = QFont(font) if font.pointSizeF() != -1: scaled.setPointSizeF(font.pointSizeF() * factor) elif font.pixelSize() != -1: scaled.setPixelSize(int(font.pixelSize() * factor)) return scaled
def font_from_dict(font_dict, font=None): # type: (dict, Optional[QFont]) -> QFont if font is None: font = QFont() else: font = QFont(font) if "family" in font_dict: font.setFamily(font_dict["family"]) if "size" in font_dict: font.setPixelSize(font_dict["size"]) return font
def paintEvent(self, e): # call the base implementation to paint normal interface QWidget.paintEvent(self, e); draw = QPainter(); draw.begin(self) h = self.height() - 1 diff = (self._higher - self._lower) * self.scale try: self._step = float(self.width()) / float(diff) except ZeroDivisionError: self._step = 0 x_start = (self._minVal - self._lower) * self._step * self.scale x_end = (self._maxVal - self._lower) * self._step * self.scale draw.setOpacity(1.0) draw.setBrush(QtCore.Qt.NoBrush) draw.setPen(QColor(200, 200, 255)) for i in range( int(self.width()/5), int(self.width()-self.width()/5) + 1, int(self.width()/5) ): draw.drawLine(i, 0, i, h) draw.setBrush(QColor(238, 238, 238)) draw.setPen(QColor(238, 238, 238)) draw.drawRoundedRect(0, 2, self.width(), h - 4, 3, 3) draw.setBrush(QColor(33, 133, 208)) draw.setPen(QColor(33, 133, 208)) draw.drawRoundedRect(int(round(x_start)), 2, int(round(x_end - x_start)), h - 4, 3, 3) # draw.setOpacity(1.0) draw.setFont(QFont('Decorative', 8)) draw.setPen(QColor(80, 80, 80)) str(self._maxVal) if self._use_float else str(int(round(self._maxVal))) boundtext = draw.boundingRect(QtCore.QRectF(), str(self._higher) if self._use_float else str(int(round(self._higher)))) draw.drawText(self.width() - boundtext.width(), 14, str(self._higher) if self._use_float else str(int(round(self._higher)))) draw.drawText(0, 14, str(self._lower) if self._use_float else str(int(round(self._lower)))) draw.setPen(QColor(255, 255, 255)) boundtext = draw.boundingRect(QtCore.QRectF(), str(self._minVal) if self._use_float else str(int(round(self._minVal)))) draw.drawText(x_start + 2, 14, str(self._minVal) if self._use_float else str(int(round(self._minVal)))) boundtext = draw.boundingRect(QtCore.QRectF(), str(self._maxVal) if self._use_float else str(int(round(self._maxVal)))) draw.drawText(x_end - boundtext.width(), 14, str(self._maxVal) if self._use_float else str(int(round(self._maxVal)))) draw.end()
def documentForScript(self, script=0): if type(script) != Script: script = self.libraryList[script] if script not in self._cachedDocuments: doc = QTextDocument(self) doc.setDocumentLayout(QPlainTextDocumentLayout(doc)) doc.setPlainText(script.script) doc.setDefaultFont(QFont(self.defaultFont)) doc.highlighter = PythonSyntaxHighlighter(doc) doc.modificationChanged[bool].connect(self.onModificationChanged) doc.setModified(False) self._cachedDocuments[script] = doc return self._cachedDocuments[script]
def default_font_size() -> int: """ Function returns default font size in points used in Qt application. Can be used to instantiate initial dialog state. Returns ------- size: int Default font size in points. """ if not QApplication.instance(): _ = QApplication(sys.argv) return QFont().pointSize()
def default_font_family() -> str: """ Function returns default font family used in Qt application. Can be used to instantiate initial dialog state. Returns ------- font: str Default font family. """ if not QApplication.instance(): _ = QApplication(sys.argv) return QFont().family()
def test_combobox(self): cb = ItemStyledComboBox() cb.setPlaceholderText("...") self.assertEqual(cb.placeholderText(), "...") cb.grab() cb.addItems(["1"]) cb.setCurrentIndex(0) model = cb.model() model.setItemData(model.index(0, 0), { Qt.ForegroundRole: QColor(Qt.blue), Qt.FontRole: QFont("Windings") }) cb.grab()
def fix_osx_10_9_private_font(): # Fix fonts on Os X (QTBUG 47206, 40833, 32789) if sys.platform == "darwin": import platform try: version = platform.mac_ver()[0] version = float(version[:version.rfind(".")]) if version >= 10.11: # El Capitan QFont.insertSubstitution(".SF NS Text", "Helvetica Neue") elif version >= 10.10: # Yosemite QFont.insertSubstitution(".Helvetica Neue DeskInterface", "Helvetica Neue") elif version >= 10.9: QFont.insertSubstitution(".Lucida Grande UI", "Lucida Grande") except AttributeError: pass
def add_main_layout(self): self.data = None self.preprocessors = None self.learner = None self.scatterplot_item = None self.plot_item = None self.x_label = 'x' self.y_label = 'y' box = gui.vBox(self.controlArea, "Variables") self.x_var_model = itemmodels.VariableListModel() self.comboBoxAttributesX = gui.comboBox( box, self, value='x_var_index', label="Input: ", orientation=Qt.Horizontal, callback=self.apply, contentsLength=12) self.comboBoxAttributesX.setSizePolicy( QSizePolicy.MinimumExpanding, QSizePolicy.Fixed) self.comboBoxAttributesX.setModel(self.x_var_model) gui.doubleSpin( gui.indentedBox(box), self, "polynomialexpansion", 0, 10, label="Polynomial expansion:", callback=self.apply) gui.separator(box, height=8) self.y_var_model = itemmodels.VariableListModel() self.comboBoxAttributesY = gui.comboBox( box, self, value="y_var_index", label="Target: ", orientation=Qt.Horizontal, callback=self.apply, contentsLength=12) self.comboBoxAttributesY.setSizePolicy( QSizePolicy.MinimumExpanding, QSizePolicy.Fixed) self.comboBoxAttributesY.setModel(self.y_var_model) gui.rubber(self.controlArea) # main area GUI self.plotview = pg.PlotWidget(background="w") self.plot = self.plotview.getPlotItem() axis_color = self.palette().color(QPalette.Text) axis_pen = QPen(axis_color) tickfont = QFont(self.font()) tickfont.setPixelSize(max(int(tickfont.pixelSize() * 2 // 3), 11)) axis = self.plot.getAxis("bottom") axis.setLabel(self.x_label) axis.setPen(axis_pen) axis.setTickFont(tickfont) axis = self.plot.getAxis("left") axis.setLabel(self.y_label) axis.setPen(axis_pen) axis.setTickFont(tickfont) self.plot.setRange(xRange=(0.0, 1.0), yRange=(0.0, 1.0), disableAutoRange=True) self.mainArea.layout().addWidget(self.plotview)
class Legend(Anchorable): """Base legend class. This class provides common attributes for any legend subclasses: - Behaviour on `QGraphicsScene` - Appearance of legend Parameters ---------- parent : QGraphicsItem, optional orientation : Qt.Orientation, optional The default orientation is vertical domain : Orange.data.domain.Domain, optional This field is left optional as in some cases, we may want to simply pass in a list that represents the legend. items : Iterable[QColor, str] bg_color : QColor, optional font : QFont, optional color_indicator_cls : ColorIndicator The color indicator class that will be used to render the indicators. See Also -------- OWDiscreteLegend OWContinuousLegend OWContinuousLegend Notes ----- .. warning:: If the domain parameter is supplied, the items parameter will be ignored. """ def __init__(self, parent=None, orientation=Qt.Vertical, domain=None, items=None, bg_color=QColor(232, 232, 232, 196), font=None, color_indicator_cls=LegendItemSquare, **kwargs): super().__init__(parent, **kwargs) self._layout = None self.orientation = orientation self.bg_color = QBrush(bg_color) self.color_indicator_cls = color_indicator_cls # Set default font if none is given if font is None: self.font = QFont() self.font.setPointSize(10) else: self.font = font self.setFlags(QGraphicsWidget.ItemIsMovable | QGraphicsItem.ItemIgnoresTransformations) self._setup_layout() if domain is not None: self.set_domain(domain) elif items is not None: self.set_items(items) def _clear_layout(self): self._layout = None for child in self.children(): child.setParent(None) def _setup_layout(self): self._clear_layout() self._layout = QGraphicsLinearLayout(self.orientation) self._layout.setContentsMargins(10, 5, 10, 5) # If horizontal, there needs to be horizontal space between the items if self.orientation == Qt.Horizontal: self._layout.setSpacing(10) # If vertical spacing, vertical space is provided by child layouts else: self._layout.setSpacing(0) self.setLayout(self._layout) def set_domain(self, domain): """Handle receiving the domain object. Parameters ---------- domain : Orange.data.domain.Domain Returns ------- Raises ------ AttributeError If the domain does not contain the correct type of class variable. """ raise NotImplementedError() def set_items(self, values): """Handle receiving an array of items. Parameters ---------- values : iterable[object, QColor] Returns ------- """ raise NotImplementedError() @staticmethod def _convert_to_color(obj): if isinstance(obj, QColor): return obj elif isinstance(obj, tuple) or isinstance(obj, list): assert len(obj) in (3, 4) return QColor(*obj) else: return QColor(obj) def setVisible(self, is_visible): """Only display the legend if it contains any items.""" return super().setVisible(is_visible and len(self._layout) > 0) def paint(self, painter, options, widget=None): painter.save() pen = QPen(QColor(196, 197, 193, 200), 1) brush = QBrush(QColor(self.bg_color)) painter.setPen(pen) painter.setBrush(brush) painter.drawRect(self.contentsRect()) painter.restore()
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 update_font(basefont, weight=None, italic=None, underline=None, pixelSize=None, pointSize=None): """ Return a copy of `basefont` :class:`QFont` with updated properties. """ font = QFont(basefont) if weight is not None: font.setWeight(weight) if italic is not None: font.setItalic(italic) if underline is not None: font.setUnderline(underline) if pixelSize is not None: font.setPixelSize(pixelSize) if pointSize is not None: font.setPointSize(pointSize) return font
def _init_ui(self): namesBox = gui.vBox(self.controlArea, "Names") hbox = gui.hBox(namesBox, margin=0, spacing=0) gui.lineEdit(hbox, self, "attr1", "Variable X: ", controlWidth=80, orientation=Qt.Horizontal, callback=self._attr_name_changed) gui.separator(hbox, 21) hbox = gui.hBox(namesBox, margin=0, spacing=0) attr2 = gui.lineEdit(hbox, self, "attr2", "Variable Y: ", controlWidth=80, orientation=Qt.Horizontal, callback=self._attr_name_changed) gui.separator(hbox) gui.checkBox(hbox, self, "hasAttr2", '', disables=attr2, labelWidth=0, callback=self.set_dimensions) gui.separator(namesBox) gui.widgetLabel(namesBox, "Labels") self.classValuesView = listView = QListView( selectionMode=QListView.SingleSelection, sizePolicy=QSizePolicy(QSizePolicy.Ignored, QSizePolicy.Maximum) ) listView.setModel(self.class_model) itemmodels.select_row(listView, 0) namesBox.layout().addWidget(listView) self.addClassLabel = QAction( "+", self, toolTip="Add new class label", triggered=self.add_new_class_label ) self.removeClassLabel = QAction( unicodedata.lookup("MINUS SIGN"), self, toolTip="Remove selected class label", triggered=self.remove_selected_class_label ) actionsWidget = itemmodels.ModelActionsWidget( [self.addClassLabel, self.removeClassLabel], self ) actionsWidget.layout().addStretch(10) actionsWidget.layout().setSpacing(1) namesBox.layout().addWidget(actionsWidget) tBox = gui.vBox(self.controlArea, "Tools", addSpace=True) buttonBox = gui.hBox(tBox) toolsBox = gui.widgetBox(buttonBox, orientation=QGridLayout()) self.toolActions = QActionGroup(self) self.toolActions.setExclusive(True) self.toolButtons = [] for i, (name, tooltip, tool, icon) in enumerate(self.TOOLS): action = QAction( name, self, toolTip=tooltip, checkable=tool.checkable, icon=QIcon(icon), ) action.triggered.connect(partial(self.set_current_tool, tool)) button = QToolButton( iconSize=QSize(24, 24), toolButtonStyle=Qt.ToolButtonTextUnderIcon, sizePolicy=QSizePolicy(QSizePolicy.MinimumExpanding, QSizePolicy.Fixed) ) button.setDefaultAction(action) self.toolButtons.append((button, tool)) toolsBox.layout().addWidget(button, i / 3, i % 3) self.toolActions.addAction(action) for column in range(3): toolsBox.layout().setColumnMinimumWidth(column, 10) toolsBox.layout().setColumnStretch(column, 1) undo = self.undo_stack.createUndoAction(self) redo = self.undo_stack.createRedoAction(self) undo.setShortcut(QKeySequence.Undo) redo.setShortcut(QKeySequence.Redo) self.addActions([undo, redo]) self.undo_stack.indexChanged.connect(lambda _: self.invalidate()) gui.separator(tBox) indBox = gui.indentedBox(tBox, sep=8) form = QFormLayout( formAlignment=Qt.AlignLeft, labelAlignment=Qt.AlignLeft, fieldGrowthPolicy=QFormLayout.AllNonFixedFieldsGrow ) indBox.layout().addLayout(form) slider = gui.hSlider( indBox, self, "brushRadius", minValue=1, maxValue=100, createLabel=False ) form.addRow("Radius:", slider) slider = gui.hSlider( indBox, self, "density", None, minValue=1, maxValue=100, createLabel=False ) form.addRow("Intensity:", slider) self.btResetToInput = gui.button( tBox, self, "Reset to Input Data", self.reset_to_input) self.btResetToInput.setDisabled(True) gui.rubber(self.controlArea) gui.auto_commit(self.left_side, self, "autocommit", "Send") # main area GUI viewbox = PaintViewBox(enableMouse=False) self.plotview = pg.PlotWidget(background="w", viewBox=viewbox) self.plotview.sizeHint = lambda: QSize(200, 100) # Minimum size for 1-d painting self.plot = self.plotview.getPlotItem() axis_color = self.palette().color(QPalette.Text) axis_pen = QPen(axis_color) tickfont = QFont(self.font()) tickfont.setPixelSize(max(int(tickfont.pixelSize() * 2 // 3), 11)) axis = self.plot.getAxis("bottom") axis.setLabel(self.attr1) axis.setPen(axis_pen) axis.setTickFont(tickfont) axis = self.plot.getAxis("left") axis.setLabel(self.attr2) axis.setPen(axis_pen) axis.setTickFont(tickfont) if not self.hasAttr2: self.plot.hideAxis('left') self.plot.hideButtons() self.plot.setXRange(0, 1, padding=0.01) self.mainArea.layout().addWidget(self.plotview) # enable brush tool self.toolActions.actions()[0].setChecked(True) self.set_current_tool(self.TOOLS[0][2]) self.set_dimensions()
def add_main_layout(self): self.data = None self.learner = None self.scatterplot_item = None self.plot_item = None self.x_label = 'x' self.y_label = 'y' self.rmse = "" self.mae = "" self.regressor_name = self.default_learner_name # info box info_box = gui.vBox(self.controlArea, "Info") self.regressor_label = gui.label( widget=info_box, master=self, label="Regressor: %(regressor_name).30s") gui.label(widget=info_box, master=self, label="Mean absolute error: %(mae).6s") gui.label(widget=info_box, master=self, label="Root mean square error: %(rmse).6s") box = gui.vBox(self.controlArea, "Variables") self.x_var_model = itemmodels.VariableListModel() self.comboBoxAttributesX = gui.comboBox( box, self, value='x_var_index', label="Input: ", orientation=Qt.Horizontal, callback=self.apply, maximumContentsLength=15) self.comboBoxAttributesX.setModel(self.x_var_model) self.expansion_spin = gui.doubleSpin( gui.indentedBox(box), self, "polynomialexpansion", 0, 10, label="Polynomial expansion:", callback=self.apply) gui.separator(box, height=8) self.y_var_model = itemmodels.VariableListModel() self.comboBoxAttributesY = gui.comboBox( box, self, value="y_var_index", label="Target: ", orientation=Qt.Horizontal, callback=self.apply, maximumContentsLength=15) self.comboBoxAttributesY.setModel(self.y_var_model) properties_box = gui.vBox(self.controlArea, "Properties") self.error_bars_checkbox = gui.checkBox( widget=properties_box, master=self, value='error_bars_enabled', label="Show error bars", callback=self.apply) gui.rubber(self.controlArea) # main area GUI self.plotview = pg.PlotWidget(background="w") self.plot = self.plotview.getPlotItem() axis_color = self.palette().color(QPalette.Text) axis_pen = QPen(axis_color) tickfont = QFont(self.font()) tickfont.setPixelSize(max(int(tickfont.pixelSize() * 2 // 3), 11)) axis = self.plot.getAxis("bottom") axis.setLabel(self.x_label) axis.setPen(axis_pen) axis.setTickFont(tickfont) axis = self.plot.getAxis("left") axis.setLabel(self.y_label) axis.setPen(axis_pen) axis.setTickFont(tickfont) self.plot.setRange(xRange=(0.0, 1.0), yRange=(0.0, 1.0), disableAutoRange=True) self.mainArea.layout().addWidget(self.plotview)
def __on_enrichment_finished(self, results): assert QThread.currentThread() is self.thread() self.__state &= ~OWSetEnrichment.RunningEnrichment query, reference, results = results results = results # type: List[Tuple[geneset.GeneSet, enrichment_res]] nquery = len(query) nref = len(reference) maxcount = max((len(e.query_mapped) for _, e in results), default=1) maxrefcount = max((len(e.reference_mapped) for _, e in results), default=1) nspaces = int(math.ceil(math.log10(maxcount or 1))) refspaces = int(math.ceil(math.log(maxrefcount or 1))) query_fmt = "%" + str(nspaces) + "s (%.2f%%)" ref_fmt = "%" + str(refspaces) + "s (%.2f%%)" def fmt_count(fmt, count, total): return fmt % (count, 100.0 * count / (total or 1)) fmt_query_count = partial(fmt_count, query_fmt, total=nquery) fmt_ref_count = partial(fmt_count, ref_fmt, total=nref) view = self.annotationsChartView delegate = view.itemDelegateForColumn(ResultsModel.Count) if delegate is not None: delegate.deleteLater() delegate = view.itemDelegateForColumn(ResultsModel.Reference) if delegate is not None: delegate.deleteLater() view.setItemDelegateForColumn( ResultsModel.Count, FormatItemDelegate(fmt_query_count, self) ) view.setItemDelegateForColumn( ResultsModel.Reference, FormatItemDelegate(fmt_ref_count, self) ) linkFont = QFont(self.annotationsChartView.viewOptions().font) linkFont.setUnderline(True) def item(value=None, tooltip=None, user=None): si = QStandardItem() if value is not None: si.setData(value, Qt.DisplayRole) if tooltip is not None: si.setData(tooltip, Qt.ToolTipRole) if user is not None: si.setData(user, Qt.UserRole) else: si.setData(value, Qt.UserRole) return si model = ResultsModel(parent=self) for i, (gset, enrich) in enumerate(results): if len(enrich.query_mapped) == 0: continue nquery_mapped = len(enrich.query_mapped) nref_mapped = len(enrich.reference_mapped) row = [ item(", ".join(gset.hierarchy)), item(gsname(gset), tooltip=gset.link), item(nquery_mapped, tooltip=nquery_mapped, user=nquery_mapped), item(nref_mapped, tooltip=nref_mapped, user=nref_mapped), item(enrich.p_value, user=enrich.p_value), item(np.nan), # column 5, FDR, is computed in _updateFDR item(enrich.enrichment_score, tooltip="%.3f" % enrich.enrichment_score, user=enrich.enrichment_score) ] row[0].geneset = gset row[0].enrichment = enrich if gset.link: row[1].setData(gset.link, gui.LinkRole) row[1].setFont(linkFont) row[1].setForeground(QColor(Qt.blue)) model.appendRow(row) currmodel = self.proxy.sourceModel() currmodel.deleteLater() self.proxy.setSourceModel(model) if not model.rowCount(): self.warning(0, "No enriched sets found.") else: self.warning(0) allnames = set(gsname(geneset) for geneset, (count, _, _, _) in results if count) allnames |= reduce(operator.ior, (set(word_split(name)) for name in allnames), set()) self.filterCompleter.setModel(None) self.completerModel = QStringListModel(sorted(allnames)) self.filterCompleter.setModel(self.completerModel) if results: max_score = max((e.enrichment_score for _, e in results if np.isfinite(e.enrichment_score)), default=1) self.annotationsChartView.setItemDelegateForColumn( ResultsModel.Enrichment, BarItemDelegate(self, scale=(0.0, max_score)) ) self.annotationsChartView.setItemDelegateForColumn( ResultsModel.TermID, gui.LinkStyledItemDelegate(self.annotationsChartView) ) self._updateFDR() self.filterAnnotationsChartView() header = self.annotationsChartView.header() for i in range(model.columnCount()): sh = self.annotationsChartView.sizeHintForColumn(i) sh = max(header.sectionSizeHint(i), sh) width = self.annotationsChartView.columnWidth(i) if min(sh, 300) > width: self.annotationsChartView.setColumnWidth(i, max(min(sh, 300), 30)) self.progressBarFinished() self.setStatusMessage("")
def __init__(self): super().__init__() self.results = None self.classifier_names = [] self.perf_line = None self.colors = [] self._curve_data = {} self._plot_curves = {} self._rocch = None self._perf_line = None box = gui.vBox(self.controlArea, "Plot") tbox = gui.vBox(box, "Target Class") tbox.setFlat(True) self.target_cb = gui.comboBox( tbox, self, "target_index", callback=self._on_target_changed, contentsLength=8) cbox = gui.vBox(box, "Classifiers") cbox.setFlat(True) self.classifiers_list_box = gui.listBox( cbox, self, "selected_classifiers", "classifier_names", selectionMode=QListView.MultiSelection, callback=self._on_classifiers_changed) abox = gui.vBox(box, "Combine ROC Curves From Folds") abox.setFlat(True) gui.comboBox(abox, self, "roc_averaging", items=["Merge Predictions from Folds", "Mean TP Rate", "Mean TP and FP at Threshold", "Show Individual Curves"], callback=self._replot) hbox = gui.vBox(box, "ROC Convex Hull") hbox.setFlat(True) gui.checkBox(hbox, self, "display_convex_curve", "Show convex ROC curves", callback=self._replot) gui.checkBox(hbox, self, "display_convex_hull", "Show ROC convex hull", callback=self._replot) box = gui.vBox(self.controlArea, "Analysis") gui.checkBox(box, self, "display_def_threshold", "Default threshold (0.5) point", callback=self._on_display_def_threshold_changed) gui.checkBox(box, self, "display_perf_line", "Show performance line", callback=self._on_display_perf_line_changed) grid = QGridLayout() ibox = gui.indentedBox(box, orientation=grid) sp = gui.spin(box, self, "fp_cost", 1, 1000, 10, callback=self._on_display_perf_line_changed) grid.addWidget(QLabel("FP Cost:"), 0, 0) grid.addWidget(sp, 0, 1) sp = gui.spin(box, self, "fn_cost", 1, 1000, 10, callback=self._on_display_perf_line_changed) grid.addWidget(QLabel("FN Cost:")) grid.addWidget(sp, 1, 1) sp = gui.spin(box, self, "target_prior", 1, 99, callback=self._on_display_perf_line_changed) sp.setSuffix("%") sp.addAction(QAction("Auto", sp)) grid.addWidget(QLabel("Prior target class probability:")) grid.addWidget(sp, 2, 1) self.plotview = pg.GraphicsView(background="w") self.plotview.setFrameStyle(QFrame.StyledPanel) self.plot = pg.PlotItem(enableMenu=False) self.plot.setMouseEnabled(False, False) self.plot.hideButtons() pen = QPen(self.palette().color(QPalette.Text)) tickfont = QFont(self.font()) tickfont.setPixelSize(max(int(tickfont.pixelSize() * 2 // 3), 11)) axis = self.plot.getAxis("bottom") axis.setTickFont(tickfont) axis.setPen(pen) axis.setLabel("FP Rate (1-Specificity)") axis = self.plot.getAxis("left") axis.setTickFont(tickfont) axis.setPen(pen) axis.setLabel("TP Rate (Sensitivity)") self.plot.showGrid(True, True, alpha=0.1) self.plot.setRange(xRange=(0.0, 1.0), yRange=(0.0, 1.0), padding=0.05) self.plotview.setCentralItem(self.plot) self.mainArea.layout().addWidget(self.plotview)
def __on_enrichment_finished(self, results): assert QThread.currentThread() is self.thread() self.__state &= ~OWSetEnrichment.RunningEnrichment query, reference, results = results if self.annotationsChartView.model(): self.annotationsChartView.model().clear() nquery = len(query) nref = len(reference) maxcount = max((len(e.query_mapped) for _, e in results), default=1) maxrefcount = max((len(e.reference_mapped) for _, e in results), default=1) nspaces = int(math.ceil(math.log10(maxcount or 1))) refspaces = int(math.ceil(math.log(maxrefcount or 1))) query_fmt = "%" + str(nspaces) + "s (%.2f%%)" ref_fmt = "%" + str(refspaces) + "s (%.2f%%)" def fmt_count(fmt, count, total): return fmt % (count, 100.0 * count / (total or 1)) fmt_query_count = partial(fmt_count, query_fmt) fmt_ref_count = partial(fmt_count, ref_fmt) linkFont = QFont(self.annotationsChartView.viewOptions().font) linkFont.setUnderline(True) def item(value=None, tooltip=None, user=None): si = QStandardItem() if value is not None: si.setData(value, Qt.DisplayRole) if tooltip is not None: si.setData(tooltip, Qt.ToolTipRole) if user is not None: si.setData(user, Qt.UserRole) else: si.setData(value, Qt.UserRole) return si model = QStandardItemModel() model.setSortRole(Qt.UserRole) model.setHorizontalHeaderLabels( ["Category", "Term", "Count", "Reference count", "p-value", "FDR", "Enrichment"]) for i, (gset, enrich) in enumerate(results): if len(enrich.query_mapped) == 0: continue nquery_mapped = len(enrich.query_mapped) nref_mapped = len(enrich.reference_mapped) row = [ item(", ".join(gset.hierarchy)), item(gsname(gset), tooltip=gset.link), item(fmt_query_count(nquery_mapped, nquery), tooltip=nquery_mapped, user=nquery_mapped), item(fmt_ref_count(nref_mapped, nref), tooltip=nref_mapped, user=nref_mapped), item(fmtp(enrich.p_value), user=enrich.p_value), item(), # column 5, FDR, is computed in filterAnnotationsChartView item(enrich.enrichment_score, tooltip="%.3f" % enrich.enrichment_score, user=enrich.enrichment_score) ] row[0].geneset = gset row[0].enrichment = enrich row[1].setData(gset.link, gui.LinkRole) row[1].setFont(linkFont) row[1].setForeground(QColor(Qt.blue)) model.appendRow(row) self.annotationsChartView.setModel(model) self.annotationsChartView.selectionModel().selectionChanged.connect( self.commit ) if not model.rowCount(): self.warning(0, "No enriched sets found.") else: self.warning(0) allnames = set(gsname(geneset) for geneset, (count, _, _, _) in results if count) allnames |= reduce(operator.ior, (set(word_split(name)) for name in allnames), set()) self.filterCompleter.setModel(None) self.completerModel = QStringListModel(sorted(allnames)) self.filterCompleter.setModel(self.completerModel) if results: max_score = max((e.enrichment_score for _, e in results if np.isfinite(e.enrichment_score)), default=1) self.annotationsChartView.setItemDelegateForColumn( 6, BarItemDelegate(self, scale=(0.0, max_score)) ) self.annotationsChartView.setItemDelegateForColumn( 1, gui.LinkStyledItemDelegate(self.annotationsChartView) ) header = self.annotationsChartView.header() for i in range(model.columnCount()): sh = self.annotationsChartView.sizeHintForColumn(i) sh = max(sh, header.sectionSizeHint(i)) self.annotationsChartView.setColumnWidth(i, max(min(sh, 300), 30)) # self.annotationsChartView.resizeColumnToContents(i) self.filterAnnotationsChartView() self.progressBarFinished() self.setStatusMessage("")