qt – opacity in qml for Item and Rectangle

Question:

Simple qml example:

import QtQuick 2.0

Item {
    width: 800; height: 800

    Rectangle {
        width: 200; height: 200
        color: "red"

        Drag.active: dragArea.drag.active

        MouseArea {
            id: dragArea
            anchors.fill: parent

            drag.target: parent
        }
    }
}

And the main.cpp file:

   QGuiApplication app(argc, argv);

   QtQuick2ApplicationViewer viewer;
   viewer.setMainQmlFile(QStringLiteral("qml/ex6/main.qml"));
   viewer.showExpanded();

   return app.exec();

Tell me how to make Item transparent? If I do this:

viewer.setOpacity(0.0);

then the Rectangle also becomes transparent.

If I do opacity:0 in qml, then the Rectangle becomes transparent, and the transparency of Item does not change.

I need to be able to drag the Rectangle across the monitor screen with the mouse.

Answer:

opacity affects child elements, so if you only need to change the opacity of the parent and not affect the child elements, then you need to use the color field:

import QtQuick 2.0

Item {
    width: 800; height: 800
    color: "transparent" // Полностью прозрачный

    // ИЛИ В формате ARGB - первый байт это прозрачность от 0 до FF
    color: "#800000FF"

    Rectangle {
        width: 200; height: 200
        color: "red"
        opacity : 1.0

        // ...
    }
}
Scroll to Top