How to call function after window is shown?

前端 未结 9 1213
余生分开走
余生分开走 2020-12-05 06:21

Using Qt I create a QMainWindow and want to call a function AFTER the windows is shown. When I call the function in the constructor the fun

9条回答
  •  心在旅途
    2020-12-05 07:09

    Assuming you want to run your code in the UI thread of the window after the window has been shown you could use the following relatively compact code.

    class MainWindow : public QMainWindow
    {
            // constructors etc omitted.
    
    protected:
        void showEvent(QShowEvent *ev)
        {
            QMainWindow::showEvent(ev);
            // Call slot via queued connection so it's called from the UI thread after this method has returned and the window has been shown
            QMetaObject::invokeMethod(this, "afterWindowShown", Qt::ConnectionType::QueuedConnection);
        }
    
    private slots:
        void afterWindowShown()
        {
            // your code here
            // note this code will also be called every time the window is restored from a minimized state
        }
    };
    

    It does invoke afterWindowShown by name but that sort of thing is fairly common practice in Qt. There are ways of avoiding this but they're a bit more verbose.

    Note that this code should work for any QWidget derived class, not just QMainWindow derived classes.

    In theory it might be possible for a very quick user to invoke some sort of action on the UI of the displayed window before afterWindowShown can be called but it seems unlikely. Something to bear in mind and code defensively against perhaps.

提交回复
热议问题