How do I create a unique connection on a Qt connect?

Viewed 75

I am creating a timer, so I can call a function periodically, I use the function connect to make the connection between the timer and the function. The code follows:

  QTimer *timer = new QTimer(this);
  connect(timer, SIGNAL(timeout()), this, SLOT(DevicesScanner::scanUpdate()));
  timer->start(1000);

My question is: How do I make this connection unique, so the timer is not created multiple times?

3 Answers

You have a few options.

  1. Make sure that your code is called once or at least uniquely.

  2. Use singleShot.

#include <QApplication>
#include <QTimer>
        
int main(int argc, char *argv[])
{
    QApplication app(argc, argv);
    QTimer::singleShot(600000, &app, SLOT(quit()));
    return app.exec();
}
  1. Use Qt::UniqueConnection.

This is a flag that can be combined with any one of the above connection types, using a bitwise OR. When Qt::UniqueConnection is set, QObject::connect() will fail if the connection already exists (i.e. if the same signal is already connected to the same slot for the same pair of objects). This flag was introduced in Qt 4.6.

QTimer should be defined in class member variable or you can define it in static variable area.The timer will be only create once.

My question is: How do I make this connection unique, so the timer is not created multiple times?

Your timer is not created multiple times unless your 1st line of code is called multiple times.

Below is an explanation of your current code:

  // 1. Create a new instance of QTimer
  QTimer *timer = new QTimer(this);

  // 2. Connect timeout signal of the this timer instance to the scanUpdate() slot
  connect(timer, SIGNAL(timeout()), this, SLOT(DevicesScanner::scanUpdate()));

  // 3. Start this repetitive timer with an interval of 1 second. From now on scanUpdate() slot shall be called every second.
  timer->start(1000);

Timer creation and the timeout signal connection must be executed just once (You could do this in your constructor).
Then you are free to trigger the timer's start() and stop() slots to control the calling of your function periodically (You could do this in your constructor or your member functions).

Related