QWidget painter



我有此代码:

import sys, random, pprint
from PyQt5 import QtWidgets, QtGui, QtCore
from PyQt5 import QtGui
from PyQt5.QtCore import Qt
class Window(QtWidgets.QMainWindow):
    def __init__(self):
        super().__init__()
        self.initUI()
    def initUI(self):
        self.setGeometry(QtCore.QRect(200, 200, 700, 700))
        self.widget = QtWidgets.QWidget(self)
        self.widget.setGeometry(QtCore.QRect(10, 10, 400, 200))
        self.widget.setObjectName("widget")
        
    def paintEvent(self, event):
        painter = QtGui.QPainter()
        painter.begin(self.widget)
        self.drawPoints(painter)
        painter.end()
    def drawPoints(self, painter):
        #drawing code

if __name__ == '__main__':
    app = QtWidgets.QApplication(sys.argv)
    ex = Window()
    ex.show()
    sys.exit(app.exec_())

我期望什么:面积(400x200)将由drawPoints()绘制。QWidget继承QPaintDevice。因此,此代码应该起作用。但是控制台说:

qpainter ::开始:油漆设备返回引擎== 0,类型:1

qpainter ::结束:画家不活跃,流产

你能帮我吗,请。

看起来您正在尝试复制此示例,正确?

主要区别似乎是您为主窗口定义了paintEvent(),而不是实际上要绘制的小部件。如果您创建了QWidget的自定义子类(在此处定义的paintEvent()),然后将其插入标准的QMainWindow实例,则可以使用:

class MyWidget(QtWidgets.QWidget):
    def __init__(self, parent=None):
        super(MyWidget, self).__init__(parent=parent)
        self.initUI()
    def initUI(self):
        self.setGeometry(QtCore.QRect(10, 10, 400, 200))
        self.setObjectName("widget")
    def paintEvent(self, event):
        painter = QtGui.QPainter()
        painter.begin(self)
        self.drawPoints(painter)
        painter.end()
    def drawPoints(self, painter):
        pass

if __name__ == '__main__':
    app = QtWidgets.QApplication(sys.argv)
    my_window = QtWidgets.QMainWindow()
    my_window.setGeometry(QtCore.QRect(200, 200, 700, 700))
    my_window.setCentralWidget(MyWidget(my_window))
    my_window.show()
    sys.exit(app.exec_())

至少,它不再打印该错误消息了。

相关内容

  • 没有找到相关文章

最新更新