1.概要
qt打开子窗体,如果设置了父对象是上层窗体,那么背景就是透明的。所以这里设置了一个白色背景。
2.内容
1.代码
#include <QApplication>
#include <QWidget>
#include <QDialog>
#include <QPushButton>
#include <QVBoxLayout>
#include <QLineEdit>
// 第二个透明窗口类
class TransparentWindow : public QWidget {
//class TransparentWindow : public QDialog {
public:
TransparentWindow(QWidget* parent = nullptr) : QWidget(parent) {
// 设置窗口属性(关键步骤)
setWindowFlags(Qt::FramelessWindowHint | Qt::WindowStaysOnTopHint); // 无边框 + 置顶
//setAttribute(Qt::WA_TranslucentBackground); // 启用透明背景
setStyleSheet("background-color: white;");
// 创建控件
QLineEdit* lineEdit1 = new QLineEdit(this);
QLineEdit* lineEdit2 = new QLineEdit(this);
QPushButton* btn = new QPushButton("提交", this);
// 布局管理
QVBoxLayout* layout = new QVBoxLayout(this);
layout->addWidget(lineEdit1);
layout->addWidget(lineEdit2);
layout->addWidget(btn);
// 设置窗口背景透明(可选样式表)
setStyleSheet("background: transparent;");
}
};
// 主窗口类
class MainWindow : public QWidget {
public:
MainWindow(QWidget* parent = nullptr) : QWidget(parent) {
QPushButton* btn = new QPushButton("打开透明窗口", this);
btn->move(200,200);
connect(btn, &QPushButton::clicked, this, &MainWindow::openTransparentWindow);
}
private slots:
void openTransparentWindow() {
TransparentWindow* window = new TransparentWindow(this);
window->resize(300, 200);
window->show();
//window->exec();
}
};
int main(int argc, char *argv[]) {
QApplication a(argc, argv);
MainWindow w;
w.resize(400, 300);
w.show();
return a.exec();
}