Dark transparent layer over a QMainWindow in Qt

前端 未结 3 508
情话喂你
情话喂你 2020-11-29 07:50

I need to implement a \"Loading...\" window in my application but I do prefer to cover the whole QMainWindow with a dark transparent layer with a text above. Does anybody kn

3条回答
  •  谎友^
    谎友^ (楼主)
    2020-11-29 08:22

    I would suggest execute a modal, frameless dialog on top and add a graphics effect on the background widget. This is IMHO a very flexible and short solution without touching the event system directly.

    The performance might be bad - one could improve that by calling drawSource(), but I haven't a reliable solution here yet.

    class DarkenEffect : public QGraphicsEffect
    {
    public:
        void draw( QPainter* painter ) override
        {
            QPixmap pixmap;
            QPoint offset;
            if( sourceIsPixmap() ) // No point in drawing in device coordinates (pixmap will be scaled anyways)
                pixmap = sourcePixmap( Qt::LogicalCoordinates, &offset );
            else // Draw pixmap in device coordinates to avoid pixmap scaling;
            {
                pixmap = sourcePixmap( Qt::DeviceCoordinates, &offset ); 
                painter->setWorldTransform( QTransform() );
            }
            painter->setBrush( QColor( 0, 0, 0, 255 ) ); // black bg
            painter->drawRect( pixmap.rect() );
            painter->setOpacity( 0.5 );
            painter->drawPixmap( offset, pixmap );
        }
    };
    
    // prepare overlay widget 
    overlayWidget->setWindowFlags( Qt::FramelessWindowHint | Qt::Dialog | Qt::WindowStaysOnTopHint );
    
    // usage
    parentWidget->setGraphicsEffect( new DarkenEffect );
    overlayWidget->exec();
    parentWidget->setGraphicsEffect( nullptr );
    

提交回复
热议问题