如何使用 Qt Quick 制作透明窗口?

2022-01-19 00:00:00 qt qml qt-quick transparent c++

有没有办法让 qml 应用程序的窗口透明?

Is there a way to make the window of a qml application transparent?

我正在寻找关于如何使用 qml 绘制简单形状同时使应用程序窗口以及背景透明的详细说明.一个有效的源代码演示会很棒.

I'm looking for a detailed description on how to draw simple shapes with qml while making the window of the application transparent, as well as the background. A working source code demo would be awesome.

推荐答案

我终于找到了一种简单的方法,可以在保持窗口透明的同时绘制几个红色/蓝色矩形.

I finally found a simple way to draw a couple of red/blue rectangles while leaving the window transparent.

draw_rectangles.qml

import Qt 4.7

Item {
     Rectangle {
         opacity: 0.5
         color: "red"
         width: 100; height: 100
         Rectangle {
             color: "blue"
             x: 50; y: 50; width: 100; height: 100
         }
     }
 }

win.cpp:

#include <QApplication>
#include <QDeclarativeView>
#include <QMainWindow>

int main(int argc, char *argv[])
{
    QApplication app(argc, argv);
    QMainWindow window;

    QDeclarativeView* v = new QDeclarativeView;
    window.setCentralWidget(v);

    v->setSource(QUrl::fromLocalFile(("draw_rectangles.qml")));   

    window.setStyleSheet("background:transparent;");
    window.setAttribute(Qt::WA_TranslucentBackground);
    window.setWindowFlags(Qt::FramelessWindowHint);
    window.show();

    return app.exec();
}

win.pro:

TEMPLATE += app
QT += gui declarative
SOURCES += win.cpp

将这些文件保存到同一目录并执行qmake,然后执行make来编译应用程序.

Save these files to the same directory and execute qmake followed by make to compile the application.

相关文章