Why can't I use QMessageBox in QApplication::notify() derived method - qt

As I understand it, the way to handle exceptions happening inside the event loop in Qt is to override QApplication::notify() and handle it there. I have tried that and it works:
class Application : public QApplication
{
Q_OBJECT
public:
explicit Application( int& argc, char** argv );
// override to handle out of memory exceptions
bool notify( QObject* receiver, QEvent* e );
signals:
public slots:
private:
char* m_buffer;
};
Application::Application(int &argc, char **argv)
:QApplication( argc, argv )
{
m_buffer = new char[1024*1024];
}
bool Application::notify(QObject *receiver, QEvent *e)
{
try
{
return QApplication::notify( receiver, e );
}
catch( std::bad_alloc& )
{
if ( m_buffer )
{
delete[] m_buffer;
m_buffer = NULL;
}
// calling QMessageBox from here doesn't work
// even if release a load of reserved memory
// don't know why
QMessageBox::critical( NULL, "Exception", "Application out of memory" );
}
But the message box is blank when it appears (i.e. not rendered correctly). I thought perhaps the process didn't have enough memory. So I tried allocating 1MB of memory at the start (see m_buffer above) and then releasing it before the QMessageBox displayed. But that didn't work either. Any ideas?

I could be interpretting QApplication::notify wrong, but I'm getting the impression that you're attempting to create a GUI object (QMessageBox) when the Qt event loop crashes. I don't believe that's possible.
For exception safety, my understanding is that you have to wrap the whole QApplication::exec function with a try-catch sequence, as in the Exception Safety docs.
Consider implementing a custom error handler using qCritical and qWarning. I like to redirect those functions to a log file in my temp directory to debug crashes. Of course, your program still crashes unlike in exception handling, but at least you know why. I can provide example code if necessary.

QMessageBox::exec(), which is used by the static convenience methods critical(), warning(), etc., opens a local event loop and only returns to the main event loop once the message box is closed. Local event loops are nasty in general, opening in the midst of event handling (QApplication::notify) is even more so. You better use QDialog::open to open the message box without blocking, or even better, defer the message box:
In your application class:
Q_INVOKABLE void showMessage( const QString& message ); // in your Application class, does the QMessageBox::critical() call
Instead of calling QMessageBox::critical() directly, replace it by something like this:
QMetaObject::invokeMethod( this, "showMessage", Qt::QueuedConnection, Q_ARG(QString, "Application out of memory") );

Related

Qt: How to avoid deadlock when multiple queued signals invoke same slot

In following code I meet deadlock in someOperation:
class A : public QObject {
Q_OBJECT
public:
explicit A(QObject* parent) : QObject(parent), data(0) {}
public slots:
void slot1() {
someOperation();
}
void slot2() {
someOperation();
}
void slot3() {
someOperation();
}
private:
void someOperation() {
QMutexLocker lk(&mutex);
data++;
QMessageBox::warning(NULL, "warning", "warning");
data--;
assert(data == 0);
}
int data;
QMutex mutex; //protect data
};
class Worker: public QThread {
Q_OBJECT
public:
explicit Worker(QObject* parent) : QThread(parent) {}
protected:
virtual void run() {
// some complicated data processing
emit signal1();
// other complicated data processing
emit signal2();
// much complicated data processing
emit signal3();
qDebug() << "end run";
}
signals:
void signal1();
void signal2();
void signal3();
};
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
A* a = new A(&app);
Worker* w = new Worker(a);
QObject::connect(w, SIGNAL(signal1()), a, SLOT(slot1()), Qt::QueuedConnection);
QObject::connect(w, SIGNAL(signal2()), a, SLOT(slot2()), Qt::QueuedConnection);
QObject::connect(w, SIGNAL(signal3()), a, SLOT(slot3()), Qt::QueuedConnection);
w->start();
return app.exec();
}
There is a thread that will emit three signals, all of them queued connected to an instance of class A, and all class A' slots will call to someOperation, and someOperation is protected by mutex and it will popup a message box.
Qt::QueuedConnection 2 The slot is invoked when control returns to the event loop of the receiver's thread. The slot is executed in the receiver's thread.
It seems slot2 is invoked when slot1's message box still doing modal, in main thread, but at that time slot1 has lock mutex, so deadlock.
How to change the code to avoid deadlock?
Update:(Jan.17, 2019)
What I want archive is that: slot2 not be execute before slot1 finished.
What should be kept are:
worker is a background thread to process data, cost long time; so, whatever, the three signals will emit from other thread.
worker should not blocked by emitting signals.
slots should execute in main thread, because they will update GUI.
someOperation is not reentrant.
The requirement that "someOperation is not reentrant" is an odd one. What should happen if reentrancy is attempted? Given that someOperation can only be called from the main thread I can only see two options...
Block completely with mutex/barrier etc. as you have tried.
Block based on a recursion level counter and spin the event loop until that counter decrements to zero.
1) Will block the thread's event loop completely preventing the current message dialog from functioning correctly.
2) Will allow all message dialogs simultaneously rather then serialising them.
Rather than trying to make someOperation non-reentrant I think you need to make sure you use in a way that won't result in reentrancy.
One option might be to make use of a separate QObject derived class instance on its own QThread. Consider the following...
class signal_serialiser: public QObject {
Q_OBJECT;
signals:
void signal1();
void signal2();
void signal3();
};
If an instance of signal_serialiser is moved to its own thread it can act as a queue to buffer and forward the various signals if suitable connection types are used. In your code you currently have...
QObject::connect(w, SIGNAL(signal1()), a, SLOT(slot1()), Qt::QueuedConnection);
QObject::connect(w, SIGNAL(signal2()), a, SLOT(slot2()), Qt::QueuedConnection);
QObject::connect(w, SIGNAL(signal3()), a, SLOT(slot3()), Qt::QueuedConnection);
Change that to...
signal_serialiser signal_serialiser;
QObject::connect(w, SIGNAL(signal1()), &signal_serialiser, SIGNAL(signal1()));
QObject::connect(w, SIGNAL(signal2()), &signal_serialiser, SIGNAL(signal2()));
QObject::connect(w, SIGNAL(signal3()), &signal_serialiser, SIGNAL(signal3()));
/*
* Note the use of Qt::BlockingQueuedConnection for the
* signal_serialiser --> A connections.
*/
QObject::connect(&signal_serialiser, SIGNAL(signal1()), a, SLOT(slot1()), Qt::BlockingQueuedConnection);
QObject::connect(&signal_serialiser, SIGNAL(signal2()), a, SLOT(slot2()), Qt::BlockingQueuedConnection);
QObject::connect(&signal_serialiser, SIGNAL(signal3()), a, SLOT(slot3()), Qt::BlockingQueuedConnection);
QThread signal_serialiser_thread;
signal_serialiser.moveToThread(&signal_serialiser_thread);
signal_serialiser_thread.start();
I've only done basic testing but it appears to give the desired behaviour.
That's because your function void someOperation() is not reentrant.
The static functions of QMessageBox span their own event loop, which calls QCoreApplication::processEvents() repeatedly:
Execution of the first invocation of someOperation() gets stuck at QMessageBox::warning(...).
In there, exec() calls processEvents(), 3. which sees the second signal
and invokes someOperation() again
where trying to re-lock mutex fails.
How to resolve this depends on what you want to achieve...
About your general approach to QThread: You're doing it wrong.
(That link gives a good start into the topic, but not a complete solution.)
You create and start a background thread. But that thread will only emit the three signals and then finish.
The slots will be called inside the main (GUI) event loop, because that's the thread affinity of your A *a.
To make the slots be executed in the background, you need to:
create your A instance without a parent: A *a = new A();
create your Worker instance with the app as parent: Worker *w = new Worker(&app); (or with nothing, at least not with a)
change the thread affinity of your A instance: a->moveToThread(Worker);
don't override Worker::run(), or if you really want to (see point 5), call the base implementation: QThread::run();
emit the signals from main (you can emit them from run(), but that's not necessary).

Using POSIX threads in Qt Widget App

I'm relatively new to both Qt and pthreads, but I'm trying to use a pthread to work in the background of basic test app I'm making. I'm aware of the Qt Frameworks own threading framework - but there's a lot of complaint surrounding it so I'd like to use pthread if possible. The code is as below
#include "drawwindow.h"
#include "ui_drawwindow.h"
#include <pthread.h>
#include <stdlib.h>
#include <stdio.h>
#include "QThread"
pthread_t th1;
DrawWindow::DrawWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::DrawWindow)
{
ui->setupUi(this);
}
DrawWindow::~DrawWindow()
{
delete ui;
}
void DrawWindow::on_pushButton_clicked()
{
pthread_create(&th1, NULL, &DrawWindow::alter_text, NULL);
}
void DrawWindow::alter_text()
{
while(1)
{
ui->pushButton->setText("1");
QThread::sleep(1);
ui->pushButton->setText("one");
QThread::sleep(1);
}
}
With the header
#ifndef DRAWWINDOW_H
#define DRAWWINDOW_H
#include <QMainWindow>
namespace Ui {
class DrawWindow;
}
class DrawWindow : public QMainWindow
{
Q_OBJECT
public:
explicit DrawWindow(QWidget *parent = 0);
~DrawWindow();
void alter_text();
private slots:
void on_pushButton_clicked();
private:
Ui::DrawWindow *ui;
};
#endif // DRAWWINDOW_H
And I'm getting the error
error: cannot convert 'void (DrawWindow::*)()' to 'void* (*)(void*)' for argument '3' to 'int pthread_create(pthread_t*, const pthread_attr_t*, void* (*)(void*), void*)'
pthread_create(&th1, NULL, &DrawWindow::alter_text, NULL);
^
Does anyone know what is wrong?
TL;DR: The way you're using pthreads is precisely the discouraged way of using QThread. Just because you use a different api doesn't mean that what you're doing is OK.
There's absolutely no problem with either QThread or std::thread. Forget about pthreads: they are not portable, their API is C and thus abhorrent from a C++ programmer's perspective, and you'll be making your life miserable for no reason by sticking to pthreads.
Your real issue is that you've not understood the concerns with QThread. There are two:
Neither QThread nor std::thread are destructible at all times. Good C++ design mandates that classes are destructible at any time.
You cannot destruct a running QThread nor std::thread. You must first ensure that it's stopped, by calling, respectively QThread::wait() or std::thread::join(). It wouldn't have been a big stretch to have their destructors do that, and also stop the event loop in case of QThread.
Way too often, people use QThread by reimplementing the run method, or they use std::thread by running a functor on it. This is, of course, precisely how you use pthreads: you run some function in a dedicated thread. The way you're using pthreads is just as bad as the discouraged way of using QThread!
There are many ways of doing multithreading in Qt, and you should understand the pros and cons of each of them.
Thus, how do you do threading in C++/Qt?
First, keep in mind that threads are expensive resources, and you should ideally have no more threads in your application than the number of available CPU cores. There are some situations when you're forced to have more threads, but we'll discuss when it's the case.
Use a QThread without subclassing it. The default implementation of run() simply spins an event loop that allows the objects to run their timers and receive events and queued slot calls. Start the thread, then move some QObject instances to it. The instances will run in that thread, and can do whatever work they need done, away from the main thread. Of course, everything that the objects do should be short, run-to-completion code that doesn't block the thread.
The downside of this method is that you're unlikely to exploit all the cores in the system, as the number of threads is fixed. For any given system, you might have exactly as many as needed, but more likely you'll have too few or too many. You also have no control over how busy the threads are. Ideally, they should all be "equally" busy.
Use QtConcurrent::run. This is similar to Apple's GCD. There is a global QThreadPool. When you run a functor, one thread from the pool will be woken up and will execute the functor. The number of threads in the pool is limited to the number of cores available on the system. Using more threads than that will decrease performance.
The functors you pass to run will do self-contained tasks that would otherwise block the GUI leading to usability problems. For example, use it to load or save an image, perform a chunk of computations, etc.
Suppose you wish to have a responsible GUI that loads a multitude of images. A Loader class could do the job without blocking the GUI.
class Loader : public QObject {
Q_OBJECT
public:
Q_SIGNAL void hasImage(const QImage &, const QString & path);
explicit Loader(const QStringList & imagePaths, QObject * parent = 0) :
QObject(parent) {
QtConcurrent::map(imagePaths, [this](const QString & path){
QImage image;
image.load(path);
emit hasImage(image, path);
});
}
};
If you wish to run a short-lived QObject in a thread from the thread pool, the functor can spin the event loop as follows:
auto foo = QSharedPointer<Object>(new Object); // Object inherits QObject
foo->moveToThread(0); // prepares the object to be moved to any thread
QtConcurrent::run([foo]{
foo->moveToThread(QThread::currentThread());
QEventLoop loop;
QObject::connect(foo, &Object::finished, &loop, &QEventLoop::quit);
loop.exec();
});
This should only be done when the object is not expected to take long to finish what it's doing. It should not use timers, for example, since as long as the object is not done, it occupies an entire thread from the pool.
Use a dedicated thread to run a functor or a method. The difference between QThread and std::thread is mostly in that std::thread lets you use functors, whereas QThread requires subclassing. The pthread API is similar to std::thread, except of course that it is C and is awfully unsafe compared to the C++ APIs.
// QThread
int main() {
class MyThread : public QThread {
void run() { qDebug() << "Hello from other thread"; }
} thread;
thread.start();
thread.wait();
return 0;
}
// std::thread
int main() {
// C++98
class Functor {
void operator()() { qDebug() << "Hello from another thread"; }
} functor;
std::thread thread98(functor);
thread98.join();
// C++11
std::thread thread11([]{ qDebug() << "Hello from another thread"; });
thread11.join();
return 0;
}
// pthread
extern "C" void* functor(void*) { qDebug() << "Hello from another thread"; }
int main()
{
pthread_t thread;
pthread_create(&thread, NULL, &functor, NULL);
void * result;
pthread_join(thread, &result);
return 0;
}
So, what is this good for? Sometimes, you have no choice but to use a blocking API. Most database drivers, for example, have blocking-only APIs. They expose no way for your code to get notified when a query has been finished. The only way to use them is to run a blocking query function/method that doesn't return until the query is done. Suppose now that you're using a database in a GUI application that you wish to remain responsive. If you're running the queries from the main thread, the GUI will block each time the database query run. Given long-running queries, a congested network, a dev server with a flaky cable that makes the TCP perform on par with sneakernet... you're facing huge usability issues.
Thus, you can't but have to run the database connection on, and execute the database queries on a dedicated thread that can get blocked as much as necessary.
Even then, it might still be helpful to use some QObject on the thread, and spin an event loop, since this will allow you to easily queue the database requests without having to write your own thread-safe queue. Qt's event loop already implements a nice, thread-safe event queue so you might as well use it. For example, with a note that Qt's SQL module can be used from one thread only - thus you can't prepare QSQLQuery in the main thread :(
Note that this example is very simplistic, you'd likely want to provide thread-safe way of iterating the query results, instead of pushing the entire query's worth of data at once.
class DBWorker : public QObject {
Q_OBJECT
QScopedPointer<QSqlDatabase> m_db;
QScopedPointer<QSqlQuery> m_qBooks, m_query2;
Q_SLOT void init() {
m_db.reset(new QSqlDatabase(QSqlDatabase::addDatabase("QSQLITE")));
m_db->setDatabaseName(":memory:");
if (!m_db->open()) { emit openFailed(); return; }
m_qBooks.reset(new QSqlQuery(*m_db));
m_qBooks->prepare("SELECT * FROM Books");
m_qCars.reset(new QSqlQuery(*m_db));
m_qCars->prepare("SELECT * FROM Cars");
}
QList<QVariantList> read(QSqlQuery * query) {
QList<QVariantList> result;
result.reserve(query->size());
while (query->next()) {
QVariantList row;
auto record = query->record();
row.reserve(record.count());
for (int i = 0; i < recourd.count(); ++i)
row << query->value(i);
result << row;
}
return result;
}
public:
typedef QList<QVariantList> Books, Cars;
DBWorker(QObject * parent = 0) : QObject(parent) {
QObject src;
connect(&src, &QObject::destroyed, this, &DBWorker::init, Qt::QueuedConnection);
m_db.moveToThread(0
}
Q_SIGNAL void openFailed();
Q_SIGNAL void gotBooks(const DBWorker::Books &);
Q_SIGNAL void gotCars(const DBWorker::Cars &);
Q_SLOT void getBooks() {
Q_ASSERT(QThread::currentThread() == thread());
m_qBooks->exec();
emit gotBooks(read(m_qBooks));
}
Q_SLOT void getCars() {
Q_ASSERT(QThread::currentThread() == thread());
m_qCars->exec();
emit gotCars(read(m_qCars));
}
};
Q_REGISTER_METATYPE(DBWorker::Books);
Q_REGISTER_METATYPE(DBWorker::Cars);
// True C++ RAII thread.
Thread : public QThread { using QThread::run; public: ~Thread() { quit(); wait(); } };
int main(int argc, char ** argv) {
QCoreApplication app(argc, argv);
Thread thread;
DBWorker worker;
worker.moveToThread(&thread);
QObject::connect(&worker, &DBWorker::gotCars, [](const DBWorker::Cars & cars){
qDebug() << "got cars:" << cars;
qApp->quit();
});
thread.start();
...
QMetaObject::invokeMethod(&worker, "getBooks"); // safely invoke `getBooks`
return app.exec();
}
Change void DrawWindow::alter_text() to void* DrawWindow::alter_text(void*) and return pthread_exit(NULL);.

Emitting signal from callback

I am using RtMidi library to handle midi message in my Qt application and I am facing problem with slot trigger:
My PhMidiInput object is emiting signal from the RtMidi callback upon specific midi message but the slots are not always triggered.
Here is a part of the PhMidiInput class:
class PhMidiInput : QObject
{
Q_OBJECT
public:
void PhMidiInput() {}
signals:
void quarterFrame(unsigned char data);
private:
static void callback(double, std::vector< unsigned char > *message, void *userData ) {
PhMidiInput *midiInput = (PhMidiInput*)userData;
if(midiInput)
midiInput->onMessage(message);
}
void onMessage(std::vector<unsigned char> *message) {
...
emit quarterFrame(data);
...
}
}
Connecting to a lambda functor works:
PhMidiInput midiIn;
int quarterFrameCount;
connect(&midiIn, &PhMidiInput::quarterFrame, [&](unsigned char data) {
quarterFrameCount++;
});
Connecting to my application window works to:
// MyWindow inherits from QMainWindow
connect(_midiIn, &PhMidiInput::quarterFrame, this, &MyWindow::onQuarterFrame);
When trying to connect to a custom class (MidiTest) inheriting from QObject it does'nt trigger:
connect(_midiIn, &PhMidiInput::quarterFrame, this, &MidiTest::onQuarterFrame);
I was wondering if there was something around QObject::moveToThread() but since I don't create the thread myself (the signal is sent from a callback) I don't know if I need to use it or not.
It is as simple as calling emit obj->quarterFrame(data); from the callback. If the connection type is default then this will be perfectly thread safe.
Though you should create a QByteArray from data to pass around as data will likely not be valid by the time the slots get called.
void callback(..., void* user){
//user is the standard void* in most callbacks passed as reinterpret_cast<void*>(this)
unsigned char* data = ...;
QByteArray bytes(data);
emit reinterpret_cast<PhMidiInput>(user)->quarterFrame(bytes);//calling the signal which will behave as you'd expect
}
In the last connect() call you pass this and MidiTest::onQuarterFrame as the receiver object and method. I bet this is not an instance of MidiTest, is it?
The problem here is that you're passing SLOT method from MidiTest, while the receiver object is this, which is not instance of MidiTest. Change receiver from this to some instance of MidiTest.
I'm surprised this code doesn't crash your application when running.

Error while inheriting QObject

I've got a class applicationManager that ought to emit signal when there is an info message or an error occurs, while I'm suppose to log that messages consuming it by QXmppLogger class object. There is a QXmppLoggable class that got methods like info() and warning() that emits a signal logmessage() of internal QXmppLogger. So, in order to emit a signal I've inherited QXmppLogable class which inherits QObject itself, hence to be able to use info() and warning() and connected emitted SIGNAL(logmessage()) by info() and warning() methods, to SLOT (log()) of QXmppLogger object. Here is the code snippet:
header "imApplicationManager.h"
class applicationManagement: public QXmppLoggable
{
//Q_OBJECT
public:
bool createDataBaseConnection();
applicationManagement();
~applicationManagement();
void setLogger(QXmppLogger *logger);
private:
QXmppLogger *logger;
};
and related "imApplicationManager.cpp"
applicationManagement::applicationManagement()
{
QObject::connect(this, SIGNAL(logMessage(QXmppLogger::MessageType,QString)),
logger, SLOT(log(QXmppLogger::MessageType,QString)));
}
applicationManagement::~applicationManagement()
{
// db..closing
}
bool applicationManagement::createDataBaseConnection(){
//...database conncetion...
if (!dataBase.open()){
warning(QString("Cannot open database %1").arg(dataBase.lastError().text()));
qDebug()<< "Cannot open database " << dataBase.lastError();
return false;
}
info(QString("Database succeeded!"));
return true;
}
void applicationManagement::setLogger(QXmppLogger *logger)
{
if(this->logger != logger)
this->logger = logger;
}
in the main.cpp
#include "imApplicationManager"
#incLude "QXmppLogger"
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
applicationManagement aa;
QXmppLogger log;
aa.setLogger(&log);
return a.exec();
}
Compilation informs of no error but when luanched there is a Sigmentation fault.
How can I fix that?
OK, decided to post a full answer:
First of all, you do NEED the Q_OBJECT macro. The errors you get from it will likely disappear when you Clean All, Run qmake and Rebuild All from the Build menu of QtCreator. Qt relies on a LOT of generated boilerplate code you never have to type, and without Q_OBJECTthat code will not be generated. That is the reason you sometimes need to clean up after you made changes, run qmake (which generates the code) and rebuild with the now up-to-date generated code.
Second - in the constructor of applicationManagement you connect to an uninitialized pointer logger. This is probably why you get segmentation fault. You can use two approaches to fix that:
Pass the pointer to the logger in the constructor of applicationManagement, this way you have something to connect to in the constructor. This way you cannot instantiate an applicationManagement before a logger, unless you use logger(new QXmppLogger) in the constructor initialization list.
Move the connection from the applicationManagement constructor to the setLogger()method. Do not forget to disconnect a previous connection if any.
It has been mentioned that the Q_OBJECT macro is needed, but I think a little explanation would be useful too, as understanding why it's needed helps to remember to use it.
Qt adds to C++, amongst other features, the functionality of signals and slots and this is done with the Meta-Object Compiler (or moc for short). When compiling Qt code, the moc parses the header files and creates source code for you, which can be seen in the moc files. Occasionally these get out of sync and cleaning these files will fix this issue.
If you look more closely at the Q_OBJECT macro, it is defined as this: -
#define Q_OBJECT \
public: \
Q_OBJECT_CHECK \
static const QMetaObject staticMetaObject; \
virtual const QMetaObject *metaObject() const; \
virtual void *qt_metacast(const char *); \
QT_TR_FUNCTIONS \
virtual int qt_metacall(QMetaObject::Call, int, void **); \
private: \
Q_DECL_HIDDEN_STATIC_METACALL static void qt_static_metacall(QObject *, QMetaObject::Call, int, void **); \
struct QPrivateSignal {};
As can be seen here, the Q_OBJECT macro adds function definitions to the class and its the implementation of these in the QObject parent class that provides the added C++ features such as signals / slots, properties, RTTI etc. When calling signals and slots, internally Qt uses the qt_metacall function. There's an interesting explanation of the implementation of these here. Therefore without the Q_OBJECT macro in a class derived from QObject, signals and slots won't work.
You use logger but it is not initialized before:
QObject::connect(this, SIGNAL(logMessage(QXmppLogger::MessageType,QString)),
logger, SLOT(log(QXmppLogger::MessageType,QString)));
try to rewrite your constructor like that:
applicationManagement::applicationManagement(QXmppLogger *logger_):
logger(logger_)
{
QObject::connect(this, SIGNAL(logMessage(QXmppLogger::MessageType,QString)),
logger, SLOT(log(QXmppLogger::MessageType,QString)));
}
or connect that signal after initializing logger.

