信号与槽
在Qt中,用户与控件的交互过程称为事件。例如点击按钮、关闭/刷新窗口。每个事件都会发出一个信号,例如点击按钮会发出按钮被点击的信号。
Qt Ctreator自动生成信号和槽
可视化实现点击按钮关闭功能
在使用信号和槽前我们需要了解一下,其在Qt中特有的消息传输机制
信号与槽的消息传输机制
例子:按钮被按下信号产生,按钮发送”按钮被按下信号“。 窗口接收信号,调用关联的槽函数,槽函数关闭窗口。
connect函数
QMetaObject::Connection QObject::connect(
const QObject *sender, //谁发送了信号
const char *signal, //发送了什么信号
const QObject *receiver, //谁接收了信号
const char *method, //怎么处理
Qt::ConnectionType type = Qt::AutoConnection)//关联类型,通常不需要设定
到处我们就实现了,点击按钮关闭窗口的动作
纯代码实现
代码
//Widget.h
#ifndef WIDGET_H
#define WIDGET_H
#include <QWidget>
#include <QPushButton>
class Widget : public QWidget
{
Q_OBJECT
public slots:
void CloseWidget(); //槽函数声明
private:
QPushButton* _but; //成员变量
public:
Widget(QWidget *parent = nullptr);
~Widget();
};
#endif // WIDGET_H
//Widget.cpp
#include "widget.h"
Widget::Widget(QWidget *parent)
: QWidget(parent)
{
_but = new QPushButton(QString("关闭"), this); //构建按钮对象,指定this父对象。
resize(800,600);//调整窗口大小
_but->move(350,300);//调整按钮位置
connect(_but, &QPushButton::clicked, this, &Widget::CloseWidget);//关联信号和槽
}
Widget::~Widget()
{
}
void Widget::CloseWidget()
{
this->close();
扩展
实现点击”打开“后按钮变为”返回“
void Widget::CloseWidget()
{
if(_but->text() == QString("打开"))//text()返回QString
{
_but->setText(QString("返回"));//设置按钮文本
}
else
{
_but->setText(QString("打开"));
}
}
一个有趣的程序, 可以玩玩
/Widget.h
#ifndef WIDGET_H
#define WIDGET_H
#include <QWidget>
#include <QString>
#include <QPushButton>
QT_BEGIN_NAMESPACE
namespace Ui { class Widget; }
QT_END_NAMESPACE
class Widget : public QWidget
{
Q_OBJECT
public:
Widget(QWidget *parent = nullptr);
~Widget();
void SetPosition();//位置调整函数
public slots:
void MySlots();
private:
QPushButton* btn;
int count;//点击次数
private:
Ui::Widget *ui;
};
#endif // WIDGET_H
Widget.cpp
#include "widget.h"
#include "ui_widget.h"
#include <QTime>
#include <QDebug>
Widget::Widget(QWidget *parent)
: QWidget(parent)
, ui(new Ui::Widget)
{
ui->setupUi(this);
count = 0;
this->btn = new QPushButton(QString("别点我"),this);
resize(800, 600);
btn->move(350, 300);
connect(btn, &QPushButton::clicked, this, &Widget::MySlots);
}
Widget::~Widget()
{
delete ui;
}
void Widget::MySlots()
{
if(count >= 3 && count < 7)
{
btn->setText(QString("别点我!!"));
SetPosition();
}
else if(count >= 7 && count < 10)
{
btn->setText(QString("别!点!我!?"));
SetPosition();
}
else if(count == 10)
{
btn->setText(QString("不要点我了!!!!!!!"));
btn->setFixedSize(400,400); //调整按钮大小
btn->move(200,100);
}
else if(count > 10)
{
this->close();
}
count++;
qDebug() << count; //qDebug 日志输出宏
}
void Widget::SetPosition()
{
qsrand(QTime::currentTime().msec()); //设置随机数种子,相同种子生成的随机数相同。这里用的是当前时间的毫秒来作为种子
int x = qrand()%500; //获取0~500的随机数作为x坐标
int y = qrand()%500; //获取0~500的随机数作为y坐标
btn->move(x,y);
}