QT conncet示例
时间: 2023-09-23 12:04:43 浏览: 58
以下是一个简单的示例,演示如何使用Qt的connect函数连接两个QObject对象的信号和槽:
假设我们有两个QObject对象:sender和receiver。sender对象发出一个名为valueChanged的信号,并且receiver对象有一个名为updateValue的槽,该槽将接收sender对象的信号并更新其值。
```cpp
class Sender : public QObject
{
Q_OBJECT
public:
Sender(QObject* parent = nullptr) : QObject(parent), value(0) {}
signals:
void valueChanged(int newValue);
public slots:
void incrementValue() { ++value; emit valueChanged(value); }
private:
int value;
};
class Receiver : public QObject
{
Q_OBJECT
public:
Receiver(QObject* parent = nullptr) : QObject(parent), value(0) {}
public slots:
void updateValue(int newValue) { value = newValue; }
private:
int value;
};
```
现在我们可以使用connect函数将sender对象的valueChanged信号连接到receiver对象的updateValue槽:
```cpp
Sender* sender = new Sender();
Receiver* receiver = new Receiver();
QObject::connect(sender, &Sender::valueChanged, receiver, &Receiver::updateValue);
```
现在,当sender对象的valueChanged信号被发射时,receiver对象的updateValue槽将被调用,并将sender的新值传递给它。
阅读全文