How can I create a process in C++ or Qt? - c++

hello people a need your help, can be with qt or c++, i want to create a process BUT a process that use a function of my program not an external program, something like this .... sorry for the example and forgive my english thanks
void count(){blablabla}
int main(){QProcess p = new QProcess(count());p.start();}

IMHO, the easiest way would be to use threads. If your only objection to using thread is that the thread will be terminate, you can overcome it by waiting for the thread to finish before exiting the process.
void doSomething();
int main (int argc, char *argv[])
{
QApplication app(argc, argv);
...
// Start a doSomething() in another thread using pure C++11
std::thread cppThread(&doSomething);
// The same using Qt
QFuture<void> qtThreadResult = QtConcurrent::run(&doSomething);
...
int r = app.exec();
...
// The Qt application is closed
// We wait for the thread to complete
cppThread.join();
// The same using Qt
qtThreadResult.waitForFinished();
// Everything is finished, we can exit
return r;
}
If you absolutely need to create another process you have 2 solutions, either you create 2 programs A and B, and you start B from A, or you have a single program and you need to provide a command line argument so it can change its behavior.
void doSomething();
int main (int argc, char *argv[])
{
QApplication app(argc, argv);
if (app.arguments().contains("--foo"))
{
doSomething();
return 0;
}
else
{
return app.exec();
}
}
You can then start the new process using Qt:
QProcess::startDetached("B");
QProcess::startDetached("A --foo");
QProcess::startDetached(QCoreApplication::applicationFilePath(), QStringList{"--foo"});
Using pure C++ it gets a little more complicated. You have system() on all platforms but it does not offer a lot of option if you need to manipulate the created process. Then you have platform specific solutions like execl() (& co.) on Linux and CreateProcess() on Windows.
Also note that this can get even more complicated if you need to share data between the 2 processes ; you will need to play with shared memories or sockets or pipes or stdin/stdout...

You can use QTimer. This will emit the timeout() signal at constant intervals.
Example for one second timer,
QTimer *timer = new QTimer(this);
connect(timer, SIGNAL(timeout()), this, SLOT(count()));
timer->start(1000);
From then on, the count() slot is called every second.
QTimer

I've done this via QtConcurrent as follow:
1) declare the method, which should run on an own thread:
void TestClass::startWorkerThread(int parameter1) {
// do something
}
2) Start the method in a thread:
#include <QtConcurrent/QtConcurrent>
...
QFuture<void> pFuture1 = QtConcurrent::run(this, &TestClass::startWorkerThread, parameter1);

Related

timer couldn't work with wiringPiISR (QtQuick application)

