• 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. 通过这种方式,可以确保信号和槽正确匹配,即使它们有相同的名字但参数不同。

  • 相关阅读:
    300道SpringCloud面试题2022(面试题及答案)
    【前端学习 -Vue (7) Vue2.x组件通信有哪些方式?】
    ChatGPT的发展,是否会有越来越多的人失业?
    Shell 运算符及语法结构
    Linux CentOS7 lrzsz工具
    SpringBoot中xml映射文件
    源码转换器 Tangible:Source Code Converters 23.9
    Retrofit网络加载库二次封装支持RxJava与Flow-HttpUtils
    vue3+vite项目配置ESlint、pritter插件
    【C语言】字符函数和字符串函数
  • 原文地址:https://blog.csdn.net/qq_42964109/article/details/139397844