重写PyQt5和PySide2中的paintEvent

2024-10-01 19:24:21 发布

您现在位置:Python中文网/ 问答频道 /正文

我用PyQt和PySide有一段时间了。今天我偶然发现了一个奇怪的行为:在Qt5的Python版本中,重新实现paintEvent似乎不起作用。我在Qt4从来没有遇到过这个问题。在

from PySide2 import QtWidgets, QtCore, QtGui # use pyside
# from PyQt5 import QtWidgets, QtCore, QtGui # use pyqt
import sys


class TagWidget(QtWidgets.QWidget):

    def __init__(self, parent):
        super().__init__(parent)
        print("__init__")


    def paintEvent(self, e): 
        # this is called or not
        # depends (see below)
        print("paintEvent")
        raise(AssertionError)


class MyGui(QtWidgets.QMainWindow):


    def __init__(self,parent=None):
        super(MyGui, self).__init__()
        self.setupUi()

    def setupUi(self):
        self.setGeometry(QtCore.QRect(100,100,500,500))

        self.w=QtWidgets.QWidget(self)    
        self.setCentralWidget(self.w)

        self.lay = QtWidgets.QHBoxLayout(self.w)
        self.image = TagWidget(self.w)
        self.lay.addWidget(self.image)

        # return 
        # exit here, and TagWidget.paintEvent 
        # is still being called

        self.file_list = QtWidgets.QListWidget(self.w)

        # return 
        # exit here, and TagWidget.paintEvent 
        # is still being called

        self.lay.addWidget(self.file_list)

        # .. but if we reach all the way here, 
        # TagWidget.paintEvent is never called !


def main():
    app=QtWidgets.QApplication(["test_app"])
    mg=MyGui()
    mg.show()
    app.exec_()


if (__name__=="__main__"):
    main()

所以,我们只是测试paintEvent是否被调用(调用时引发AssertionError)。在

一旦我们将另一个小部件添加到TagWidget所在的同一布局中,paintEvent就不再有效了。在

太奇怪了。感谢帮助。在


Tags: importselfhereinitismaindefparent
1条回答
网友
1楼 · 发布于 2024-10-01 19:24:21

当需要重新绘制时,paintEvent()会被调用,如果小部件有size(0, 0),或者大小无效或被隐藏,则不会调用该方法,而在您的情况下,当使用布局时,默认情况下,QWidget sizeHint()的大小为sizeHint(),因此不需要绘制。在

因此,解决方案是设置适当的sizeHint()

class TagWidget(QtWidgets.QWidget):
    def paintEvent(self, e): 
        print("paintEvent")
        raise(AssertionError)

    def sizeHint(self):
        print("default sizeHint: ", super(TagWidget, self).sizeHint())
        return QtCore.QSize(640, 480)

我用PyQt4PySide尝试过,同样的问题也发生了,所以问题不是Qt而是具体的例子。在

相关问题 更多 >

    热门问题