QDialog show() - before displaying, the window area is painted white

580 Views Asked by At
auto*w=new Dialog1();
w->show();

QDialog show() - before displaying, the window area is painted white. You may not notice this on fast computers. How to avoid this ?

If I use

auto*w=new Dialog1();
w->setWindowFlags(Qt::FramelessWindowHint); 
w->show();

then there is no white paint, but there is no window header

Windows 10. Desktop Qt 5.15.0 MinGW 64-bit

Link to project https://drive.google.com/file/d/1vpuon7lIByZzgjJ0nBg8qU1e5SZAX46Z/view

Video - https://drive.google.com/file/d/1-gs5UrD62f_JIUFYu4zZftSaxCAbV9zr/view?usp=sharing

2

There are 2 best solutions below

0
On BEST ANSWER

I solved this problem

class Dialog1 : public QDialog
{
    Q_OBJECT
 
public:
    explicit Dialog1(QWidget *parent = nullptr);
    ~Dialog1();
 
private:
    Ui::Dialog1 *ui;
protected:
    bool event(QEvent*e);
};

Dialog1::Dialog1(QWidget *parent) :
    QDialog(parent),ui(new Ui::Dialog1)
{
    ui->setupUi(this);
 
    setWindowFlags(Qt::Window);
    setWindowOpacity(0);
}
 
bool Dialog1::event(QEvent*e)
{
    if(e->type()==QEvent::WindowActivate)
    {
        QTimer::singleShot(0,NULL,[this](){this->setWindowOpacity(1);});
        return true;
    }
    if(e->type()==QEvent::Hide)
    {
        setWindowOpacity(0);
        return true;
    }
    return QDialog::event(e);
}

This is not a Qt problem, this is a Windows problem. I looked at my WPF and Windows Forms projects and saw that they have this problem. You can also see it by running Windows Explorer or Windows Task Manager. Another question is whether this is considered a problem. I think so, Yes. This flickering hits my eyes

3
On

I tried your code and found that MainWindow is painted white on the start, but both dialogs are OK.

I'll show how to address the MainWindow issue, and you can use it with any widget.

The problem is, at the very first painting, QPainter takes some time to be initialized. So the solution is to perform first paint before the window is shown.

Code:

#include "mainwindow.h"
#include <QApplication>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);

    MainWindow w;
    w.grab(); // draw to an offscreen buffer
    w.show();

    return a.exec();
}