我用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就不再有效了。在
太奇怪了。感谢帮助。在
当需要重新绘制时,
paintEvent()
会被调用,如果小部件有size(0, 0)
,或者大小无效或被隐藏,则不会调用该方法,而在您的情况下,当使用布局时,默认情况下,QWidgetsizeHint()
的大小为sizeHint()
,因此不需要绘制。在因此,解决方案是设置适当的
sizeHint()
:我用
PyQt4
和PySide
尝试过,同样的问题也发生了,所以问题不是Qt而是具体的例子。在相关问题 更多 >
编程相关推荐