01.01 QT信号和槽
1.思维导图
2.写1个widget窗口,窗口里面放1个按钮,按钮随便叫什么
创建2个widget对象
Widget w1,w2
w1.show()
w2不管
要求:点击 w1.btn,w1隐藏,w2显示
点击 w2.btn ,w2隐藏,w1 显示
程序代码:
#include <QApplication>
#include <QWidget>
#include <QPushButton>
#include <QVBoxLayout>
class Widget : public QWidget {
QPushButton* btn;
Widget* otherWindow; // 指向另一个窗口的指针
public:
Widget(const QString& buttonName, Widget* other = nullptr, QWidget* parent = nullptr);
void setOtherWindow(Widget* other) { otherWindow = other; }
private slots:
void onButtonClicked();
};
Widget::Widget(const QString& buttonName, Widget* other, QWidget* parent)
: QWidget(parent), otherWindow(other) {
// 创建按钮
btn = new QPushButton(buttonName, this);
// 设置布局
QVBoxLayout* layout = new QVBoxLayout(this);
layout->addWidget(btn);
setLayout(layout);
// 连接按钮的点击信号到槽函数
connect(btn, &QPushButton::clicked, this, &Widget::onButtonClicked);
}
void Widget::onButtonClicked() {
if (otherWindow) {
this->hide(); // 隐藏当前窗口
otherWindow->show(); // 显示另一个窗口
}
}
int main(int argc, char** argv) {
QApplication app(argc, argv); // QT应用程序的入口类
// 创建两个 Widget 对象
Widget w1("Hide Me (W1)");
Widget w2("Hide Me (W2)");
// 设置窗口标题
w1.setWindowTitle("Window 1");
w2.setWindowTitle("Window 2");
// 设置相互指向
w1.setOtherWindow(&w2);
w2.setOtherWindow(&w1);
// 显示 w1,w2不管
w1.show();
return app.exec(); // 执行QT应用程序的事件循环
}