二、QT自定义信号
要点
- 一定要使用signals进行声明
- 在signals中进行声明后就可以不用实现此函数
- 信号的声明在申请类的头文件中进行
- 自定义信号可以有参数、可以重载
- 返回值为void
- 发送信号:emit + 信号名
举例
class Index : public QDialog
{
Q_OBJECT
public:
explicit Index(QWidget *parent = 0);
~Index();
signals:
//自定义信号
//调用方式:emit sig();
void sig();
public slots:
private slots:
private:
Ui::Index *ui;
};
此时如果需要使用此信号,还需要定义一个槽函数。此槽函数需要定义在public slots中,然后回到cpp中对此槽函数进行实现。
使用示例
申请信号的.h
class Index : public QDialog
{
Q_OBJECT
public:
explicit Index(QWidget *parent = 0);
~Index();
signals:
//自定义信号
//调用方式:emit sig();
void sig();
public slots:
void my_slot();
private slots:
private:
Ui::Index *ui;
};
申请信号的.cpp
Index::Index(QWidget *parent) :
QDialog(parent),
ui(new Ui::Index)
{
ui->setupUi(this);
//创建按键1
b1 = new QPushButton;
b1->setText("我是按键1");
b1->move(100,100);
connect(b1, &QPushButton::pressed, this, &Index::myslot);
}
void Index::my_slot()
{
emit sig();
}
信号使用对象的.h
#include "index.h"
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
void SlotForhide();
void SlotForshow();
private slots:
private:
Ui::MainWindow *ui;
//在此处添加子窗口对象 ** 非常重要 **
Index Inde;
};
信号使用对象的.cpp
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
//创建按键1
b1 = new QPushButton;
b1->setText("我是按键1");
b1->move(100,100);
//创建按键2
b2 = new QPushButton;
b2->setText("我是按键2");
b2->move(200,100);
//创建按键3
b3 = new QPushButton;
b3->setText("我是按键3");
b3->move(300,100);
//信号和槽连接函数:connect();
//四个参数:**不要忘记取地址**
//此处的pressed函数没有没有参数,所以定义的槽函数也没有参数
connect(b3, &QPushButton::pressed, this, &MainWidget::slotForhide);
connect(&Inde, &Index::sig, this, &MainWidget::slotForshow);
}
void MainWidget::SlotForhide()
{
hide();
Inde.show();//此处的对象与头文件中声明的Index Inde;对应
}
void MainWidget::SlotForshow()
{
show();
Inde.hide();//此处的对象与头文件中声明的Index Inde;对应
}