Widget::Widget(QWidget *parent)
: QWidget(parent)
{
this->resize(500, 300);
QPushButton *btn = new QPushButton;
btn->setParent(this);
btn->setText(QString("确定"));
btn->move(100, 100);
btn->resize(70, 30);
// this->setFixedSize(600, 400);
setWindowTitle(QString("Qt的第一个窗口"));
MyButton *myBtn = new MyButton;
myBtn->setParent(this);
myBtn->move(200, 100);
myBtn->setText("取消");
myBtn->resize(70, 30);
connect(myBtn, &QPushButton::clicked, this, &QWidget::close);
}
connect(信号的发送者,信号,信号的接受者,槽函数)
connect(btn, &QPushButton::clicked, this, &QWidget::close)
1. 自定义信号
2. 自定义槽函数
3. 信号触发槽函数方式
emit obj->signal(); // obj为拥有signal信号的对象, signal可以为任意名称
注意: 当自定义信号和槽出现重载时, 原先写法失效,因为执行的函数地址不明确
解决方法是: 利用函数指针来明确指明特定函数地址
Widget::Widget(QWidget *parent)
: QWidget(parent)
{
pTeacher = new Teacher(this);
pStudent = new Student(this);
void (Teacher:: *teacher_signal)(QString) = &Teacher::hungry;
void (Student:: *student_slot)(QString) = &Student::treat;
connect(pTeacher, teacher_signal, pStudent, student_slot);
// connect(pTeacher, &Teacher::hungry, pStudent, &Student::treat);
}
如果直接输出QString会出现字符串有双引号括起来的现象,可以通过str.toUtf8().data()来转换
Widget::Widget(QWidget *parent)
: QWidget(parent)
{
pTeacher = new Teacher(this);
pStudent = new Student(this);
// void (Teacher:: *teacher_signal)(QString) = &Teacher::hungry;
// void (Student:: *student_slot)(QString) = &Student::treat;
// connect(pTeacher, teacher_signal, pStudent, student_slot);
// connect(pTeacher, &Teacher::hungry, pStudent, &Student::treat);
QPushButton *btn = new QPushButton("下课", this);
// 信号连接信号
void (Teacher::*t_has_param)() = &Teacher::hungry;
void (Student::*s_has_param)() = &Student::treat;
connect(btn, &QPushButton::clicked, pTeacher, t_has_param);
connect(pTeacher, t_has_param, pStudent, s_has_param);
this->resize(400, 200);
// 一个信号触发多个槽函数,这里btn触发了两次treat槽
connect(btn, &QPushButton::clicked, pStudent, s_has_param);
// 信号可以与槽函数断开, 多个信号也可以连接同一个槽函数
disconnect(btn, &QPushButton::clicked, pStudent, s_has_param);
// 信号的形参和槽函数的形参类型必须一一对应, 数量可以不一一对应, 信号形参数目可以多于槽函数
}
Qt4版本的信号与槽的写法:
//Qt4版本connect写法
connect(pTeacher, SIGNAL(hungry(QString)), pStudent, SLOT(treat(QString)));
(完)