可以创建一个包含小部件并添加一个带有背景颜色属性和 alpha 属性的 QSS 样式。然后将布局添加到包含小部件以组织嵌套小部件的布局。我使用这种技术来实现透明效果,同时保持嵌套控件的不透明度。这是一些示例代码:
setAttribute(Qt::WA_NoSystemBackground, true);
// set the parent widget's background to translucent
setAttribute(Qt::WA_TranslucentBackground, true);
setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
// create a display widget for displaying child widgets
QWidget* displayWidget = new QWidget;
displayWidget->setGeometry(0, 0, this->width(), this->height());
displayWidget->setStyleSheet(".QWidget { background-color: rgba(0, 0, 0, 75%); border-width: 1px; border-style: solid; border-radius: 5px; border-color: #555555; } .QWidget:hover { background-color: rgba(68, 68, 68, 75%); border-width: 2px; border-style: solid; border-radius: 10px; border-color: #ffffff; }");
QLabel* icon = new QLabel;
icon->setPixmap(pixmapIcon);
icon->setMaximumSize(32, 32);
QLabel* header = new QLabel;
header->setMaximumSize(225, 50);
header->setWordWrap(true);
header->setText(headerText);
header->setStyleSheet("QLabel { color: #ffffff; font-weight: bold; font-size: 12px; }");
QLabel* message = new QLabel;
message->setMaximumSize(225, 100);
message->setWordWrap(true);
message->setText(messageText);
message->setStyleSheet("QLabel { color: #ffffff; font-size: 10px; }");
QHBoxLayout* displayMainLayout = new QHBoxLayout;
displayMainLayout->addWidget(icon);
QVBoxLayout* vl = new QVBoxLayout;
vl->addWidget(header);
vl->addWidget(message);
displayMainLayout->addLayout(vl);
displayWidget->setLayout(displayMainLayout);
QHBoxLayout* containerLayout = new QHBoxLayout;
containerLayout->addWidget(displayWidget);
setLayout(containerLayout);
show();
此代码直接取自我的 Qt Tray Notification Manager 项目。您可以在此处查看完整代码以获取一些上下文:https ://github.com/pcmantinker/Tray-Notification-System
请注意,如果您熟悉 CSS,则 QSS 非常相似。如果您想以某种方式设置所有 QWidget 的样式,您将使用 QWidget 选择器。但是,如果您只想设置特定 QWidget 的样式,请使用 .QWidget 选择器。为所有 QWidget 设置样式将使每个可见的 QWidget 继承相同的属性,因为每个 UI 元素都派生自 QWidget。在构建样式时请记住这一点。这是对 QSS 的参考:http: //qt-project.org/doc/qt-4.8/stylesheet.html
以下是它外观的一些示例图像:
Windows 7

Mac OS X Lion

Ubuntu

我希望这会有所帮助。如果您有任何问题,请告诉我。