I have created a class Capteur_Input and one of the options in the constructor creates an interrupt using wiringPiISR
wiringPiISR(m_pin, INT_EDGE_RISING, isrInput);
my class also has an attribute m_impulsion and I am incrementing this value each time that an interruption happens.
this what my interrupt handler looks like
void Capteur_Input::isrCallback()
{
if(m_pin== Pin_vitesse)
{
increment_impulsion();
emit digital_inputChanged(m_impulsion);
}
else
emit digital_inputChanged(m_value);
}
in my main.cpp I created an instance of this class
static void isrInput_vitesse();
static Capteur_Input vitesse(Pin_vitesse,PUD_OFF,INT_EDGE_RISING,isrInput_vitesse);
static void isrInput_vitesse()
{
vitesse.isrCallback();
}
every thing is working fine, the qml and C++ part.
and now I want to calculate the number of impulse detected per second. but I couldn't do it.
my class Capteur_Input also has a timer, I configured it in the constructor
m_timer =new QTimer (this);
m_timer->setTimerType(Qt::PreciseTimer);
connect (m_timer,SIGNAL(timeout()),this,SLOT(onTimeout()));
m_timer->start(500);
and I tried to test in the SLOT onTimeout() someting but this qDebug()<<"VITESSEEEEEEEE"<<m_pin <<readPin()<<vitesse; never shows up. I don't know why maybe because wiringPiISR is a thread and has a higher priority than the timer?
can someone explain to me please, how to make a timer that calculates the exact time and make the interrupt work in the same time?
the timer is working for the other instances of this class that are just inputs no interruptions
void Capteur_Input::onTimeout()
{
qDebug()<<"time is up"<<m_pin;
if(m_pin== Pin_vitesse)
{
qDebug()<<"m_pin== Pin_vitesse";
int vitesse;
vitesse= int (calcul_vitesse/4*2.166);//*0.001/3600;
qDebug()<<"VITESSEEEEEEEE"<<m_pin <<readPin()<<vitesse;
emit vitesse_Changed(vitesse);
qDebug()<<"VITESSEEEEEEEE"<<m_pin <<readPin()<<vitesse;
}
else{
emit digital_inputChanged(readPin());
qDebug()<<"signal DIGITAL emitted m_pin"<<m_pin <<"value"<<readPin();
}
}
actually the slot onTimeout is working for these 2 instances
#define Pin_vitesse 3
#define PinFrein 0
#define PinClignotnat_G 2
Capteur_Input frein(PinFrein,PUD_UP,NO_INTERRUPT);
Capteur_Input clignotant_G(PinClignotnat_G,PUD_DOWN,NO_INTERRUPT);
and is not working for this one which is an interrupt static Capteur_Input vitesse(Pin_vitesse,PUD_OFF,INT_EDGE_RISING,isrInput_vitesse);
and this what I got as an output
time is up 0
signal DIGITAL emitted 0 1
time is up 2
signal DIGITAL emitted 2 0
time is up 0
signal DIGITAL emitted 0 1
the timer is working for the other instances and it is not working for the one that is an interrupt
Static QObject instance is not supported in Qt, as stated below (QObject reentrancy section ):
In general, creating QObjects before the QApplication is not supported
and can lead to weird crashes on exit, depending on the platform. This
means static instances of QObject are also not supported. A properly
structured single or multi-threaded application should make the
QApplication be the first created, and last destroyed QObject.
If you need a callback when isr interrupt comes up, a static pointer should work:
static void isrInput_vitesse();
static Capteur_Input *vitesse = nullptr;
static void isrInput_vitesse()
{
if(!vitesse) //not initialized yet
return;
QMetaObject::invokeMethod( vitesse, "isrCallback", Qt::QueuedConnection ); //or blockingQueue if you need to handle it directly in Qt way.
}
The vitesse pointer should be initialized in main() after the initialization of QApplication instance.
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
//..... your main application body
vitesse = new Capteur_Input(Pin_vitesse,PUD_OFF,INT_EDGE_RISING,isrInput_vitesse);
//...
}
Your timeout signal might be interfered or delayed.
You may try to specify a Qt::Connectiontype to force Qt to treat your timeout signal as soon as it is emitted.
QObject::connect(m_timer, &QTimer::timeout, this, &Capteur_Input::onTimeOut, Qt::DirectConnection);
This will deliver the timeout signal to the ontimeOut slot as soon as it is emitted.

QT Multi-threading & Updating GUI

I'm currently updating an existing codebase designed to be used with a GTK GUI to QT, so that it can implement multi threading, as the functions take hours to complete.
This codebase makes frequent calls to a function display(std::string), for the purpose of updating a text display widget. I redefined this function for the new QT version:
In Display.cpp:
void display(std::string output)
{
//
MainWindow * gui = MainWindow::getMainWinPtr(); //Gets instance of GUI
gui->DisplayInGUI(output); //Sends string to new QT display function
}
In MainWindow.cpp:
void MainWindow::DisplayInGUI(std::string output)
{
//converts output to qstring and displays in text edit widget
}
void MainWindow::mainFunction(){
//calls function in existing codebase, which itself is frequently calling display()
}
void MainWindow::on_mainFunctionButton_released()
{
QFuture<void> future = QtConcurrent::run(this,&MainWindow::mainFunction);
}
If I run the main function in a new thread, display(std::string) won't update the GUI until the thread completes. I understand why; the GUI can only be updated in the main thread. Everything else functions as intended.
What I want to implement, but I'm not sure how, is having display(std:string) send a signal back to the main thread to call MainWindow::DisplayInGUI(output_text) with the string that was passed to the display() function. I believe this is the correct way to do it, but correct me if I'm wrong. I want to avoid changing the existing codebase at all costs.
EDIT: I should add that for some dumb reasons entirely out of my control, I am forced to use C++98 (yeah, I know)
You must schedule the code that does UI calls to run in the main thread. I use a simple and easy to use wrapper for that:
#include <QApplication>
#include <QtGlobal>
#include <utility>
template<typename F>
void runInMainThread(F&& fun)
{
QObject tmp;
QObject::connect(&tmp, &QObject::destroyed, qApp, std::forward<F>(fun),
Qt::QueuedConnection);
}
You can now run code (using a lambda in this example, but any other callable will work) in the main thread like this:
runInMainThread([] { /* code */ });
In your case:
void display(std::string output)
{
runInMainThread([output = std::move(output)] {
MainWindow* gui = MainWindow::getMainWinPtr();
gui->DisplayInGUI(output);
});
}
Or you can leave display() as is and instead wrap the calls to it:
runInMainThread([str] { display(std::move(str)); );
The std::move is just an optimization to avoid another copy of the string since you should not pass the string by reference in this case (it would be a dangling reference once the string object goes out of scope.)
This is not a high performance inter-thread communication mechanism. Every call will result in the construction of a temporary QObject and a temporary signal/slot connection. For periodic UI updates, it's good enough and it allows you to run any code in the main thread without having to manually set up signal/slot connections for the various UI update operations. But for thousands of UI calls per second, it's probably not very efficient.
First of all: there's no way to make the getMainWinPtr method thread-safe, so this pseudo-singleton hack should probably go away. You can pass around some application-global context to all the objects that do application-global things like provide user feedback. Say, have a MyApplication : QObject (don't derive from QApplication, it's unnecessary). This can be passed around when new objects are created, and you'd then control the relative lifetime of the involved objects directly in the main() function:
void main(int argc, char **argv) {
QApplication app(argc, argv);
MainWindow win;
MyApplication foo;
win.setApplication(&foo);
// it is now guaranteed by the semantics of the language that
// the main window outlives `MyApplication`, and thus `MyApplication` is free to assume
// that the window exists and it's OK to call its methods
...
return app.exec();
}
Of course MyApplication must take care that the worker threads are stopped before its destructor returns.
To communicate asynchronous changes to QObject living in (non-overloaded) QThreads (including the main thread), leverage the built-in inter-thread communication inherent in Qt's design: the events, and the slot calls that traverse thread boundaries.
So, given the DisplayInGUI method, you need a thread-safe way of invoking it:
std::string newOutput = ...;
QMetaObject::invokeMethod(mainWindow, [mainWindow, newOutput]{
mainWindow->displayInGUI(newOutput);
});
This takes care of the thread-safety aspect. Now we have another problem: the main window can get hammered with those updates much faster than the screen refresh rate, so there's no point in the thread notifying the main window more often than some reasonable rate, it'll just waste resources.
This is best handled by making the DisplayInGUI method thread-safe, and leveraging the timing APIs in Qt:
class MainWindow : public QWidget {
Q_OBJECT
...
static constexpr m_updatePeriod = 1000/25; // in ms
QMutex m_displayMutex;
QBasicTimer m_displayRefreshTimer;
std::string m_newDisplayText;
bool m_pendingRefresh;
...
void timerEvent(QTimerEvent *event) override {
if (event->timerId() == m_displayRefreshTimer.timerId()) {
QMutexLocker lock(&m_displayMutex);
std::string text = std::move(m_newDisplayText);
m_pendingRefresh = false;
lock.release();
widget->setText(QString::fromStdString(text));
}
QWidget::timerEvent(event);
}
void DisplayInGUI(const std::string &str) {
// Note pass-by-reference, not pass-by-value. Pass by value gives us no benefit here.
QMutexLocker lock(&m_displayMutex);
m_newDisplayText = str;
if (m_pendingRefresh) return;
m_pendingRefresh = true;
lock.release();
QMetaObject::invokeMethod(this, &MainWindow::DisplayInGui_impl);
}
private:
Q_SLOT void DisplayInGui_impl() {
if (!m_displayRefreshTimer.isActive())
m_displayRefreshTimer.start(this, m_updatePeriod);
}
};
In a more complex situation you'd likely want to factor out the cross-thread property setting to some "adjunct" class that would perform such operations without the boilerplate.
You could take advantage of the fact that QTimer::singleShot has an overload which, when called with a zero time interval, allows you to effectively schedule a task to be run on a specified thread during that thread's next idle slot...
void QTimer::singleShot(int msec, const QObject *context, Functor functor);
So your MainWindow::mainFunction could be something along the lines of...
void MainWindow::mainFunction ()
{
...
std::string output = get_ouput_from_somewhere();
QTimer::singleShot(0, QApplication::instance(),
[output]()
{
display(output);
});
...
}

QT - Mainwindow doesn't update unless it's closed

I'm trying to update the main window by calling updateGUI function in a thread every 500 ms. The window is displayed but not updated with the new values unless I close the window. When I do so, a new window is opened with the new value. I found this question but it didn't answer my question. I knew that (as stated in qt documentation)
QApplication::exec enters the main event loop and waits until
exit() is called.
I tried to use processEvents() but the main window is opened and closed repeatedly and very fast that I can't even see it. Here is my code:
float distanceToObject;
bool objectDetected;
Modes currentMode;
void timerStart(std::function<void(void)> func, unsigned int interval)
{
std::thread([func, interval]()
{
while (true)
{
auto x = std::chrono::steady_clock::now() + std::chrono::milliseconds(interval);
func();
std::this_thread::sleep_until(x);
}
}).detach();
}
int updateGUI(void)
{
int argc = 0;
char **argv = NULL;
QApplication a(argc, argv);
MainWindow w;
// Set text of a label
w.setDistance(QString::number(distanceToObject));
// Also update objectDetected and currentMode values
w.show();
//a.processEvents();
return a.exec();
}
void sendMsg(void)
{
// Send heartbeat signal to another device
}
void receiveMsg(void)
{
// Read messages from the other device and update the variables
// These two values change continuously
objectDetected = true;
distanceToObject = 5.4;
}
void decide(void)
{
// The core function of the program. Takes relatively long time
// Run a decision-making algorithm which makes decisions based on the values received from the other device.
// Update some variables according to the made decisions
currentMode = Auto;
// Execute functions according to the made decisions.
setMode(currentMode);
}
int main(void)
{
timerStart(updateGUI, 500);
timerStart(sendMsg, 1000);
timerStart(receiveMsg, 10);
timerStart(decide, 500);
}
How can I update the main window with the variables' values correctly?
Your thread does not update the MainWindow, but it does create an entirely new QApplication and MainWindow on every iteration. Your thread should be stuck inside QApplication::exec until you quit the application (e.g. by closing the window). Only then should your thread's loop make further progress.
In general, you must be very careful when doing updates from outside the main thread, since typically GUI operations must be performed inside the main thread.
Think about using QThread, which already comes with its own event loop, which you can use to notify/update your window using a respective slot.
Without further details about what you are actually trying to achieve, it is not possible to give you further direction. I, at least, recommend that you create your QApplication and MainWindow inside the main thread (e.g. main). Then it depends what you are trying to 'update'. If you need to progress some data, then you can do that within your second thread and send the results to your MainWindow instance using signal-slot. If you need to draw onto the window, then this either has to be done in the main thread directly, or you might find a way to render into a separate buffer (i.e. QImage) from within your thread and then send this buffer to the main thread for drawing it into the window.
I try to sketch how something like this can be done. Notice, however, that this it neither complete nor compilable, but merely an outline.
First, you have your MainWindow and add to it a signal, that notifies all observers to start doing their work (will become clear in a moment). Furthermore, you add slots that will be invoked whenever one of your values changes. Those slots run in the main thread (and are members of the MainWindow) and thus can update the window however they need to:
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
// constructors and stuff
void startWorking()
{
emit startWorkers();
}
public slots:
void onModeChanged(Modes m)
{
// update your window with new mode
}
void onDistanceChanged(float distance)
{
// update your window with new distance
}
signals:
void startWorkers();
};
Next, you build a Worker class, that encapsulates all the 'background work' you like to do (basically what your thread did in your original code):
class Worker : public QObject
{
Q_OBJECT
public:
// constructors and stuff
public slots:
void doWork()
{
while(!done)
{
// do stuff ...
Modes m = // change mode
emit modeModified(m);
// do stuff ...
float distance = // compute distance
emit distanceModified(distance);
// do stuff ...
}
}
signals:
void modeModified(Modes m);
void distanceModified(float distance);
};
Note, that Worker must inherit QObject and that your doWork method must be a public slot. Furthermore, you add a signal for each of the values you like your MainWindow to be informed about. No implementation for them is needed, since it is generated by the Qt MOC (Meta Object Compiler). Whenever one of the respective values changes, simply emit the corresponding signal and pass the new value.
Lastly, you put everything together:
int main(int argc, char* argv[])
{
QApplication app(argc, argv);
MainWindow window;
// create a worker object
Worker* worker = new Worker;
// connect signals and slots between worker and main window
QObject::connect(worker, &Worker::modeModified,
&window, &MainWindow::onModeChanged);
QObject::connect(worker, &Worker::distanceModified,
&window, &MainWindow::onDistanceChanged);
QObject::connect(&window, &MainWindow::startWorkers,
worker, &Worker::doWork);
// create a new thread
QThread* thread = new QThread;
// send worker to work inside this new thread
worker->moveToThread(thread);
thread->start();
// show window and start doing work
window.show();
window.startWorking();
// start main loop
int result = app.exec();
// join worker thread and perform cleanup
return result;
}
Alright, let's go through it. First, you create your QApplication and MainWindow inside your main thread. Next, create an instance of your Worker object (could create multiple here). Then you connect the signals of the worker to the slots of the window and vice versa. Once these connections are established, whenever you emit a signal, the connected slot is invoked by Qt (and passed values are transmitted). Notice, that this connection works across thread boundaries. Whenever a signal is emitted from a thread different then the receiving object's thread, Qt will send a message, which is processed in the receiving object's thread.
Then you tell Qt that you want your worker to live inside another thread using QObject::moveToThread. See here for a very detailed explanation of how to correctly use QThread and objects inside it.
The rest is then simple. show your window and start processing. Here different ways are possible. I just call the startWorking method here, which then emits the startWorkers signal, which is connect to the worker's doWork method, such that doWork will start executing after this signal is received by the other thread.
You then call QApplication::exec which runs the main thread's event loop, where all these signals are processed by Qt. Once your application is closed (e.g. by calling quit or closing the main window) the exec method returns and you are back in main. Notice, that you need to correctly close the thread (e.g. by sending an addition signal that stops the while loop) and join it. You also should delete all the allocated objects (worker, thread). I omitted this here for simplicity of the code example.
Answering your Question
I have many functions, e.g., updateClips and mavReceive that should be called periodically and run independently from each other. I should create a different Worker class for each function, as each has different signals, and a QThread object for each of these functions, right? I don't need startTimer() anymore? If yes, how can I control the calling interval for each function (used to be done in startTimer()
from the comment:
The answer greatly depends on what exactly you mean by "should be called periodically". Who is supposed to call them? The user? Or should they just be executed periodically?
So in principle, you can have multiple workers in one thread. However, if they are supposed to do work all the time (spin in a while loop) it does not make sense, since one is running and all others are blocked. In that case you would have one thread for each worker.
If I understand you correctly, you are interested in updating something periodically (e.g. every 500ms). In that case I highly recommend using the QTimer. You can set an interval and then start it. The timer will then periodically emit the timeout signal, which you can connect to whatever function (more precisely slot) you want to have executed.
An updated version of the Worker could look like this:
class Worker : public QObject
{
Q_OBJECT
public:
Worker()
{
QObject::connect(&modeTimer_, &QTimer::timeout,
this, &Worker::onModeTimerTimeout);
QObject::connect(&distanceTimer_, &QTimer::timeout,
this, &Worker::onDistanceTimerTimeout);
modeTimer_.start(500); // emit timeout() every 500ms
distanceTimer_.start(100); // emit timeout() every 100ms
}
public slots:
void onModeTimerTimeout()
{
// recompute mode
Modes m = // ...
emit modeModified(m);
}
void onDistanceTimerTimeout()
{
// recompute distance
float distance = // ...
emit distanceModified(distance);
}
signals:
void modeModified(Modes m);
void distanceModified(float distance);
private:
QTimer modeTimer_;
QTimer distanceTimer_;
};
Notice, the connections established in the constructor. Whenever one of the timers times out, the connected slot is invoked. This slot then may compute whatever it needs to and afterwards send the result back to the MainWindow in the main thread using the same signal as before.
So, as you see, you can have multiple timers / re-computations / update signals within one Worker (and thus, one thread). However, the crucial point for an implementation is, how long the computations take. If they take very long (e.g. nearly as long as the intervals) then you should think about using multiple threads to speed up the computation (meaning: perform one computation in each thread). As I slowly seem to get a clearer picture of what you want to achieve, I am wondering whether it is only about these periodic updates that you 'misused' the thread for in your question. If this is indeed the case, then you do not need that thread and Worker at all. Then simply add the timers to your MainWindow and connect their timeout signal to the respective slot of the MainWindow directly.

QEventLoop for synchronous wait for signal

I'm using Qt5, QCoreApplication.
In order to allow for readable and easy to maintain code, I need to write a blocking method in a class/thread A that will emit a signal, connected to a slot in a different thread B, and then wait for an answer or a timeout to occur asynchronously in thread B.
I have first been thinking about what felt like a natural solution: let thread B reply with a signal connected to a slot in thread A, and somehow wait for it. It seems QEventLoop can do that for me. But I keep reading contradictory statements: that's the pattern but avoid it if you can :-).
I'm pretty sure I could achieve my purpose by blocking A on a 0 QSemaphore that B would release when ready. The code would probably not be much more complex that way.
What do you experienced Qt developers think?
Is there a good solution or do you find some symptoms of flawed analysis in my description (i.e. do you think I should never ever need to do something like that? :-))?
The key ingredient you can leverage is the Qt::BlockingQueuedConnection.
This connection type lets you pass return value from a slot. You can use it in a signal-slot connection. You can also directly invoke the slot without using a signal through the QMetaMethod::invoke / QMetaObject::invokeMethod mechanism.
#include <QDebug>
#include <QThread>
#include <QCoreApplication>
class Master : public QObject {
Q_OBJECT
public:
Q_SIGNAL bool mySignal();
Q_SLOT void process() {
if (mySignal()) { // this can be a blocking call
qDebug() << "success!";
}
thread()->quit();
}
};
class Slave : public QObject {
Q_OBJECT
public:
Q_SLOT bool mySlot() {
// do whatever processing is needed here
// It's OK to call QCoreApplication::processEvents here
return true;
}
};
int main(int argc, char** argv) {
QCoreApplication app(argc, argv);
QThread masterThread, slaveThread;
Master master;
Slave slave;
master.moveToThread(&masterThread);
slave.moveToThread(&slaveThread);
slave.connect(&master, SIGNAL(mySignal()), SLOT(mySlot()),
Qt::BlockingQueuedConnection);
masterThread.start();
slaveThread.start();
QMetaObject::invokeMethod(&master, "process");
masterThread.wait();
slaveThread.quit();
slaveThread.wait();
return 0;
}
#include "main.moc"
if you just want to emit a signal in your thread, which means your main thread will have a slot to connect you thread signal, it is simple, just emit it.
but if you want a slot in your thread, and receive signal and so something in your thread, you have to use QEventloop in you run method.
usually, I will just use QThread::wait to wait for other thread end.
be careful here, some Qt objects cannot work across the thread like QSql* and QTcpSocket....

