【问题标题】:QPainter methods return "Painter not active" error [duplicate]QPainter 方法返回“Painter not active”错误[重复]
【发布时间】:2019-05-07 04:31:45
【问题描述】:

我是 Qt5/PyQt5 的新手,想创建一个矩形对象,将其附加到列表中并在窗口中绘制,但由于 Painter not active 错误而失败。

这是什么原因?

错误:

QPainter::setBrush: Painter 未激活

QPainter::drawRects: Painter 未激活

代码:

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_())

【问题讨论】:

  • 我已经尝试过了,但它会产生另一个错误。回溯(最后一次调用):文件“/home/ata/source/Tests/rect.py”,第 16 行,在paintpainter = QPainter(self)类型错误:参数不匹配任何重载调用:QPainter():太许多参数 QPainter(QPaintDevice):参数 1 具有意外的类型“矩形”
  • 删除painter = QPainter()

标签: python python-3.x pyqt pyqt5 qpainter


【解决方案1】:

在您的绘画方法中,您已经有一个画家对象,我不确定您是否正在使用 painter = QPainter() 而不是使用该画家(如果是对一个对象的有效引用),无论如何,你正在创建一个新的画家对象,所以在你绘制任何东西之前,下面的代码实际上是 c++ 代码,但由于 qt 是一个独立于语言的框架,所以要走的路是一样的......

painter.begin(this);
painter.doSomePicasso(); //paint what you need
painter.end();

在python中应该是这样的

qp.begin(self)
self.drawText(event, qp)
qp.end()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-09-26
    • 1970-01-01
    • 2021-11-03
    • 1970-01-01
    • 2021-01-04
    • 2014-06-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多