[Tutor] PyQt segfault

David Boddie david at boddie.org.uk
Sat Dec 1 01:04:04 CET 2007

On Fri Nov 30 18:56:04 CET 2007, Eric Brunson wrote:

> This comboboxsegfault.py doesn't seem to do anything on my box, but I
> did get an "MemoryError" and a stack trace when I ran cbox.py and
> changed the dropdown menu selection.
> I changed the line:
>         Globals.changedtext = qstring
> to:
>         Globals.changedtext = qstring[:]
> to get a copy of qstring instead of a reference to it, and cbox.py seems
> to execute without problems now.  My guess is that the qstring is being
> disposed of when the dialog is torn down.

Something like that, yes. The internal character data becomes invalid, but
there's still a reference to the QString object.

Here's the original code posted by Tiago:

> class Combobox(QtGui.QDialog):
>     def __init__(self):
>         QtGui.QDialog.__init__(self)
>         self.ui = Ui_Dialog()
>         self.ui.setupUi(self)
>         self.connect(self.ui.comboBox, QtCore.SIGNAL("activated(QString)"),
>                      self.save)
>         def save(self, qstring):
>             # Here it works:
>             #Aux.mystring = unicode(qstring)
>             Aux.mystring = qstring

The correct way to handle this is commented out: to take a copy of the data,
as you pointed out. This could be done by converting it to a Python unicode
object, as shown, or by copying the QString:

  Aux.mystring = QString(string)

[Off topic, but PyQt-related: You need to explicitly copy value types with
PyQt because the semantics of copying objects with Python are different to
those for copying Qt's value classes in C++. In Python, you just bind an
object to a name, but the equivalent assignment in C++ is basically just
creating an additional reference to the same object.]


More information about the Tutor mailing list