我是Qt5 / PyQt5的新手,想创建一个矩形对象,将其附加到列表中并在窗口中绘制,但是由于Painter无效错误而失败。
这是什么原因?
错误:
QPainter :: setBrush:画家不活跃
QPainter :: drawRects:画家不活跃
代码:
from PyQt5.QtCore import QRectF
from PyQt5 import QtCore
from PyQt5.QtWidgets import QApplication, QGraphicsView, QGraphicsScene, QGraphicsRectItem
from PyQt5.QtGui import QPainter, QBrush
rectangles = []
class Rectangle(QGraphicsRectItem):
def __init__(self):
super(Rectangle, self).__init__()
self.brush = QBrush(QtCore.Qt.blue)
def paint(self, painter, option, widget):
painter = QPainter()
painter.setBrush(self.brush)
self.setRect(10, 10, 300, 300)
painter.drawRect(10, 10, 200, 200)
def boundingRect(self):
return QRectF(0,0,800,800)
class GraphicsWindow(QGraphicsView):
def __init__(self, parent=None):
super(GraphicsWindow, self).__init__(parent)
scene = QGraphicsScene(self)
rectangle = Rectangle()
rectangles.append(rectangle)
scene.addItem(rectangle)
scene.setSceneRect(0, 0, 800, 800)
self.setScene(scene)
self.setCacheMode(QGraphicsView.CacheBackground)
if __name__ == '__main__':
import sys
app = QApplication(sys.argv)
graphics_window = GraphicsWindow()
graphics_window.show()
sys.exit(app.exec_())
答案 0 :(得分:0)
在您的绘画方法中,您已经有一个绘画对象,我不确定您是在做 painter = QPainter() 而不是使用该绘画器(如果有效引用对象),无论如何,您正在创建一个新的painter对象,因此在绘制任何内容之前,以下代码实际上是c ++代码,但是由于qt是独立于语言的框架,因此处理方法是相同的... < / p>
painter.begin(this);
painter.doSomePicasso(); //paint what you need
painter.end();
应该类似于
qp.begin(self)
self.drawText(event, qp)
qp.end()