对对象每次执行一次connect的操作,都会增加一个信号槽连接
如果我们想断开某个对象的所有信号槽,调用对象的disconnect()方法
如果想断开某一个信号槽,在connect时将返回的对象保存一下,然后调用QObject的disconnect()就可以了,如下面的代码:
dialog.cpp文件
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 |
#include "dialog.h" #include "ui_dialog.h" Dialog::Dialog(QWidget *parent) : QDialog(parent), ui(new Ui::Dialog) { ui->setupUi(this); } Dialog::~Dialog() { delete ui; } void Dialog::on_pushButton_2_clicked() { Connection1 = connect(ui->btnTest, SIGNAL(clicked(bool)), this, SLOT(connectFunc1(bool))); } void Dialog::on_pushButton_3_clicked() { connect(ui->btnTest, SIGNAL(clicked(bool)), this, SLOT(connectFunc2(bool))); } void Dialog::connectFunc1(bool b) { qDebug() << "connectFunc1"; } void Dialog::connectFunc2(bool b) { qDebug() << "connectFunc2"; } void Dialog::on_pushButton_clicked() { // 断开所有的connect ui->btnTest->disconnect(); } void Dialog::on_pushButton_4_clicked() { // 只断开其中的某个connect disconnect(Connection1); } |
dialog.h头文件
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
#ifndef DIALOG_H #define DIALOG_H #include <QDialog> #include <QMetaObject> #include <QDebug> namespace Ui { class Dialog; } class Dialog : public QDialog { Q_OBJECT public: explicit Dialog(QWidget *parent = 0); ~Dialog(); private slots: void on_pushButton_2_clicked(); void on_pushButton_3_clicked(); void connectFunc1(bool b); void connectFunc2(bool b); void on_pushButton_clicked(); void on_pushButton_4_clicked(); private: Ui::Dialog *ui; QMetaObject::Connection Connection1; }; #endif // DIALOG_H |
界面图片: