import sys from PyQt5 import QtWidgets, QtGui, QtCore class PingLeiItem(QtWidgets.QGraphicsItem): def __init__(self): QtWidgets.QGraphicsItem.__init__(self) self.setFlags(QtWidgets.QGraphicsItem.ItemIsSelectable | QtWidgets.QGraphicsItem.ItemIsMovable) self.prepareGeometryChange() self.width = 100 self.height = 25 self.pingleiColor = QtGui.QColor(100, 100, 100) self.pingleiText = "abc" def boundingRect(self): return QtCore.QRectF(0, 0, self.width, self.height) def paint(self, painter, option, widget): pen = QtGui.QPen() pen.setWidthF(1) pen.setColor(self.pingleiColor) brushColor = self.pingleiColor if option.state & QtWidgets.QStyle.State_Selected: brushColor = self.pingleiColor.darker(150) painter.setPen(pen) painter.setBrush(QtGui.QBrush(brushColor)) painter.drawRect(0, 0, 100, 25) pen.setColor(QtGui.QColor(255, 255, 255)) painter.setPen(pen) painter.drawText(10, 10, self.pingleiText) class DanPingItem(QtWidgets.QGraphicsItem): def __init__(self): QtWidgets.QGraphicsItem.__init__(self) self.setFlags(QtWidgets.QGraphicsItem.ItemIsSelectable) self.setAcceptHoverEvents(True) self.danPingColor = QtGui.QColor(100, 100, 100) self.danPingText = "abc" def boundingRect(self): return QtCore.QRectF(0, 0, 100, 40) def paint(self, painter, option, widget): pen = QtGui.QPen() pen.setWidthF(1) pen.setColor(self.danPingColor) brushColor = self.danPingColor if option.state & QtWidgets.QStyle.State_Selected: brushColor = self.danPingColor.darker(150) if option.state & QtWidgets.QStyle.State_MouseOver: brushColor = self.danPingColor.darker(110) painter.setPen(pen) painter.setBrush(QtGui.QBrush(brushColor)) painter.drawRect(0, 0, 100, 40) pen.setColor(QtGui.QColor(255, 255, 255)) painter.setPen(pen) painter.drawText(35, 10, self.danPingText) painter.drawPixmap() class Window(QtWidgets.QGraphicsView): def __init__(self): QtWidgets.QGraphicsView.__init__(self) self.resize(1000, 800) myScene = QtWidgets.QGraphicsScene() self.setScene(myScene) item1 = PingLeiItem() item2 = DanPingItem() # myScene.addItem(item1) myScene.addItem(item2) if __name__ == "__main__": app = QtWidgets.QApplication(sys.argv) window = Window() window.show() sys.exit(app.exec_())
自己实现的qgraphicsitem
最新推荐文章于 2024-09-24 11:00:14 发布