PyQt Runtime Error of QTreeWidgetItem - python

I'm trying to avoid the well-known PyQt Runtime Error when the underlying C/C++ object is deleted:
http://www.riverbankcomputing.com/pipermail/pyqt/2009-April/022809.html
PyQt4 - "RuntimeError: underlying C/C object has been deleted"
PyQt4 nested classes - "RuntimeError: underlying C/C++ object has been deleted"
PyQt: RuntimeError: wrapped C/C++ object has been deleted
Every one of my subclasses calls the super() method and therefore the base classes are properly constructed.
Still, I get this error and am wondering if it is due to the fact that I'm adding a QComboBox widget to a QTreeWidgetItem (using the setItemWidget() method of a QTreeWidget) but I cannot set the parent as the QTreeWidgetItem that contains it. When I try, I get the following error:
TypeError: QComboBox(QWidget parent=None): argument 1 has unexpected type 'QTreeWidgetItem'
Of course, I can either omit the parent in the constructor or pass the QTreeWidget as the parent, but I think I need to reference the correct parent.
I have subclassed the QComboBox and in my subclass it runs some basic operations on the QTreeWidget, but as soon as I enter the methods of my subclassed QComboBox, the underlying C object for the parent QTreeWidgetItem containing the QComboBox is deleted (which is why I'm thinking its something to do with setting the parent of the QComboBox).
I understand 9 times out of 10 the runtime error is due to not constructing the base class. But with that ruled out, how else can the error occur? Could it be due to not referencing the correct parent?
EDIT
I'm using the QComboBox to signal when a new combobox selection was made. Upon a new selection, it adds that selected value to a PyXB XML node. Interestingly, this issue only occurs if I append the value to the PyXB class binding storing the information permanently in an XML file. In otherwords, if that part of the code doesn't run I dont get the error - its only when the code runs the PyXB operation for appending a value to an XML node binding...

I usually avoid that kind of errors keeping a reference on my class to all the objects susceptible of being deleted like your QComboBox so try something like self.comboBoxHolder = QComboBox(...) when you create it.

Related

pyqt5: QPushButton class ,clicked method and the connect [duplicate]

This question already has an answer here:
Declaration of the custom Signals
(1 answer)
Closed 1 year ago.
i am trying to learn pyqt5 take look at the following code
qbtn = QPushButton('Quit', self)
qbtn.clicked.connect(QApplication.instance().quit)
clicked signature in qtwidgets.py
def clicked(self, checked: bool = ...) -> None: ...
where is the implementation of the clicked method ?
how it is not callable i mean it's method right ?
print (qbtn.clicked())
output:
TypeError: native Qt signal is not callable
and finally if it doesn't have any implementation how it effects the QPushButton
?
print(qbtn)
print (qbtn.clicked)
print (qbtn.clicked.connect)
output:
<PyQt5.QtWidgets.QPushButton object at 0x7f963ca88160>
<bound PYQT_SIGNAL clicked of QPushButton object at 0x7f963ca88160>
<built-in method connect of PyQt5.QtCore.pyqtBoundSignal object at 0x7f963ca91cc0>
There are two important aspects that should always be kept in mind:
PyQt (similarly to PySide) is a binding: it is an interface to the Qt framework, and as such provides access to it using standard python functions and methods; in order to create it, a special tool is used, SIP, which actually creates the binding from objects exposed to python to those of Qt and viceversa (for PySide, the tool used is called Shiboken);
signals are not methods, they are interfaces to which callable objects can connect to, and those objects will be called whenever the signal is emitted, provided they have a compatible signature;
The file you're referring to is a pyi file. From What does ā€œiā€ represent in Python .pyi extension?:
The *.pyi files are used by PyCharm and other development tools to provide more information, such as PEP 484 type hints, than it is able to glean from introspection of extension types and methods. They are not intended to be imported, executed or used for any other purpose other than providing info to the tools. If you don't use use a tool that makes use of .pyi files then you can safely ignore this file.
You mentioned the following line:
def clicked(self, checked: bool = ...) -> None: ...
which is only found in those files, and is just that: an information.
Signals in C++ are declared in headers similarly to functions, having arguments that indicate the signal signature(s), and are then "transformed" into signals when Qt (or the program that declares its own signals) is compiled.[1]
Since PyQt and PySide are created using the aforementioned automated tools, the result is that signals might be listed as methods; notably, the official PySide docs list signals even including def: in PySide2 a specific "Signal" section is used, while in PySide6 they are not even identified as such.
In the python bindings, signals are unbound attributes for classes, but when a signal is referenced as a QObject instance, PyQt automatically binds the instance to the signal to create a bound signal.
>>> hasattr(QtWidgets.QPushButton.clicked, 'emit')
False
>>> hasattr(QtWidgets.QPushButton().clicked, 'emit')
True
You can see that the signal is dynamically bound by using a simple id (which should return an unique and constant value for an object):
>>> b = QtWidgets.QPushButton()
>>> id(b.clicked)
2971296616
>>> id(b.clicked)
2971299208
# or even:
>>> b.clicked == b.clicked
False
So, what you see from some documentation or reference file, is primarily the signature used to create the signal, but also the expected signature for the signal emission/receiver, similarly to what can be done in Python when declaring a new signal (with the difference that it's not possible to define default values, like the checked=False of QAbstractButton).
[1] this is a major oversimplification, I don't have enough knowledge of C++ to explain how exactly signal creation works, but it's just for the sake of explanation.

PyQt5 dbus: Force type signature of signal argument to be array of string

I'm writing an MPRIS player, which communicates with clients over
dbus. I need to emit a signal when my playback state changes. However,
the signal requires a format of (sa{sv}as), and my code is producing
(sa{sv}av). Here's the important part:
self.signal = QDBusMessage.createSignal(
"/org/mpris/MediaPlayer2",
"org.freedesktop.DBus.Properties",
"PropertiesChanged"
)
self.signal.setArguments(
[interface, {property: values}, ['']]
)
The problem is the third item in the list given to setArguments. It is
an empty string in a list because I need to produce a type of 'array
of string' (as) but pyqt5 translates that into 'array of variant' (av).
I never need to put any actual data in that list, I just need the type
signature to be correct.
Is there any way to do this in PyQt5? Perhaps using QDBusArgument?
I... I got it working. Wow. That was a campaign.
I don't know what is going wrong exactly, I wasn't able to dig out of the PyQt5 source where exactly the conversion happens. However, I did look into QDbusArgument(). There is no documentation for this in python, and the C++ docs are worthless due to major differences, so I took to the source code. in sip/QtDbus/qdbusargument.sip, I discovered a completely undocumented new method called qdbusargument_add. This maps to QDbusArgument().add() in python. It is used to add arguments with an explicit type id to a QDbusArgument. And it has a special case for QStringList!
From then I just bruteforced every possibility I could think of with arguments to QDbusArgument(), and finally got the following:
def PropertiesChanged(self, interface, property, values):
"""Sends PropertiesChanged signal through sessionBus.
Args:
interface: interface name
property: property name
values: current property value(s)
"""
emptyStringListArg = QDBusArgument()
emptyStringListArg.add([""], QMetaType.QStringList)
self.signal.setArguments([interface, {property: values}, emptyStringListArg])
QDBusConnection.sessionBus().send(self.signal)
It'd be great if the add() function could be documented, but I can't seem to send messages to the PyQt5 mailing list. Do I have to register first?

GUI design - display messages without popups

What techniques do you use to display messages in a GUI without popup dialogs?
Popup dialogs are generally quite horrible for a user - they get in the way and often you are not interested that you just caused an error. An alternative is just to ignore errors and do nothing
However, there may be the occasional user who wants to know when they caused an error...
So you want to display informative messages but without requiring that the user has to click away annoying popup boxes.
One option could be to use a statusbar of the mainwindow, but in order for any widget to use it, you need to pass around references to this damn statusbar (I'm thinking of python/qt here)...it quickly gets confusing and removes 'resuability' of your widgets (imagine you create another app, without a statusbar and you want to reuse a widget in it...)...
Any ideas?
One option could be to use a statusbar of the mainwindow, but in order for any widget to use it, you need to pass around references to this damn statusbar
Designed correctly, this is not the case. Many of my classes have a Log signal like this:-
void Log(const QString& message, enum LogPriority priority);
The priority is an enum, used to define the level of information, whether it's a debug message, warning, error, critical error etc.
In addition, I have a Logging class with a matching Log slot. You could make this a singleton, or simply have a static method.
Classes connect their signals either directly to the logging class, or to a parent's signal. This ensures that the class doesn't care what happens when it sends a log message. You can also disable a class from logging by removing its connect.
As for the logging itself, the Log class can choose to either set the text on the message bar, write to a file, display a notification (OSX) or any other method you want.
While my method uses C++, I expect you can do the same or similar in Python.
What I've done in my QT/C++ application, is a QDockedWidget in the main window called "Message Board", containing a list of warning/error/info messages. It could be anyway removed by the user. To do not pass a reference to all the widgets of this QDockedWidget, I use (for many other purpose too...) a SharedData class, with global visibility, built as singleton for the application. So every widget as a global reference to it and can set an error or warning or something else:
Gshared->setError("oops!", ErrorType::Critical);
In setError function here I emit a signal, that is catched by a slot in the QDockedWidget (for displaying the error), by a logger manager (that writes in a log file more details about the error), etc...
An another option would be the "do not show again" checkbox in a custom messageBox.
First of all, the message and the display widget for it are two separate things. It's a serious design error to mangle them together.
A typical solution would have some sort of a logger/message sink that is a semantically a singleton, but not necessarily implemented using the singleton pattern. The sink could be a QObject so that you can easily connect message sources to the sink. The sink can then be attached to one or more display widgets.
Passing the sink around is very easy thanks to QObject and the fact that qApp is a global instance pointer, and QCoreApplication is a QObject. Thus you can:
pass the pointer via the dynamic property system, or
make the sink a sole child of the global application object.
See example below. Note that the Widget only needs to know the declaration of the MessageSink class. It doesn't need to be passed any instances explicitly. Neither is the usual singleton pattern used as-is.
class MessageSink : public QObject {
Q_OBJECT
public:
MessageSink(QObject * parent = 0) : QObject(parent) {}
Q_SIGNAL void message(const QString &);
static MessageSink * instance() { return qApp->findChild<MessageSink*>(); }
}
class Widget : public QWidget {
QVBoxLayout m_layout;
QLabel m_l1, m_l2;
public:
Widget(QWidget * parent = 0) : QWidget(parent), m_layout(this) {
m_layout.addWidget(&m_l1);
m_layout.addWidget(&m_l2);
m_l1.connect(MessageSink::instance(), SIGNAL(message(QString)), SLOT(setText(QString)));
m_l2.connect(MessageSink::instance(), SIGNAL(message(QString)), SLOT(setText(QString)));
}
}
int main(int argc, char ** argv) {
QApplication app(argc, argv);
MessageSink sink(&app);
Widget w;
w.show();
emit sink.message("Hello!");
return app.exec();
}
Note: It is not a bug to have a local QObject that has a parent. You just have to make sure it gets destructed before the parent. C++ guarantees that here.

How to get all child components of QWidget in pyside/pyqt/qt?

I am developing a desktop application using pyside(qt), I want to access(iterate) all line edit components of QWidget. In qt I found two methods findChild and findChildren but there is no proper example found and My code shows error, 'form' object has no attribute 'findChild'.
Here 'form' is Qwidget form consist components lineEdit, comboboxes, Qpushbuttons etc.
Code:
lineEdits = form.findChild<QLineEdit>() //This is not working
lineEdits = form.findChild('QLineEdit) //This also not working
The signatures of findChild and findChildren are different in PySide/PyQt4 because there is no real equivalent to the C++ cast syntax in Python.
Instead, you have to pass a type (or tuple of types) as the first argument, and an optional string as the second argument (for matching the objectName).
So your example should look something like this:
lineEdits = form.findChildren(QtGui.QLineEdit)
Note that findChild and findChildren are methods of QObject - so if your form does not have them, it cannot be a QWidget (because all widgets inherit QObject).
Use this method QObject::findChildren(onst QString & name = QString()) with no parameters.
Omitting the name argument causes all object names to be matched.
Here is C++ example code:
QList<QLineEdit*> line_edits = form.findChildren<QLineEdit*>();

Need help with Classes in Python

I'm making a program that imports a custom widget that is a class (it inherits from the Tkinter Frame widget). It all works great until I get to binding. To reduce confusion we'll call the main application app, the module it's importing the widget from lib, and the widget that's being imported into app will be called cwid.
Basically I need to somehow reference a function in app, so that it may be bound to my widget in lib.
The function I'm trying to bind a widget within cwid to is element_click (The function element_click is in app.):
lambda event: element_click(event, elementinfo[3])
So the binding would look something like this in lib (element is a canvas widget within cwid)
element.bind('<ButtonRelease-1>', lambda event: element_click(event, elementinfo[3]))
The above line wont work however seeing as element_click is in app. So I tried a work around which doesn't seem to be working.
import app
loc = app.EOG
element.bind('<ButtonRelease-1>', lambda event: loc.element_click( event, elementinfo[3]))
When I try the above I get the following error:
TypeError: unbound method element_click() must be called with EOG instance as first argument (got Event instance instead)
EOG is a class in app which contains element_click.
Also, all of the above bits of code are snippets.
EDIT:
Tried loc = app.EOG(), and go the following error:
AttributeError: EOG instance has no attribute '__nonzero__'
I think you just want:
loc = app.EOG()
Then, loc is an instance of EOG, and loc.element_click is a bound method, so it works as intended.

Categories