Take action after the main form is shown in a Qt desktop application

若如初见. 提交于 2019-12-02 05:00:44

问题


In Delphi I often made an OnAfterShow event for the main form. The standard OnShow() for the form would have little but a postmessage() which would cause the OnafterShow method to be executed.

I did this so that sometimes lengthy data loading or initializations would not stop the normal loading and showing of the main form.

I'd like to do something similar in a Qt application that will run on a desktop computer either Linux or Windows.

What ways are available to me to do this?


回答1:


You can override showEvent() of the window and call the function you want to be called with a single shot timer :

void MyWidget::showEvent(QShowEvent *)
{
    QTimer::singleShot(50, this, SLOT(doWork());
}

This way when the windows is about to be shown, showEvent is triggered and the doWork slot would be called within a small time after it is shown.

You can also override the eventFilter in your widget and check for QEvent::Show event :

bool MyWidget::eventFilter(QObject * obj, QEvent * event)
{
    if(obj == this && event->type() == QEvent::Show)
    {
        QTimer::singleShot(50, this, SLOT(doWork());
    }

    return false;
}

When using event filter approach, you should also install the event filter in the constructor by:

this->installEventFilter(this);



回答2:


I solved it without a timer using Paint event. Works for me at least on Windows.

// MainWindow.h
class MainWindow : public QMainWindow
{
    ...
    bool event(QEvent *event) override;
    void functionAfterShown();
    ...
    bool functionAfterShownCalled = false;
    ...
}

// MainWindow.cpp
bool MainWindow::event(QEvent *event)
{
    const bool ret_val = QMainWindow::event(event);
    if(!functionAfterShownCalled && event->type() == QEvent::Paint)
    {
        functionAfterShown();
        functionAfterShownCalled = true;
    }
    return ret_val;
}


来源:https://stackoverflow.com/questions/28458639/take-action-after-the-main-form-is-shown-in-a-qt-desktop-application

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!