错误案例(QPaintDevice: Cannot destroy paint device that is being painted)

今天,帮一网友改程序,非常郁闷,一个小bug找了很就,于是把程序写下,作下记录:

程序的功能大致是,点击四个按钮,分别显示四个图片在窗口!

先上程序:

__author__ = 'Administrator'
try:
    from PySide import QtCore
    from PySide import QtGui
except ImportError:
    from PyQt4 import QtCore
    from PyQt4 import QtGui
class Mainwindow(QtGui.QWidget):
    def __init__(self):
        super(Mainwindow,self).__init__()

        self.img1=QtGui.QImage("D:\myicon.jpg")
        self.img2=QtGui.QImage("D:\one.jpg")
        self.img3=QtGui.QImage("D:\m2yicon.jpg")
        self.img4=QtGui.QImage("D:\myi3con.jpg")

        button1 = QtGui.QPushButton("1")
        button2 = QtGui.QPushButton("2")
        button3 = QtGui.QPushButton("3")
        button4 = QtGui.QPushButton("4")

        button1.clicked.connect(self.slotbutton1)
        button2.clicked.connect(self.slotbutton2)
        button3.clicked.connect(self.slotbutton3)
        button4.clicked.connect(self.slotbutton4)

        buttonlayout = QtGui.QHBoxLayout()
        buttonlayout.addWidget(button1)
        buttonlayout.addWidget(button2)
        buttonlayout.addWidget(button3)
        buttonlayout.addWidget(button4)


        mainlayout = QtGui.QVBoxLayout()
        mainlayout.addLayout(buttonlayout)
        self.setLayout(mainlayout)
        self.showimg = self.img1
        self.resize(self.showimg.width(),self.height())
    def paintEvent(self, e):

       painter = QtGui.QPainter(self)
       painter.drawImage(0,0,self.showimg)
       self.resize(self.showimg.width(),self.height())
    def slotbutton1(self):
        self.showimg = self.img1
        self.repaint()
    def slotbutton2(self):
        self.showimg = self.img2
        self.repaint()
    def slotbutton3(self):
        self.showimg = self.img3
        self.repaint()
    def slotbutton4(self):
        self.showimg = self.img4
        self.repaint()



if __name__ == '__main__':
    import sys
    app = QtGui.QApplication(sys.argv)
    mainwindow = Mainwindow()
    mainwindow.show()
    sys.exit(app.exec_())
我遇到的错误是什么呢?

下面这个代码片段是我改过的

       painter = QtGui.QPainter(self)
       painter.drawImage(0,0,self.showimg)
      
我没改之前是什么呢:

       self.painter = QtGui.QPainter(self)
       self.painter.drawImage(0,0,self.showimg)
     
错误信息是:QPaintDevice: Cannot destroy paint device that is being painted

我对self.a和a的理解是,带了self的话,会是a的作用域变为整个对象域,不加的话,就是整个函数域

所以,我们得记住重载paintEvent()函数的时候,里面的Qpainter()对象一定不能带self,不然就会出现析构错误.

你可能感兴趣的:(PySide)