Is there a way to implement the OnReady () callback in Qt4?

I want to do something that will access the network when the QMainWindow is ready.
I suppose I shouldn't be doing this in the constructor, so I'm trying to find the signal that the widget will receive and try to implement something like a call to OnReady () in another UI library. But I still cannot find a way to do this.
Thank you very much in advance.

+2


a source to share


2 answers


If I understand correctly, you need to do something as soon as the application's event loop is ready to handle events.

The reason you can't do this in the constructor is because the application's event loop isn't ready until the constructor has finished.

What you can do is create a slot in your MainWindow class that contains the code you want to run, set up a one-shot timer in the constructor, and set up a timer for your slot. For instance:

mainwindow.h



class MainWindow : public QMainWindow                                                                                                        
{                                                                                                                                            
  Q_OBJECT                                                                                                                                   
public:                                                                                                                                      
  MainWindow(QWidget *parent = 0);                                                                                                           
  ~MainWindow();                                                                                                                             
private slots:
  void doStuff(); // This slot will contain your code
// ...
// ...
// ...
}

      

mainwindow.cpp

:

MainWindow::MainWindow(QWidget *parent)                                                                                                      
  : QMainWindow(parent), ui(new Ui::MainWindow)                                                                                              
{                                                                                                                                            
  ui->setupUi(this);
  QTimer::singleShot(0, this, SLOT(doStuff())); // This will call your slot when the event loop is ready
  // ...
  // ...
  // ...
}

void MainWindow::doStuff()
{
  // This code will run as soon as the event loop is ready
}

      

+4


a source


An alternative way is to use it QMetaObject::invokeMethod

with a regular connection. If you are using invokeMethod, you can also pass an argument.



QMetaObject::invokeMethod(
    this, 
    "onReady", 
    Qt::QueuedConnection, 
    Q_ARG(QString, argument));

      

0


a source







All Articles