def data(self, index, role=qt.Qt.DisplayRole): if not index.isValid(): return item = index.internalPointer() if role in (qt.Qt.DisplayRole, qt.Qt.EditRole): return item.data(index.column()) elif role == qt.Qt.CheckStateRole: if index.column() == 1: return int( qt.Qt.Checked if item.isVisible else qt.Qt.Unchecked) elif role == qt.Qt.ToolTipRole: if index.column() == 0: return item.tooltip() elif role == qt.Qt.BackgroundRole: if item.beingTransformed and index.column() == 0: return BUSY_BKGND if item.childItems: # is a group return GROUP_BKGND color = BKGND[item.get_state(index.column())] if color is not None: return color elif role == qt.Qt.ForegroundRole: if index.column() < len(csi.modelLeadingColumns): return qt.QColor(FONT_COLOR_TAG[item.colorTag]) else: return qt.QColor(item.color()) elif role == qt.Qt.FontRole: if item.childItems and (index.column() == 0): # group in bold myFont = qt.QFont() myFont.setBold(True) return myFont elif role == qt.Qt.TextAlignmentRole: if index.column() == 1: return qt.Qt.AlignCenter
def _updatePrinter(self): """Resize :attr:`page`, :attr:`scene` and :attr:`view` to :attr:`printer` width and height.""" printer = self.printer assert printer is not None, \ "_updatePrinter should not be called unless a printer is defined" if self.scene is None: self.scene = qt.QGraphicsScene() self.scene.setBackgroundBrush(qt.QColor(qt.Qt.lightGray)) self.scene.setSceneRect( qt.QRectF(0, 0, printer.width(), printer.height())) if self.page is None: self.page = qt.QGraphicsRectItem(0, 0, printer.width(), printer.height()) self.page.setBrush(qt.QColor(qt.Qt.white)) self.scene.addItem(self.page) self.scene.setSceneRect( qt.QRectF(0, 0, printer.width(), printer.height())) self.page.setPos(qt.QPointF(0.0, 0.0)) self.page.setRect(qt.QRectF(0, 0, printer.width(), printer.height())) if self.view is None: self.view = qt.QGraphicsView(self.scene) self.mainLayout.addWidget(self.view) self._buildStatusBar() # self.view.scale(1./self._viewScale, 1./self._viewScale) self.view.fitInView(self.page.rect(), qt.Qt.KeepAspectRatio) self._viewScale = 1.00 self._updateTargetLabel()
def paintEvent(self, event): border = self._histoBorder pixmap = self.__pixmap painter = Qt.QPainter(self) rect = self.frameRect().adjusted(border, border, -border, -border) if not pixmap: painter.save() painter.setPen(Qt.QColor(Qt.Qt.gray)) painter.setBrush(Qt.QColor(Qt.Qt.white)) painter.drawRect(rect) painter.restore() else: painter.drawPixmap(rect, pixmap, pixmap.rect()) painter.save() painter.setBrush(Qt.QColor(Qt.Qt.black)) lineMin = self.__lineMin if lineMin: xLine = lineMin * (rect.width() - 1.) / (pixmap.width() - 1) painter.drawRect(xLine - 2, 0, 2, rect.height()) lineMax = self.__lineMax if lineMax: xLine = lineMax * (rect.width() - 1.) / (pixmap.width() - 1) painter.drawRect(xLine + 2, 0, 2, rect.height()) painter.restore()
def paint(self, painter, option, index): txt = index.model().data(index, qt.Qt.DisplayRole) if txt == '': return if txt.startswith('no'): super(SymbolDelegate, self).paint(painter, option, index) return lineSymbol = lineSymbols[lineSymbolsText[txt]] painter.save() painter.setRenderHint(qt.QPainter.Antialiasing, True) rect = option.rect rect.adjust(+5, 0, -5, 0) symbolFC = qt.QColor(self.parent().color) symbolEC = qt.QColor(self.parent().color) # symbolSize = self.parent().sizeSpinBox.value() * 2 symbolSize = (self.parent().sizeSpinBox.value() + 1) * 1.75 symbolPath = qt.QPainterPath(lineSymbol) scale = symbolSize painter.scale(scale, scale) symbolOffset = qt.QPointF( (rect.left() + rect.right() - symbolSize) * 0.5 / scale, (rect.top() + rect.bottom() - symbolSize) * 0.5 / scale) symbolPath.translate(symbolOffset) symbolBrush = qt.QBrush(symbolFC, qt.Qt.SolidPattern) symbolPen = qt.QPen(symbolEC, 1. / scale, qt.Qt.SolidLine) painter.setPen(symbolPen) painter.setBrush(symbolBrush) painter.drawPath(symbolPath) painter.restore()
def setFloatingTabColor(self, state): pal = self.title.palette() if state == 1: pal.setColor(qt.QPalette.WindowText, qt.QColor("deepskyblue")) self.titleIcon.setVisible(True) else: pal.setColor(qt.QPalette.WindowText, qt.QColor("black")) self.titleIcon.setVisible(False) self.title.setPalette(pal) self.update()
def _update(self): data, exptime = self._get_data() E = np.arange(data.shape[1]) * 10 # ad hoc for i in range(data.shape[0]): self.addCurve(E, data[i, :], legend=str(i), resetzoom=(not self.hasData)) self.hasData = True sums = np.sum(data, axis=1) self.setGraphTitle('max(Channels 0,1,2): %.1e (%.1e / s)\nChannel 3: %.1e (%.1e / s)' % (np.max(sums[0:3]), np.max(sums[0:3])/exptime, sums[3], sums[3]/exptime)) if (self.alarm is not None) and (sums.max()/exptime > self.alarm): self.setBackgroundColor(qt.QColor(255, 0, 0)) else: self.setBackgroundColor(qt.QColor(255, 255, 255))
def makeGradientCollection(color1, color2, ncolor=8): c1 = np.array(qt.QColor(color1).getHsvF()) c2 = np.array(qt.QColor(color2).getHsvF()) c1[c1 < 0] = 0 # for gray, getHsvF returns hue=-1 that is not accepted by fromHsv # noqa c2[c2 < 0] = 0 t = np.linspace(0, 1, ncolor)[:, np.newaxis] colors = c1 * (1 - t) + c2 * t res = [] for i in range(ncolor): res.append(qt.QColor.fromHsvF(*colors[i])) return res
def _update(self): image, exptime = self._get_image() if image is None: return self.setImage(image, copy=False, reset=(not self.hasImage)) self.hasImage = True total = np.sum(image) hottest = np.max(image) if (self.alarm is not None) and (hottest/exptime > self.alarm): self.setBackgroundColor(qt.QColor(255, 0, 0)) else: self.setBackgroundColor(qt.QColor(255, 255, 255)) self.setGraphTitle('Total: %.1e (%.1e / s) \n Hottest: %.1e (%.1e / s)' % (total, total/exptime, hottest, hottest/exptime)) self._positionWidget.updateInfo()
def icon(self): pixmap = qt.QPixmap(2, 2) painter = qt.QPainter(pixmap) painter.setPen(qt.QColor(255, 0, 0)) painter.drawPoint(qt.QPoint(0, 0)) painter.setPen(qt.QColor(255, 255, 0)) painter.drawPoint(qt.QPoint(1, 0)) painter.setPen(qt.QColor(0, 255, 0)) painter.drawPoint(qt.QPoint(0, 1)) painter.setPen(qt.QColor(0, 255, 255)) painter.drawPoint(qt.QPoint(1, 1)) painter.end() pixmap = pixmap.scaled(32, 32, qt.Qt.IgnoreAspectRatio, qt.Qt.FastTransformation) return qt.QIcon(pixmap)
def paintEvent(self, e): txt = self.currentText() if txt.startswith('no'): super(LineStyleComboBox, self).paintEvent(e) return lineStyle = lineStyles[lineStylesText[txt]] p = qt.QStylePainter(self) p.setPen(self.palette().color(qt.QPalette.Text)) opt = qt.QStyleOptionComboBox() self.initStyleOption(opt) p.drawComplexControl(qt.QStyle.CC_ComboBox, opt) painter = qt.QPainter(self) painter.save() painter.setRenderHint(qt.QPainter.Antialiasing, False) rect = p.style().subElementRect(qt.QStyle.SE_ComboBoxFocusRect, opt, self) rect.adjust(+5, 0, -5, 0) pen = qt.QPen() pen.setColor(qt.QColor(self.parent().color)) pen.setWidth(self.parent().widthSpinBox.value() * 1.5) pen.setStyle(lineStyle) painter.setPen(pen) middle = (rect.bottom() + rect.top()) / 2 painter.drawLine(rect.left(), middle, rect.right(), middle) painter.restore()
def __init__(self, parent): super(_PeakSelectionTableView, self).__init__(parent=parent) ringDelegate = _SpinBoxItemDelegate(self) palette = qt.QPalette(self.palette()) # make sure this value is not edited palette.setColor(qt.QPalette.Base, palette.base().color()) ringDelegate.setPalette(palette) toolDelegate = _PeakToolItemDelegate(self) self.setItemDelegateForColumn(2, ringDelegate) self.setItemDelegateForColumn(3, toolDelegate) # self.setSelectionMode(qt.QAbstractItemView.SingleSelection) self.setSelectionMode(qt.QAbstractItemView.NoSelection) self.setSelectionBehavior(qt.QAbstractItemView.SelectRows) self.setVerticalScrollMode(qt.QAbstractItemView.ScrollPerPixel) self.setShowGrid(False) self.setWordWrap(False) # NoFrame glitchies on Debian8 Qt5 # self.setFrameShape(qt.QFrame.NoFrame) self.horizontalHeader().setHighlightSections(False) self.verticalHeader().setVisible(False) palette = qt.QPalette(self.palette()) palette.setColor(qt.QPalette.Base, qt.QColor(0, 0, 0, 0)) self.setPalette(palette) self.setFrameShape(qt.QFrame.Panel)
def openColorDialog(self, policy): title = 'Select Color' self.initColorOption(policy) if policy == gco.COLOR_POLICY_INDIVIDUAL: initialColor = self.color elif policy == gco.COLOR_POLICY_GRADIENT: if self.colorSeq % 2 == 0: initialColor = self.color1 title += ' 1' else: initialColor = self.color2 title += ' 2' else: return initialColor = qt.QColor(initialColor) color = qt.QColorDialog.getColor( title=title, parent=self, initial=initialColor, options=qt.QColorDialog.ShowAlphaChannel) if color.isValid(): self.setButtonColor(color, policy) if policy == gco.COLOR_POLICY_GRADIENT: self.colorSeq += 1 for tab in self.tabs: tab.color = color
def data(self, index, role=qt.Qt.DisplayRole): if not index.isValid(): return if role == LOAD_DATASET_ROLE: return self.tryLoadDataset(index) if role == USE_HDF5_ARRAY_ROLE: return self.getHDF5ArrayPath(index) nodeType = self.nodeType(index) if nodeType == NODE_FS: indexFS = self.mapToFS(index) if role == LOAD_ITEM_PATH_ROLE: return self.filePath(indexFS) if role == qt.Qt.ForegroundRole: fileInfo = self.fsModel.fileInfo(index) if is_text_file(fileInfo.filePath()): return qt.QColor(gco.COLOR_FS_COLUMN_FILE) if self.fsModel is self: return super(FileSystemWithHdf5Model, self).data(index, role) return self.fsModel.data(indexFS, role) elif nodeType == NODE_HDF5: if role == LOAD_ITEM_PATH_ROLE: return self.getHDF5FullPath(index) indexH5 = self.mapToH5(index) if useProxyModel: return self.h5ProxyModel.data( self.h5ProxyModel.mapFromSource(indexH5), role) else: return self.h5Model.data(indexH5, role) elif nodeType == NODE_HDF5_HEAD: indexFS = self.mapToFS(index) fileInfo = self.fsModel.fileInfo(indexFS) if role == qt.Qt.ToolTipRole: indexH5 = self.mapFStoH5(indexFS) return self.h5Model.data(indexH5, role) elif role == qt.Qt.ForegroundRole: return qt.QColor(gco.COLOR_HDF5_HEAD) elif role == qt.Qt.DecorationRole: if useProxyModel and \ index.column() == self.h5Model.NAME_COLUMN: ic = super(FileSystemWithHdf5Model, self).data(index, role) return self.h5ProxyModel.getNxIcon(ic) if self.fsModel is self: return super(FileSystemWithHdf5Model, self).data(index, role) return self.fsModel.data(indexFS, role) else: raise ValueError('unknown node type in `data`')
class QColorEditor(qt.QWidget): """ QColor editor. """ sigColorChanged = qt.Signal(object) color = property(lambda self: qt.QColor(self.__color)) @color.setter def color(self, color): self._setColor(color) self.__previousColor = color def __init__(self, *args, **kwargs): super(QColorEditor, self).__init__(*args, **kwargs) layout = qt.QHBoxLayout(self) layout.setContentsMargins(0, 0, 0, 0) button = qt.QToolButton() icon = qt.QIcon(qt.QPixmap(32, 32)) button.setIcon(icon) layout.addWidget(button) button.clicked.connect(self.__showColorDialog) layout.addStretch(1) self.__color = None self.__previousColor = None def sizeHint(self): return qt.QSize(0, 0) def _setColor(self, qColor): button = self.findChild(qt.QToolButton) pixmap = qt.QPixmap(32, 32) pixmap.fill(qColor) button.setIcon(qt.QIcon(pixmap)) self.__color = qColor def __showColorDialog(self): dialog = qt.QColorDialog(parent=self) if sys.platform == 'darwin': # Use of native color dialog on macos might cause problems dialog.setOption(qt.QColorDialog.DontUseNativeDialog, True) self.__previousColor = self.__color dialog.setAttribute(qt.Qt.WA_DeleteOnClose) dialog.setModal(True) dialog.currentColorChanged.connect(self.__colorChanged) dialog.finished.connect(self.__dialogClosed) dialog.show() def __colorChanged(self, color): self.__color = color self._setColor(color) self.sigColorChanged.emit(color) def __dialogClosed(self, result): if result == qt.QDialog.Rejected: self.__colorChanged(self.__previousColor) self.__previousColor = None
def __init__(self, parent=None): """Constructor""" super(_HashDropZones, self).__init__(parent) pen = qt.QPen() pen.setColor(qt.QColor("#D0D0D0")) pen.setStyle(qt.Qt.DotLine) pen.setWidth(2) self.__dropPen = pen
def testSimple(self): """Set the data and an isosurface""" data = self._buildData(size=32) self.widget.setData(data) self.widget.addIsosurface(0.5, (1., 0., 0., 0.5)) self.widget.addIsosurface(0.7, qt.QColor('green')) self.qapp.processEvents()
def _setupNode(self): plot = self.subject curveName = self.branchName # [x, y, legend, info, parameters] curveInfo = plot.getCurve(legend=curveName)[4] color = Qt.QColor(curveInfo['color']) self.setData(ModelColumns.NameColumn, color, role=Qt.Qt.DecorationRole)
def changeWindowFlags(self, node, evt): if self.isFloating(): # The dockWidget will automatically regain it's Qt::widget flag # when it becomes docked again self.setWindowFlags(qt.Qt.Window | qt.Qt.CustomizeWindowHint | qt.Qt.WindowMaximizeButtonHint) # setWindowFlags calls setParent() when changing the flags for a # window, causing the widget to be hidden, so: self.show() # Custom title bar: self.titleBar = qt.QWidget() self.titleBar.setAutoFillBackground(True) self.titleBar.setStyleSheet("QWidget {font: bold; font-size: " + fontSize + "pt;}") pal = self.titleBar.palette() pal.setColor(qt.QPalette.Window, qt.QColor("lightgray")) self.titleBar.setPalette(pal) height = qt.QApplication.style().pixelMetric( qt.QStyle.PM_TitleBarHeight) self.titleBar.setMaximumHeight(height) layout = qt.QHBoxLayout() self.titleBar.setLayout(layout) buttonSize = qt.QSize(height - 16, height - 16) self.titleIcon = qt.QLabel() # self.titleIcon.setPixmap(self.parent().runIcon.pixmap(buttonSize)) self.titleIcon.setPixmap(node.widget.dimIcon.pixmap(buttonSize)) self.titleIcon.setVisible(True) layout.addWidget(self.titleIcon, 0) self.title = qt.QLabel(self.windowTitle()) layout.addWidget(self.title, 0) layout.setContentsMargins(4, 4, 4, 4) layout.addStretch() self.dockButton = qt.QToolButton(self) self.dockButton.setIcon(qt.QApplication.style().standardIcon( qt.QStyle.SP_ToolBarVerticalExtensionButton)) self.dockButton.setMaximumSize(buttonSize) self.dockButton.setAutoRaise(True) self.dockButton.clicked.connect(self.toggleFloating) self.dockButton.setToolTip('dock into the main window') layout.addWidget(self.dockButton, 0) self.maxButton = qt.QToolButton(self) self.maxButton.setIcon(qt.QApplication.style().standardIcon( qt.QStyle.SP_TitleBarMaxButton)) self.maxButton.setMaximumSize(buttonSize) self.maxButton.setAutoRaise(True) self.maxButton.clicked.connect(self.toggleMax) layout.addWidget(self.maxButton, 0) self.setTitleBarWidget(self.titleBar) else: self.setTitleBarWidget(None) self.parent().setTabIcons()
def hoverLeaveEvent(self, event): self.setCursor(qt.QCursor(qt.Qt.ArrowCursor)) pen = qt.QPen() color = qt.QColor(qt.Qt.white) color.setAlpha(0) pen.setColor(color) pen.setStyle(qt.Qt.NoPen) self.setPen(pen) self.setBrush(color) return qt.QGraphicsRectItem.hoverLeaveEvent(self, event)
def testConvertArrayToQImage(self): """Test conversion of numpy array to QImage""" for format_, channels in [('Format_RGB888', 3), ('Format_ARGB32', 4)]: with self.subTest(format_): image = numpy.arange(3 * 3 * channels, dtype=numpy.uint8).reshape( 3, 3, channels) qimage = convertArrayToQImage(image) self.assertEqual(qimage.height(), image.shape[0]) self.assertEqual(qimage.width(), image.shape[1]) self.assertEqual(qimage.format(), getattr(qt.QImage, format_)) for row in range(3): for col in range(3): # Qrgb has no alpha channel, not compared # Qt uses x,y while array is row,col... self.assertEqual(qt.QColor(qimage.pixel(col, row)), qt.QColor(*image[row, col, :3]))
def testConvertArrayToQImage(self): """Test conversion of numpy array to QImage""" image = numpy.ones((3, 3, 3), dtype=numpy.uint8) qimage = _utils.convertArrayToQImage(image) self.assertEqual(qimage.height(), image.shape[0]) self.assertEqual(qimage.width(), image.shape[1]) self.assertEqual(qimage.format(), qt.QImage.Format_RGB888) color = qt.QColor(1, 1, 1).rgb() self.assertEqual(qimage.pixel(1, 1), color)
class _CellFilterAvailableData(_CellData): """Cell rendering for availability of a filter""" _states = { True: ("Available", qt.QColor(0x000000), None, None), False: ("Not available", qt.QColor(0xFFFFFF), qt.QColor(0xFF0000), "You have to install this filter on your system to be able to read this dataset" ), "na": ("n.a.", qt.QColor(0x000000), None, "This version of h5py/hdf5 is not able to display the information"), } def __init__(self, filterId): import h5py.version if h5py.version.hdf5_version_tuple >= (1, 10, 2): # Previous versions only returns True if the filter was first used # to decode a dataset import h5py.h5z self.__availability = h5py.h5z.filter_avail(filterId) else: self.__availability = "na" _CellData.__init__(self) def value(self): state = self._states[self.__availability] return state[0] def tooltip(self): state = self._states[self.__availability] return state[3] def data(self, role=qt.Qt.DisplayRole): state = self._states[self.__availability] if role == qt.Qt.TextColorRole: return state[1] elif role == qt.Qt.BackgroundColorRole: return state[2] else: return None
def testColors(self): a = numpy.arange(256, dtype=numpy.uint8) self.aw.setArrayData(a) bgcolor = numpy.empty(a.shape + (3,), dtype=numpy.uint8) # Black & white palette bgcolor[..., 0] = a bgcolor[..., 1] = a bgcolor[..., 2] = a fgcolor = numpy.bitwise_xor(bgcolor, 255) self.aw.setArrayColors(bgcolor, fgcolor) # test colors are as expected in model for i in range(256): # all RGB channels for BG equal to data value self.assertEqual( self.aw.model.data(self.aw.model.index(0, i), role=qt.Qt.BackgroundRole), qt.QColor(i, i, i), "Unexpected background color" ) # all RGB channels for FG equal to XOR(data value, 255) self.assertEqual( self.aw.model.data(self.aw.model.index(0, i), role=qt.Qt.ForegroundRole), qt.QColor(i ^ 255, i ^ 255, i ^ 255), "Unexpected text color" ) # test colors are reset to None when a new data array is loaded # with different shape self.aw.setArrayData(numpy.arange(300)) for i in range(300): # all RGB channels for BG equal to data value self.assertIsNone( self.aw.model.data(self.aw.model.index(0, i), role=qt.Qt.BackgroundRole))
def getBackgroundColor(self): """Returns the Qt color used to display part of the diagram outside of the data. :rtype: qt.QColor """ colors = self.__rawColormap.getNColors() color = colors[0] color = 255 - ((255 - color) // 2) color = int(color.mean()) color = [color, color, color] return qt.QColor(color[0], color[1], color[2])
def testCustomElements(self): PTI = PeriodicTable.ColoredPeriodicTableItem my_items = [ PTI("Xx", 42, 43, 44, "xaxatorium", 1002.2, bgcolor="#FF0000"), PTI("Yy", 25, 22, 44, "yoyotrium", 8.8) ] pt = PeriodicTable.PeriodicTable(elements=my_items) pt.setSelection(["He", "Xx"]) selection = pt.getSelection() self.assertEqual(len(selection), 1) # "He" not found self.assertEqual(selection[0].symbol, "Xx") self.assertEqual(selection[0].Z, 42) self.assertEqual(selection[0].col, 43) self.assertAlmostEqual(selection[0].mass, 1002.2) self.assertEqual(qt.QColor(selection[0].bgcolor), qt.QColor(qt.Qt.red)) self.assertTrue(pt.isElementSelected("Xx")) self.assertFalse(pt.isElementSelected("Yy")) self.assertRaises(KeyError, pt.isElementSelected, "Yx")
def testColors(self): """Test setting scene colors""" sceneWidget = self.window.getSceneWidget() color = qt.QColor(128, 128, 128) sceneWidget.setBackgroundColor(color) self.assertEqual(sceneWidget.getBackgroundColor(), color) color = qt.QColor(0, 0, 0) sceneWidget.setForegroundColor(color) self.assertEqual(sceneWidget.getForegroundColor(), color) color = qt.QColor(255, 0, 0) sceneWidget.setTextColor(color) self.assertEqual(sceneWidget.getTextColor(), color) color = qt.QColor(0, 255, 0) sceneWidget.setHighlightColor(color) self.assertEqual(sceneWidget.getHighlightColor(), color) self.qapp.processEvents()
def data(self, index, role=qt.Qt.DisplayRole): """QAbstractTableModel method to access data values in the format ready to be displayed""" if index.isValid(): selection = self._getIndexTuple(index.row(), index.column()) if role == qt.Qt.DisplayRole: return self._formatter.toString(self._array[selection], self._array.dtype) if role == qt.Qt.BackgroundRole and self._bgcolors is not None: r, g, b = self._bgcolors[selection][0:3] if self._bgcolors.shape[-1] == 3: return qt.QColor(r, g, b) if self._bgcolors.shape[-1] == 4: a = self._bgcolors[selection][3] return qt.QColor(r, g, b, a) if role == qt.Qt.ForegroundRole: if self._fgcolors is not None: r, g, b = self._fgcolors[selection][0:3] if self._fgcolors.shape[-1] == 3: return qt.QColor(r, g, b) if self._fgcolors.shape[-1] == 4: a = self._fgcolors[selection][3] return qt.QColor(r, g, b, a) # no fg color given, use black or white # based on luminosity threshold elif self._bgcolors is not None: r, g, b = self._bgcolors[selection][0:3] lum = 0.21 * r + 0.72 * g + 0.07 * b if lum < 128: return qt.QColor(qt.Qt.white) else: return qt.QColor(qt.Qt.black)
def testNaNColor(self): """Test Colormap.applyToData with NaN values""" colormap = Colormap(name='gray', normalization='linear') colormap.setNaNColor('red') self.assertEqual(colormap.getNaNColor(), qt.QColor(255, 0, 0)) data = numpy.array([50., numpy.nan]) image = items.ImageData() image.setData(numpy.array([[0, 100]])) value = colormap.applyToData(data, reference=image) self.assertEqual(len(value), 2) self.assertTrue(numpy.array_equal(value[0], (128, 128, 128, 255))) self.assertTrue(numpy.array_equal(value[1], (255, 0, 0, 255)))
def __init__(self, item, parent=None): """ :param parent: Parent widget :param PeriodicTableItem item: :class:`PeriodicTableItem` object """ qt.QPushButton.__init__(self, parent) self.item = item """:class:`PeriodicTableItem` object represented by this button""" self.setText(item.symbol) self.setFlat(1) self.setCheckable(0) self.setSizePolicy( qt.QSizePolicy(qt.QSizePolicy.Expanding, qt.QSizePolicy.Expanding)) self.selected = False self.current = False # selection colors self.selected_color = qt.QColor(qt.Qt.yellow) self.current_color = qt.QColor(qt.Qt.gray) self.selected_current_color = qt.QColor(qt.Qt.darkYellow) # element colors if hasattr(item, "bgcolor"): self.bgcolor = qt.QColor(item.bgcolor) else: self.bgcolor = qt.QColor("#FFFFFF") self.brush = qt.QBrush() self.__setBrush() self.clicked.connect(self.clickedSlot)
def paintEvent(self, e): txt = self.currentText() if txt == '': return if txt.startswith('no'): super(SymbolComboBox, self).paintEvent(e) return lineSymbol = lineSymbols[lineSymbolsText[txt]] p = qt.QStylePainter(self) p.setPen(self.palette().color(qt.QPalette.Text)) opt = qt.QStyleOptionComboBox() self.initStyleOption(opt) p.drawComplexControl(qt.QStyle.CC_ComboBox, opt) painter = qt.QPainter(self) painter.save() painter.setRenderHint(qt.QPainter.Antialiasing, True) rect = p.style().subElementRect(qt.QStyle.SE_ComboBoxFocusRect, opt, self) rect.adjust(+5, 0, -5, 0) symbolFC = qt.QColor(self.parent().color) symbolEC = qt.QColor(self.parent().color) symbolSize = self.parent().sizeSpinBox.value() * 2 symbolPath = qt.QPainterPath(lineSymbol) scale = symbolSize painter.scale(scale, scale) symbolOffset = qt.QPointF( (rect.left() + rect.right() - symbolSize) * 0.5 / scale, (rect.top() + rect.bottom() - symbolSize) * 0.5 / scale) symbolPath.translate(symbolOffset) symbolBrush = qt.QBrush(symbolFC, qt.Qt.SolidPattern) symbolPen = qt.QPen(symbolEC, 1. / scale, qt.Qt.SolidLine) painter.setPen(symbolPen) painter.setBrush(symbolBrush) painter.drawPath(symbolPath) painter.restore()