40

I love both python and Qt, but it's pretty obvious to me that Qt was not designed with python in mind. There are numerous ways to crash a PyQt / PySide application, many of which are extraordinarily difficult to debug, even with the proper tools.

I would like to know: what are good practices for avoiding crashes and lockups when using PyQt and PySide? These can be anything from general programming tips and support modules down to highly specific workarounds and bugs to avoid.

1

4 Answers 4

58

General Programming Practices

  • If you must use multi-threaded code, never-ever access the GUI from a non-GUI thread. Always instead send a message to the GUI thread by emitting a signal or some other thread-safe mechanism.
  • Be careful with Model/View anything. TableView, TreeView, etc. They are difficult to program correctly, and any mistakes lead to untraceable crashing. Use Model Test to help ensure your model is internally consistent.
  • Understand the way Qt object management interacts with Python object management and the cases where this can go wrong. See http://python-camelot.s3.amazonaws.com/gpl/release/pyqt/doc/advanced/development.html
    • Qt objects with no parent are "owned" by Python; only Python may delete them.
    • Qt objects with a parent are "owned" by Qt and will be deleted by Qt if their parent is deleted.
    • Example: Core dump with PyQt4
  • A QObject should generally not have a reference to its parent or any of its ancestors (weak references are ok). This will cause memory leaks at best and occasional crashes as well.
  • Be aware of situations where Qt auto-deletes objects. If the python wrapper has not been informed that the C++ object was deleted, then accessing it will cause a crash. This can happen in many different ways due to the difficulty PyQt and PySide have in tracking Qt objects.

    • Compound widgets such as a QScrollArea and its scroll bars, QSpinBox and its QLineEdit, etc. (Pyside does not have this problem)
    • Deleting a QObject will automatically delete all of its children (however PyQt usually handles this correctly).
    • Removing items from QTreeWidget will cause any associated widgets (set with QTreeWidget.setItemWidget) to be deleted.

      # Example:
      from PyQt4 import QtGui, QtCore
      app = QtGui.QApplication([])
      
      # Create a QScrollArea, get a reference to one of its scroll bars.
      w = QtGui.QWidget()
      sa = QtGui.QScrollArea(w)
      sb = sa.horizontalScrollBar()
      
      # Later on, we delete the top-level widget because it was removed from the 
      # GUI and is no longer needed
      del w
      
      # At this point, Qt has automatically deleted all three widgets.
      # PyQt knows that the QScrollArea is gone and will raise an exception if
      # you try to access it:
      sa.parent()
      Traceback (most recent call last):
        File "<stdin>", line 1, in <module>
      RuntimeError: underlying C/C++ object has been deleted
      
      # However, PyQt does not know that the scroll bar has also been deleted.
      # Since any attempt to access the deleted object will probably cause a 
      # crash, this object is 'toxic'; remove all references to it to avoid 
      # any accidents
      sb.parent()
      # Segmentation fault (core dumped)
      

Specific Workarounds / Bugs

  • Changing the bounds of QGraphicsItems without calling prepareGeometryChange() first can cause crash.
  • Raising exceptions inside QGraphicsItem.paint() can cause crashes. Always catch exceptions inside paint() and display a message rather than letting the exception proceed uncaught.
  • QGraphicsItems should never keep a reference to the QGraphicsView they live in. (weakrefs are ok).
  • Using QTimer.singleShot repeatedly can cause lockups.
  • Avoid using QGraphicsView with QGLWidget.

Practices for Avoiding Exit Crashes

  • QGraphicsItems that are not part of a QGraphicsScene can cause crash on exit.
  • QObjects that reference their parent or any ancestor can cause an exit crash.
  • QGraphicsScene with no parent can cause an exit crash.
  • The easiest way to avoid exit crashes is to call os._exit() before python starts collecting Qt objects. However, this can be dangerous because some part of the program may be relying on proper exit handling to function correctly (for example, terminating log files or properly closing device handles). At a minimum, one should manually invoke the atexit callbacks before calling os._exit().
4
  • 1
    The several claims you make about QObject hierarchies are highly questionable. They sound more like buggy programs than issues with PyQt or PySide themselves - but it's hard to be certain without seeing real examples. The only specific example you give is totally artificial - why create a QScrollArea and then immediately throw it away? Have you raised any of these issues with the maintainers of PyQt and/or PySide? It seems pointless documenting them here if you haven't.
    – ekhumoro
    Commented Aug 14, 2012 at 16:51
  • 3
    You are correct that many of these issues are the result of buggy programming rather than pyqt/pyside bugs (I did not intend to imply otherwise). However, every issue I put in this list comes from at least one real bug I encountered in my own applications. Many of them took hours of debugging to resolve, hence the need for a comprehensive list like this. The example I gave is artificial, yes, but only because I simplified it; it should not be difficult to imagine real situations where this could lead to a crash.
    – Luke
    Commented Aug 14, 2012 at 17:37
  • I added some extra example to your part about the C++ object being deleted... however, I still feel that overall its a poor example to do it with the ScrollWidget, since that would never happen. I think it should be completely re-edited to simply show the difference between python and c++ ownership ob objects.
    – jdi
    Commented Aug 15, 2012 at 21:11
  • 2
    The example was not intended to be about object ownership--there are plenty of legitimate reasons to delete Qt objects. The point is that PyQt and PySide are not perfect at keeping track of their Qt objects. If something goes wrong, it will cause a crash. The bigger point is that if we understand what causes these crashes, we can avoid them altogether with more careful programming practices.
    – Luke
    Commented Aug 15, 2012 at 22:49
4

Just adding to the point:

If you must use threads in your qt-based program, you really must disable the automatic garbage collector and do manual collections on the main thread (as described in http://pydev.blogspot.com.br/2014/03/should-python-garbage-collector-be.html) -- note that you should do that even if you make sure your objects don't have cycles (with a cycle you basically make your objects live until the python cyclic garbage collector bumps in, but sometimes if you have something as an exception it's possible that a frame is kept alive, so, in such a situation your object may still be kept alive longer than you anticipate)... in those cases, it's possible that the garbage collector bumps in in a secondary thread, which may cause qt to segfault (qt widgets must always be collected in the main thread).

2
  • Ah, I had never even considered the GC!
    – Luke
    Commented Mar 16, 2014 at 0:45
  • 1
    The only thing to note here is that if you create cycles in python with qt widgets it's still possible that gc.collect() does crash (because the deletion order can get 'wrong' -- which can possibly segfault -- this can be considered as a bug in PySide, which unfortunately isn't uncommon). Commented Mar 17, 2014 at 10:51
4

Just for the reference, I post the comment from the author of PyQt to the answer by Luke: "It's rubbish."

I think it's important because somebody can jump into this post and remained perplexed with all these (nonexistent) "problems".

3
  • As general advice, a lot of it is very misleading. It does highlight some important issues, but many of the suggested "solutions" are actually worse than the alleged problems they attempt to solve.
    – ekhumoro
    Commented Mar 20, 2015 at 18:50
  • 1
    It's editable; you're welcome to fix it. These are my own observations from years of fixing PyQt-related segmentation faults. I'm sure many of the items listed there have either been fixed or had more complex causes that I never fully discerned.
    – Luke
    Commented Mar 21, 2015 at 1:23
  • Link is broken.
    – deponovo
    Commented Oct 27, 2021 at 12:01
0

Emitting signals instead of synchronic UI control was the key to avoid problems for me during implementation of logic circuit simulator

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.