2017-02-20 60 views
-1

我有這樣的代碼:QWidget的畫家

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

什麼我想到:這將由drawPoints()畫區(400x200)。 QWidget繼承QPaintDevice。所以這段代碼應該工作。但是,控制檯說:

了QPainter ::開始:噴漆設備返回的發動機== 0,類型:1點

了QPainter ::結束:畫家不活躍,中止

能不能幫我, 請。

+0

初始化畫筆使用空油漆設備造成的問題。換句話說,畫家沒有什麼可以借鑑的。什麼是'self.widget'? – vahancho

+0

@vahanco self.widget = QtWidgets.QWidget(self) – cheremushkin

回答

0

它看起來像你試圖複製this example,對嗎?

主要區別似乎在於您爲主窗口定義了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_()) 

最起碼,它沒有打印該錯誤信息了。