Why I get “QTimer can only be used with threads started with QThread” messages if I have no QTimer in my code?

僤鯓⒐⒋嵵緔 提交于 2019-12-04 03:07:33
Vicent

I've had similar problems in the past.

The QFileSystemModeldocumentation page says the following:

QFileSystemModel.__init__ (self, QObject parent = None)

The parent argument, if not None, causes self to be owned by Qt instead of PyQt.

Constructs a file system model with the given parent.

If you don't pass a parent argument then the Python garbage collector can delete the object at the wrong time and as a side effect raise the error you mention. My advise is to make sure that your objects have a proper parent. I think it should fix the problem.

PS: I haven't checked the docs for every class you use. Maybe QFileSystemModel is not the only class on which this thing happens.

In my experience this happens when I subclass a Qt class and one of the members of the subclass is not part of the Qt hierarchy. For example:

class MainWindow(QMainWindow):
    def __init__(self, *args, **kwargs):
        super(MainWindow, self).__init__(*args, **kwargs)
        ...
        self.my_widget = MyWidget()
        ...

If I implement MyWidget in this way, it will give me the QTimer error when the object is destroyed:

class MyWidget(object):
    def __init__(self):
        # do stuff

However, if MyWidget inherits from QObject then no error occurs:

class MyWidget(QObject):
    def __init__(self, parent):
        super(MyWidget, self).__init__(parent)
        #do stuff
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!