• QT5槽函数的重载问题


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

    1. 假设你有以下信号和槽:
    2. class DeviceOperationInterface : public QObject {
    3. Q_OBJECT
    4. signals:
    5. void ScaleX(bool _Scale);
    6. void ScaleX(int _Scale);//此处有重载
    7. };
    8. class UseQcustomplot : public QObject {
    9. Q_OBJECT
    10. public:
    11. static UseQcustomplot* getInstance() {
    12. static UseQcustomplot instance;
    13. return &instance;
    14. }
    15. public slots:
    16. void ScaleState(bool _Scale) {
    17. qDebug() << "Scale state (bool):" << _Scale;
    18. }
    19. void ScaleState(int _Scale) {
    20. qDebug() << "Scale state (int):" << _Scale;
    21. }
    22. };
    23. 你希望将 DeviceOperationInterface::ScaleX(bool) 信号连接到 UseQcustomplot::ScaleState(bool) 槽,以及将 DeviceOperationInterface::ScaleX(int) 信号连接到 UseQcustomplot::ScaleState(int) 槽,可以这样做:
    24. #include
    25. #include
    26. #include
    27. // 类定义如上
    28. int main(int argc, char *argv[])
    29. {
    30. QCoreApplication a(argc, argv);
    31. DeviceOperationInterface device;
    32. UseQcustomplot* customPlot = UseQcustomplot::getInstance();
    33. // 连接 ScaleX(bool) 信号到 ScaleState(bool) 槽
    34. QObject::connect(&device, QOverload<bool>::of(&DeviceOperationInterface::ScaleX),
    35. customPlot, &UseQcustomplot::ScaleState);
    36. // 连接 ScaleX(int) 信号到 ScaleState(int) 槽
    37. QObject::connect(&device, QOverload<int>::of(&DeviceOperationInterface::ScaleX),
    38. customPlot, QOverload<int>::of(&UseQcustomplot::ScaleState));
    39. // 测试信号
    40. emit device.ScaleX(true);
    41. emit device.ScaleX(42);
    42. return a.exec();
    43. }

    总结:

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

  • 相关阅读:
    Python 升级之路( Lv12 ) Pygame游戏开发基础
    C语言编程陷阱(二)
    【Linux】实时线程的优先级设置、调度和抢占
    Java项目源码SSM宿舍管理系统|寝室
    解读TLS协议、CA认证中的非对称加密
    [CAD二次开发]获取CAD内3D块参照的欧拉旋转交,Matrix3d矩阵转欧拉角。
    spring上传文件
    VsCode 常见的配置、常用好用插件
    AUTOSAR之网络管理API定义
    5.Mybatis 基础知识
  • 原文地址:https://blog.csdn.net/qq_42964109/article/details/139397844