Qt: Measure event handling time

I would like to measure which events in my application take long time to execute in main thread (blocking GUI) or at least if there are any that take more than, lets say, 10msec. I obviously use threading and concurrency for tasks that take a long time, but it's sometimes hard to draw the line between what to put in other threads and what can stay with GUI. Especially with app that runs on multiple OSes and both new and few-years old hardware.
I looked at QApplication (and QCoreApplication) but it doesn't have any "processSingleEvent" kind of function which I cloud easily override and wrap with time measurement. Event filters also doesn't do the trick because AFAIU there is no way to get a notification after event is processed.
I thought that I could call QApplication::processEvents manually (without ever invoking exec), but again it doesn't give single-event granularity and, as I read, it doesn't handle destroy events.
I looked at QCoreApplication::exec implementation, and saw that it uses QEventLoop internally, so if I wanted to add my special code to original implementation I would have to reimplement both QApplication and QEventLoop copying a lot of code from Qt source...
Edit: the question obviously is: How to measure event handling time in possibly simple and "clean" way?
Override bool QCoreApplication::notify ( QObject * receiver, QEvent * event ):
class MyApplication : public QApplication
{
QElapsedTimer t;
public:
MyApplication(int& argc, char ** argv) : QApplication(argc, argv) { }
virtual ~MyApplication() { }
virtual bool notify(QObject* receiver, QEvent* event)
{
t.start();
bool ret = QApplication::notify(receiver, event);
if(t.elapsed() > 10)
qDebug("processing event type %d for object %s took %dms",
(int)event->type(), receiver->objectName().toLocal8Bit().data(),
(int)t.elapsed());
return ret;
}
};
int main(int argc, char *argv[])
{
MyApplication a(argc, argv);
...
That also happens to be the place for a catch all type exception handling.

Resources