简体   繁体   中英

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

I want to do something which will access network when a QMainWindow is ready.
I suppose I should not do it in the constructor, so I try to find a signal the widget will get and try to implement something like a OnReady() call back in other UI library. But I still can not find a way to do this.
Thanks a lot in advance.

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

The reason you can't do it in the constructor because the application's event loop isn't ready until some time after the constructor has finished running.

What you can do is create a slot in your MainWindow class containing the code you want to run, set up a single-shot timer in the constructor, and have that timer call your slot. For example:

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
}

Alternative way is to use QMetaObject::invokeMethod with a queued connection. If you use invokeMethod you can also pass an argument.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM