from PyQt5.QtWidgets import QGraphicsItem
from PyQt5.QtSvg import QGraphicsSvgItem, QSvgRenderer
from PyQt5.QtCore import Qt, QRectF
class MyItem(QGraphicsItem):
def __init__(self, parent ):
super().__init__( parent = parent )
self.textRect = QRectF( 0,0,100,100 )
self.SvgGItem = QGraphicsSvgItem(self)
self.Svg_renderer = QSvgRenderer("./item.svg")
self.SvgGItem.setSharedRenderer ( self.Svg_renderer )
self.SvgGItem.setElementId( "1" )
def paint(self, painter, option, widget):
alignFlags = Qt.AlignLeft | Qt.AlignTop
painter.drawText( self.textRect, alignFlags , "text" )
我希望文本在svg项目上方。举例来说,这段代码很难实现,但是意义是一样的。 setZValue()在这种情况下不起作用,很明显。有其他办法吗?
答案 0 :(得分:0)
尝试一下:
import sys
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from PyQt5.QtSvg import QGraphicsSvgItem, QSvgRenderer
class MyItem(QGraphicsItem):
def __init__(self):
super().__init__()
self.x = 0
self.y = 0
self.w = 100
self.h = 100
self.width = 8
self.text = "None"
self.setFlags(MyItem.ItemIsSelectable | MyItem.ItemIsMovable)
def boundingRect(self):
return QRectF(self.x, self.y, self.w, self.h)
def paint(self, painter, option, widget):
painter.setPen(QPen(Qt.blue, self.width))
rec = self.boundingRect().adjusted(self.width / 2,
self.width / 2,
-self.width / 2,
-self.width / 2)
painter.setBrush(Qt.yellow)
painter.drawRect(rec)
painter.setFont(QFont("Arial", 16))
self.textRect = QRectF( 0, 0, 100, 100 )
alignFlags = Qt.AlignCenter
painter.drawText( self.textRect, alignFlags , "! text !" )
class MySvg(QGraphicsSvgItem):
def __init__(self):
super(MySvg, self).__init__('blank.svg')
self.setFlags(QGraphicsItem.ItemIsSelectable|
QGraphicsItem.ItemIsMovable)
class GraphicsScene(QGraphicsScene):
def __init__(self):
super().__init__()
self.setSceneRect(-200, -200, 400, 400)
self.fillScene()
def fillScene(self):
test = MySvg()
self.addItem(test)
item = MyItem()
self.addItem(item)
def drawBackground(self, painter, rect):
painter.setPen(QPen(Qt.green, 3))
painter.drawRect(self.sceneRect())
painter.setPen(QPen(Qt.red, 3))
painter.drawText(0, 0, '0')
painter.drawText(-200, -200, '-200')
painter.drawText(200, 200, '200')
class Main(QWidget):
def __init__(self):
super(Main, self).__init__()
self.scene = GraphicsScene()
self.view = QGraphicsView(self)
self.view.setScene(self.scene)
hbox = QHBoxLayout()
hbox.addWidget(self.view)
self.setLayout(hbox)
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = Main()
ex.show()
sys.exit(app.exec_())