-->

Transparent widget with QtQuick 2.0

2020-07-18 09:39发布

问题:

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();
    }
};

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); 

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();

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

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

now my questions:

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

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

回答1:

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

Create a view:

QQuickView view;
view.setOpacity(0.9999);
view.setColor( Qt::transparent );
view.setSource( QUrl::fromLocalFile( QLatin1String( "Main.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"
}