QT学习第一次作业
实现按钮Open/Close窗口
- 效果
步骤1: 刚运行会弹出下面👇窗口
步骤2: 点击Open按钮后
步骤3: 点击Close回到步骤1界面,此后可循环
- 代码
1. main.cpp
#include "widget.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
Widget w2;
Widget w(&w2);
w.show();
return a.exec();
}
2. widget.h
#ifndef WIDGET_H
#define WIDGET_H
#include <QWidget>
#include <QPushButton>
class Widget : public QWidget
{
Q_OBJECT
public:
Widget();
Widget(Widget *w2);
~Widget();
void Open();
void Close();
public:
Widget *w2;
QPushButton *button;
};
#endif // WIDGET_H
3. widget.cpp
#include "widget.h"
#include "qpushbutton.h"
#include "QDebug"
Widget::Widget()
{
return;
}
Widget::Widget(Widget *w2)
{
/*Button codes second type*/
QPushButton *button = new QPushButton();
button->setParent(this);
button->setText("Open");
button->move(350,250);
button->resize(100,50);
setWindowTitle("Demo"); //Set windows title
setFixedSize(800, 500); //Resize windows size
//----------------------------------------------------
this->w2 = w2;
this->button = button;
connect(button, &QPushButton::clicked, this, &Widget::Open);
}
Widget::~Widget()
{
}
void Widget::Open()
{
if(w2 == 0)
{
qDebug() << "error open";
return;
}
w2->move(20, 20);
w2->show();
this->button->setText("Close");
disconnect(this->button, &QPushButton::clicked, this, &Widget::Open);
connect(button, &QPushButton::clicked, this, &Widget::Close);
}
void Widget::Close()
{
if(w2 == 0)
{
qDebug() << "error close";
return;
}
w2->close();
this->button->setText("Open");
disconnect(this->button, &QPushButton::clicked, this, &Widget::Close);
connect(button, &QPushButton::clicked, this, &Widget::Open);
}