使用 QtQuick 2.0 的透明小部件

2022-01-19 00:00:00 qt graphics qml c++ directx

我正在尝试使用 QtQuick 2.0 创建一个透明窗口.

I'am trying to create a transparent window with QtQuick 2.0.

我可以创建一个像这样的透明小部件:

I can create a transparent widget like that:

class TransparentWidget : public QWidget
{
public:
    TransparentWidget(QWidget* parent)
    : QWidget(parent)
    {
        resize(QSize(500, 500));
        setAttribute(Qt::WA_TranslucentBackground);
        setWindowFlags(Qt::FramelessWindowHint);
    }

    void paintEvent(QPaintEvent * event)
    {
        QPainter painter;
        QBrush brush(Qt::cyan);
        painter.begin(this);
        painter.setRenderHint(QPainter::Antialiasing);
        painter.setBrush(brush);
        painter.drawRect(0,0,100,100);
        painter.end();
    }
};

现在我想用 QQuickView 做同样的事情,首先我创建它:

Now i want to do the same thing with QQuickView, first i create it:

QQuickView view;
view.setSource(QUrl::fromLocalFile("test.qml"));
view.setResizeMode(QQuickView::SizeRootObjectToView); 

这是我的test.qml"文件:

and here is my "test.qml" file:

Rectangle
{
    width: 300;
    height: 300;
    color: "transparent";

    Rectangle
    {
        anchors.top: parent.top;
        anchors.left: parent.left;
        width: 50;
        height: 100;
        color: "lightsteelblue";
    }

    Rectangle
    {
        anchors.bottom: parent.bottom;
        anchors.right: parent.right;
        width: 50;
        height: 100;
        color: "darkgrey";
    }
}

现在我想创建一个透明小部件,我就是这样做的:

now I want to create a transparent widget and i did it like that:

QWidget *p = QWidget::createWindowContainer(&view, NULL, Qt::FramelessWindowHint);
p->setAttribute(Qt::WA_TranslucentBackground);
p->show();

我创建了一个带有 WA_TranseculentBackground 和 FramelessWindowHint 的小部件,就像我使用前一个的方式一样,但它不起作用.

i create a widget with WA_TranseculentBackground and FramelessWindowHint just like the way i did with the previous one but it didn't work.

比深入一点并使用 pix 来查看 QQuickView 后面调用了什么,我看到了这一行:

Than go a little deeper and used pix to see whats QQuickView calling behind and i see this line:

现在我的问题:

1 - 为什么 Qt 用白色调用 IDirect3DDevice9::clear?

1 - Why Qt is calling IDirect3DDevice9::clear with color white?

2- 有没有办法告诉 QQuickView 或 QmlEngine 不要绘制背景?

2- Is there a way to tell QQuickView or QmlEngine not to draw background anything?

推荐答案

QtQuick2 的透明性从 Qt 5.2 开始工作,至少对于 Windows(Angle 和 OpenGL 构建):

Transparency with QtQuick2 works since Qt 5.2, at least for Windows (both Angle and OpenGL builds):

创建视图:

QQuickView view;
view.setOpacity(0.9999);
view.setColor( Qt::transparent );
view.setSource( QUrl::fromLocalFile( QLatin1String( "Main.qml" ) ) );

除了 setOpacity 和 setColor 之外,不需要额外的样式/属性/标志调用.Main.qml"必须正确设置透明度,就像您的 QML 示例一样:

No additional style/attribute/flag calls are needed besides setOpacity and setColor. "Main.qml" must set transparency properly, like your QML example also does:

Rectangle {
    color: "transparent"
}

相关文章