QMainWindow透明背景

先上效果图,

实现方法就是设置WA_TranslucentBackground属性,并禁止窗口自动填充背景。

#include <QApplication>
#include <QMainWindow>
#include <QPainter>

class CMainWindow : public QMainWindow
{
public:
    CMainWindow(QWidget* parent = 0) : QMainWindow(parent)
    {
        setAutoFillBackground(false);
//        setWindowFlags(Qt::FramelessWindowHint);
        setAttribute(Qt::WA_TranslucentBackground, true);
    }

protected:
    void paintEvent(QPaintEvent*)
    {
        QPainter pt(this);
        QColor c(Qt::gray);
        c.setAlpha(100);
        pt.fillRect(rect(), c);
    }
};


int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    CMainWindow w;
    w.show();
    return a.exec();
}

需要注意不能使用QtCreator创建的UI文件来创建QMainWindow,会有一个黑色的背景无法祛除。

原文地址:https://www.cnblogs.com/vectorli/p/4792347.html