参数传递:
(1)全局传参
在一个类中进行参数传递,可以通过成员变量等方式
用槽函数实现:点击按钮,按钮上显示当前按钮的点击次数。
代码示例:
dialog.h
#ifndef DIALOG_H
#define DIALOG_H
#include <QDialog>
#include <QPushButton>
class Dialog : public QDialog
{
Q_OBJECT
public:
Dialog(QWidget *parent = 0);
~Dialog();
private:
int count; // 点击按钮的次数
QPushButton* btn;
private slots:
void setTextSlot(); // 自定义槽函数
};
#endif // DIALOG_H
dialog.cpp
#include "dialog.h"
Dialog::Dialog(QWidget *parent)
: QDialog(parent),count(0)
{
btn = new QPushButton("0",this);
btn->move(100,100);
// 点击按钮,设置当前点击的次数
// 连接信号槽
connect(btn,SIGNAL(clicked()),this,SLOT(setTextSlot()));
}
void Dialog::setTextSlot()
{
// 点击次数+1
count++;
// int → QString
QString text = QString::number(count);
// 设置当前点次数的字符串
btn->setText(text);
}
Dialog::~Dialog()
{
delete btn;
}
(2)信号槽传参
代码示例:
dialog.h
#ifndef DIALOG_H
#define DIALOG_H
#include <QDialog>
#include <QPushButton>
class Dialog : public QDialog
{
Q_OBJECT
public:
Dialog(QWidget *parent = 0);
~Dialog();
private:
int count; // 点击按钮的次数
QPushButton* btn;
private slots:
void mySlot1(); // 自定义槽函数1
void mySlot2(QString); // 自定义槽函数2
signals:
// 带参数的自定义信号,参数使用哑元
void mySignal(QString);
};
#endif // DIALOG_H
dialog.cpp
#include "dialog.h"
Dialog::Dialog(QWidget *parent)
: QDialog(parent),count(0)
{
btn = new QPushButton("0",this);
btn->move(100,100);
// 点击按钮,设置当前点击的次数
// 连接信号槽1
connect(btn,SIGNAL(clicked()),this,SLOT(mySlot1()));
// 连接信号槽2
connect(this,SIGNAL(mySignal(QString)),this,SLOT(mySlot2(QString)));
}
void Dialog::mySlot1()
{
// 点击次数+1
count++;
// int → QString
QString text = QString::number(count);
// 发射带参数的自定义信号
emit mySignal(text);
}
/**
* @brief Dialog::mySlot2
* @param text 信号发来的参数
*/
void Dialog::mySlot2(QString text)
{
// 更新按钮显示
btn->setText(text);
}
Dialog::~Dialog()
{
delete btn;
}
信号槽传参需要注意以下几点:
(1)理论上可以传递任意个数的参数
(2)信号的参数个数必须大于等于槽的参数个数
(3)参数类型必须一一匹配
信号的对应关系:
同一个信号可以连接到多个槽(一对多),多个信号也可以连接到同一个槽(多对一)。一对多的情况可以优化为一对一
代码示例:
dialog.h
#ifndef DIALOG_H
#define DIALOG_H
#include <QDialog>
#include <QPushButton>
#include <QDebug>
class Dialog : public QDialog
{
Q_OBJECT
public:
Dialog(QWidget *parent = 0);
~Dialog();
private:
QPushButton* btn1;
QPushButton* btn2;
private slots:
void mySlot1();
void mySlot2();
void mySlot3();
};
#endif // DIALOG_H
dialog.cpp
#include "dialog.h"
Dialog::Dialog(QWidget *parent)
: QDialog(parent)
{
btn1 = new QPushButton("1",this);
btn2 = new QPushButton("2",this);
btn1->move(50,50);
btn2->move(100,100);
// 点击btn1,一对多
connect(btn1,SIGNAL(clicked()),this,SLOT(mySlot1()));
connect(btn1,SIGNAL(clicked()),this,SLOT(mySlot2()));
// 可以优化为btn2的一对一
connect(btn2,SIGNAL(clicked()),this,SLOT(mySlot3()));
}
void Dialog::mySlot1()
{
qDebug() << "槽函数1";
}
void Dialog::mySlot2()
{
qDebug() << "槽函数2";
}
void Dialog::mySlot3()
{
// 槽函数也是成员函数,可以直接调用
mySlot1();
mySlot2();
}
Dialog::~Dialog()
{
delete btn1;
delete btn2;
}