Qt Slot not being Called

I got a program in which I connect with a QSignalMapper multiple signal from object to a slot in the main program:
class A()
{
private:
QSignalMapper * signalMapperRead_;
std::vector<Service*> services_;
public:
void initConnection()
{
signalMapperRead_ = new QSignalMapper();
connect(signalMapperRead_, SIGNAL(mapped(int)), this, SLOT(readyToSendToService(int)));
for ( size_t i = 0 ; i < services_.size() ; ++i )
{
connect(services_.at(i), SIGNAL(readyToSendToServer()), signalMapperRead_, SLOT(map()));
signalMapperRead_->setMapping(services_.at(i), (int)i);
}
}
int run()
{
initConnection();
for(;;)
{
//do stuff;
}
}
};
int main()
{
QApplication app(argc, argv);
A * a = new A();
a->run();
return app.exec
}
then, as the program is a kind of server i make him loop, and waiting for new client, ...
But the slot is never called. I am thinking that maybe it's because the program is always in the loop and never check if a signal has been emitted.
Can you please help me
Don't use your own loop, create a QApplication and call its exec() method.
You have to call QApplication::exec() for Qt to deliver signals.
Edit for changed code: Just remove the for(;;)-Loop, it's uneccessary. QApplication::exec() has its own loop.
But the slot is never called.
The Qt documentation about QApplication::exec says:
Enters the main event loop and waits until exit() is called [...].
It is necessary to call this function to start event handling. The main event loop receives events from the window system and dispatches these to the application widgets. [...]
Generally, no user interaction can take place before calling exec(). [...]
This means that it's the exec method that takes care of the signal-slot system. You are calling A::run (before the exec function) which contains an for(;;) infinite loop which will block the real loop from being executed leading to your signals to be lost.
I have found a work-around. Beside I am not sure it's very efficient, my solution is to start a QEventLoop at every cycle of my for(;;) loop, and I made this QEventLoop quit on a QTimer timeout