最近初学qt,有一个练习作业:创建一个按钮,当点击按钮时,弹出新窗口,并且按钮文字由“open“变为“close”。
1.Widget.h文件
#pragma once
#include <QtWidgets/QWidget>
#include "ui_Widget.h"
class Widget : public QWidget
{
Q_OBJECT
public:
Widget(QWidget *parent = Q_NULLPTR);
private:
Ui::WidgetClass ui;
QWidget* w1 = new QWidget();
bool flag = 0;
void showWindow();
};
- Widget.cpp文件
#include "Widget.h"
#include<QpushButton>
Widget::Widget(QWidget *parent)
: QWidget(parent)
{
ui.setupUi(this);
this->resize(600,400);
//创建按钮
QPushButton* btn1 = new QPushButton("open", this);
btn4->move(300, 200);
connect(btn1, &QPushButton::clicked, this, &Widget::showWindow);
connect(btn1, &QPushButton::clicked, this, [=]() {btn4->setText("Close"); });
}
void Widget::showWindow()
{
if (flag == false)
{
w1->show();
flag = 1;
}
else
{
w1->close();
flag = 0;
}
}