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.
Related
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.
I had written a gui using PyQt5 and recently I wanted to increase the font size of all my QLabels to a particular size. I could go through the entire code and individually and change the qfont. But that is not efficient and I thought I could just override the class and set all QLabel font sizes to the desired size.
However, I need to understand the class written in python so I can figure out how to override it. But I did not find any python documentation that shows what the code looks like for QLabel. There is just documentation for c++. Hence, I wanted to know where I can get the python code for all of PyQt5 if that exists? If not, how can I change the font size of all QLabels used in my code?
To change the font of all QLabels then there are several options:
Use Qt StyleSheet
app.setStyleSheet("QLabel{font-size: 18pt;}")
Use QApplication::setFont()
custom_font = QFont()
custom_font.setWeight(18);
QApplication.setFont(custom_font, "QLabel")
While the provided answers should have already given you enough suggestions, I'd like to add some insight.
Are there python sources for Qt?
First of all, you cannot find "the class written in python", because (luckily) there's none. PyQt is a binding: it is an interface to the actual Qt library, which is written in C++.
As you might already know, while Python is pretty fast on nowadays computers, it's not that fast, so using a binding is a very good compromise: it allows the simple syntax Python provides, and gives all speed provided by C++ compiled libraries under the hood.
You can find the source code for Qt widgets here (official mirror), or here.
How to override the default font?
Well, this depends on how you're going to manage your project.
Generally speaking, you can set the default font [size] for a specific widget, for its child widgets, for the top level window or even for the whole application. And there are at least two ways to do it.
use setFont(): it sets the default font for the target; you can get the current default font using something.font(), then use font.setPointSize() (or setPointSizeF() for float values, if the font allows it) and then call setFont(font) on the target.
use font[-*] in the target setStyleSheet();
Target?
The target might be the widget itself, one of its parents or even the QApplication.instance(). You can use both setFont() or setStyleSheet() on any of them:
font = self.font()
font.setPointSize(24)
# set the font for the widget:
self.pushButton.setFont(someFont)
# set the font for the top level window (and any of its children):
self.window().setFont(someFont)
# set the font for *any* widget created in this QApplication:
QApplication.instance().setFont(someFont)
# the same as...
self.pushButton.setStyleSheet(''' font-size: 24px; ''')
# etc...
Also, consider setting the Qt.AA_UseStyleSheetPropagationInWidgetStyles attribute for the application instance.
Setting and inheritance
By default, Qt uses font propagation (as much as palette propagation) for both setFont and setStyleSheet, but whenever a style sheet is set, it takes precedence, even if it's set on any of the parent widgets (up to the top level window OR the QApplication instance).
Whenever stylesheets are applied, there are various possibilities, based on CSS Selectors:
'font-size: 24px;': no selector, the current widget and any of its child will use the specified font size;
'QClass { font-size: 24px; }': classes and subclasses selector, any widget (including the current instance) and its children of the same class/subclass will use the specified font size:
'QClass[property="value"] {...}': property selector, as the above, but only if the property matches the value; note that values are always quoted, and bool values are always lower case;
'.QClass {...}': classes selector, but not subclasses: if you're using a subclass of QLabel and the stylesheet is set for .QLabel, that stylesheet won't be applied;
'QClass#objectName {...}': apply only for widgets for which objectName() matches;
'QParentClass QClass {...}': apply for widget of class QClass that are children of QParentClass
'QParentClass > QClass {...}': apply for widget of class QClass that are direct children of QParentClass
Note that both setFont and setStyleSheet support propagation, but setStyle only works on children when set to the QApplication instance: if you use widget.setStyle() it won't have effect on any of the widget's children.
Finally, remember:
whenever a widget gets reparented, it receives the font, palette and stylesheet of its parent, in "cascading" mode (the closest parent has precedence);
stylesheets have precedence on both palette and font, whenever any of the related properties are set, and palette/font properties are not compatible with stylesheets (or, at least, they behave in unexpected ways);
Qt Stylesheets
This is probably the easiest way to do in your situation, you are really trying to apply a specific "style" to all your QLabels. You can apply a style to your whole application, or a specific window, and this will affect all children that match the selectors.
So in your case, to apply to all widgets in your application you can do the following to set the font size of all QLabel instances:
app = QApplication([])
app.setStyleSheet('.QLabel { font-size: 14pt;}')
Note: Be sure to set the stylesheet before attaching your widgets to its parent, otherwise you would need to manually trigger a style refresh.
Also...
The .QLabel selector will only apply to QLabel class instances, and not to classes that inherit QLabel. To apply to both QLabel and inherited classes, use QLabel {...} instead of .QLabel {...} in the stylesheet.
Some documentation to help you beyond that:
Qt stylesheet documentation: https://doc.qt.io/qt-5/stylesheet.html
Qt stylesheet syntax: https://doc.qt.io/qt-5/stylesheet-syntax.html
Qt stylesheet reference: https://doc.qt.io/qt-5/stylesheet-reference.html
PyQt documentation: https://doc.qt.io/qtforpython/api.html
Completing Adrien's answer, you can use QFont class and perform .setFont() method for every button.
my_font = QFont("Times New Roman", 12)
my_button.setFont(my_font)
Using this class you can also change some font parameters, see https://doc.qt.io/qt-5/qfont.html
Yeah, documentation for C++ is okay to read because all methods & classes from C++ are implemented in Python.
UPD: QWidget class also has setFont method so you can set font size on centralwidget as well as using stylesheets.
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.
I am writing a Python GTK application for studying some sort of math data. The main script has a single class with only three methods: __INIT__, main(self) for starting the loop and delete_event for killing it.
__INIT__ creates the GUI, which includes a TextBuffer and TextView widgets so that the analysis functions (defined on a separate functions.py module) can output their results to a common log/message area. A relevant extract follows:
include module functions(.py)
(...)
class TURING:
def __init__(self):
self.window = gtk.Window(gtk.WINDOW_TOPLEVEL)
(...)
self.logscroll = gtk.ScrolledWindow()
self.logscroll.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC)
self.logbuffer = gtk.TextBuffer()
self.logpage = gtk.TextView(self.logbuffer)
self.logpage.set_editable(gtk.FALSE)
self.logpage.set_cursor_visible(gtk.FALSE)
self.logpage.set_wrap_mode(gtk.WRAP_CHAR)
self.logscroll.add(self.logpage)
self.logscroll.show()
self.logpage.show()
(...)
enditer = self.logbuffer.get_end_iter()
self.logbuffer.insert(enditer, 'Welcome!')
(...)
def main(self):
gtk.main()
if __name__ == "__main__":
turing = TURING()
turing.main()
The intermediate two lines successfully print a welcome message onto the message area defined by self.logpage.
Now, one of the functions in method functions checks whether the database is up to date and if not asks the user to load a new batch of raw data.
One way of doing this is to include a menu item that triggers that function, like this:
item_dataCheck.connect("activate", functions.data_check, '')
functions.data_check runs fine however when it tries to write its output to self.logbuffer an error is thrown complaining that menu item item_dataCheck has no property logbuffer. The offending code is
enditer = self.logbuffer.get_end_iter()
self.logbuffer.insert(enditer, 'Please update the database.')
Obviously the name self is representing the widget that invoked the function, viz., item_dataCheck. My question is how can I from functions.data_check refer directly to logbuffer as a member of the turing instance of the TURING class. I tried to write
enditer = turing.logbuffer.get_end_iter()
turing.logbuffer.insert(enditer, 'Please update the database.')
but that's is not working. I have tried hard to find a solution but with no success.
I believe the matter is quite trivial and I know I still have some serious conceptual problems with Python and OOP, but any help will be heartly appreciated. (I started out card punching Fortran programs on a Burroughs mainframe, so I could count on some community mercy...)
You can provide additional arguments when connecting signals to functions or methods. So your handler functions.data_check can accept extra arguments apart from self:
def data_check(self, logbuffer):
# ...
Then, you can connect with arguments:
item_dataCheck.connect("activate", functions.data_check, logbuffer)
Also, the self parameter is normally used as the first parameter in method definitions. This is a very strong convention so you should use obj or something similar instead. Specially since your signal handlers may be methods too; in which case you could mess it up with its arguments.
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*>();