Qt 5.9.2 版本,QObject::connect() 常用的形式为
connect(sender, signal, receiver, slot);
connect() 一般会使用前面四个参数,第一个是发出信号的对象,第二个是发送对象发出的信号,第三个是接收信号的对象,第四个是接收对象在接收到信号之后所需要调用的函数。
1.
QMetaObject::Connection connect(const QObject *sender, const char *signal, const QObject *receiver, const char *method, Qt::ConnectionType type = Qt::AutoConnection)
sender为发送控件名称,receiver为接受控件名称,signal为触发事件,method为接受函数。例子如下:
QLabel *label = new QLabel;
QScrollBar *scrollBar = new QScrollBar;
QObject::connect(scrollBar, SIGNAL(valueChanged(int)), label, SLOT(setNum(int)));
一个信号也可以关联另一个信号:
class MyWidget : public QWidget
{
Q_OBJECT
public:
MyWidget();
signals:
void buttonClicked();
private:
QPushButton *myButton;
};
MyWidget::MyWidget()
{
myButton = new QPushButton(this);
connect(myButton, SIGNAL(clicked()), this, SIGNAL(buttonClicked()));
}
2.
QMetaObject::Connection connect(const QObject *sender, PointerToMemberFunction signal, const QObject *receiver, PointerToMemberFunction method, Qt::ConnectionType type = Qt::AutoConnection)
signal 和 method 类型则是 PointerToMemberFunction是指向成员函数的指针。
QLabel *label = new QLabel;
QLineEdit *lineEdit = new QLineEdit;
QObject::connect(lineEdit, &QLineEdit::textChanged, label, &QLabel::setText);
3.
QMetaObject::Connection connect(const QObject *sender, PointerToMemberFunction signal, Functor functor)
最后一个参数是 Functor 类型。这个类型可以接受 static 函数、全局函数以及 Lambda 表达式。
void someFunction();
QPushButton *button = new QPushButton;
QObject::connect(button, &QPushButton::clicked, someFunction);
4.
QMetaObject::Connection connect(const QObject *sender, PointerToMemberFunction signal, const QObject *context, Functor functor, Qt::ConnectionType type = Qt::AutoConnection)
例:
void someFunction();
QPushButton *button = new QPushButton;
QObject::connect(button, &QPushButton::clicked, this, someFunction, Qt::QueuedConnection);
信号槽要求信号和槽的参数一致,所谓一致,是参数类型一致。如果不一致,允许的情况是,槽函数的参数可以比信号的少。
槽函数存在的那些参数的顺序必须和信号的前面几个一致起来。