【发布时间】:2014-03-21 09:26:02
【问题描述】:
我一直在寻找如何使我的 QtQuick 2.0 应用程序的背景透明。 我发现的大多数答案都使用 QtDeclarative,它适用于 QtQuick 1.0,但不适用于版本 2。
最后我找到了我将发布的答案,但我想知道是否有更好/更简单/更小的方法来完成这项任务。
注意*
我想让窗口的背景透明。 有些人建议 setOpacity 但这会使所有 qml 元素透明。
【问题讨论】:
我一直在寻找如何使我的 QtQuick 2.0 应用程序的背景透明。 我发现的大多数答案都使用 QtDeclarative,它适用于 QtQuick 1.0,但不适用于版本 2。
最后我找到了我将发布的答案,但我想知道是否有更好/更简单/更小的方法来完成这项任务。
注意*
我想让窗口的背景透明。 有些人建议 setOpacity 但这会使所有 qml 元素透明。
【问题讨论】:
我在 billouparis 的这篇帖子 http://qt-project.org/forums/viewthread/18984/#106629 中找到了解决方案。他使用由 QtCreator 生成的主应用程序模板,非常方便。 注意:我对原代码做了一点改动,使其更小。
#include <QtGui/QGuiApplication>
#include "qtquick2applicationviewer.h"
#include <QSurface>
#include <QSurfaceFormat>
#include <QDebug>
int main(int argc, char *argv[])
{
QGuiApplication app(argc, argv);
QtQuick2ApplicationViewer viewer;
// Make Background Transparent Start
viewer.setSurfaceType(QSurface::OpenGLSurface);
QSurfaceFormat format;
format.setAlphaBufferSize(8);
format.setRenderableType(QSurfaceFormat::OpenGL);
viewer.setFormat(format);
viewer.setColor(QColor(Qt::transparent));
viewer.setClearBeforeRendering(true);
// Make Background Transparent Stop
viewer.setMainQmlFile(QStringLiteral("qml/myProject/main.qml"));
viewer.showExpanded();
return app.exec();
}
还要确保根 qml 元素具有 alpha 颜色 (Qt.rgba)
【讨论】:
这里是一个在纯 qml 中获得无框透明窗口的示例
import QtQuick 2.2
import QtQuick.Window 2.0
import QtQuick.Controls 1.1
import QtQuick.Controls.Styles 1.1
ApplicationWindow {
id: backlight
flags: Qt.FramelessWindowHint
visible: true
title: qsTr("backlight")
width: 500
height: 50
x: (Screen.width - width) / 2
y: (Screen.height - height) / 2
color: "transparent"
property real slideValue
signal onSlide(real value)
Rectangle {
anchors.centerIn: parent
width: parent.width
height: 50
color: "transparent"
Rectangle {
anchors.fill: parent
radius: 25
opacity: 0.3
color: "gray"
}
Slider {
anchors.centerIn: parent
width: backlight.width - 16
height: backlight.height
value: backlight.slideValue
focus: true
onValueChanged: backlight.onSlide(value)
Keys.onSpacePressed: Qt.quit()
Keys.onEscapePressed: Qt.quit()
style: SliderStyle {
groove: Rectangle {
implicitHeight: 8
radius: 4
color: "gray"
}
handle: Rectangle {
anchors.centerIn: parent
color: control.pressed ? "white" : "lightgray"
border.color: "gray"
border.width: 2
width: 34
height: 34
radius: 17
}
}
}
}
}
【讨论】:
试试这个
import QtQuick 2.2
import QtQuick.Window 2.0
Window {
id: backlight
visible: true
title: qsTr("backlight")
width: 500
height: 50
x: (Screen.width - width) / 2
y: (Screen.height - height) / 2
color: "transparent"
}
【讨论】: