QT5槽函数的重载问题

当你遇到信号或槽函数有重载时,需要使用 QOverload 来明确指定连接的是哪个重载版本。下面是如何在 connect 函数中区分重载的示例。

假设你有以下信号和槽:

class DeviceOperationInterface : public QObject {
    Q_OBJECT
signals:
    void ScaleX(bool _Scale);
    void ScaleX(int _Scale);//此处有重载
};

class UseQcustomplot : public QObject {
    Q_OBJECT
public:
    static UseQcustomplot* getInstance() {
        static UseQcustomplot instance;
        return &instance;
    }
public slots:
    void ScaleState(bool _Scale) {
        qDebug() << "Scale state (bool):" << _Scale;
    }

    void ScaleState(int _Scale) {
        qDebug() << "Scale state (int):" << _Scale;
    }
};


你希望将 DeviceOperationInterface::ScaleX(bool) 信号连接到 UseQcustomplot::ScaleState(bool) 槽,以及将 DeviceOperationInterface::ScaleX(int) 信号连接到 UseQcustomplot::ScaleState(int) 槽,可以这样做:

#include <QCoreApplication>
#include <QDebug>
#include <QObject>

// 类定义如上

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    DeviceOperationInterface device;
    UseQcustomplot* customPlot = UseQcustomplot::getInstance();

    // 连接 ScaleX(bool) 信号到 ScaleState(bool) 槽
    QObject::connect(&device, QOverload<bool>::of(&DeviceOperationInterface::ScaleX),
                     customPlot, &UseQcustomplot::ScaleState);

    // 连接 ScaleX(int) 信号到 ScaleState(int) 槽
    QObject::connect(&device, QOverload<int>::of(&DeviceOperationInterface::ScaleX),
                     customPlot, QOverload<int>::of(&UseQcustomplot::ScaleState));

    // 测试信号
    emit device.ScaleX(true);
    emit device.ScaleX(42);

    return a.exec();
}

总结:

在这个示例中:

1.使用 QOverload<bool>::of(&DeviceOperationInterface::ScaleX) 明确指定连接的是 ScaleX(bool) 信号。
2.使用 QOverload<int>::of(&DeviceOperationInterface::ScaleX) 明确指定连接的是 ScaleX(int) 信号。
3.对于槽函数,如果槽函数也有重载,需要使用 QOverload 来指定正确的重载版本,如 QOverload<int>::of(&UseQcustomplot::ScaleState)。
通过这种方式,可以确保信号和槽正确匹配,即使它们有相同的名字但参数不同。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Gallagher_SF

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值