当你遇到信号或槽函数有重载时,需要使用 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
- #include
- #include
-
- // 类定义如上
-
- 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)。
- 通过这种方式,可以确保信号和槽正确匹配,即使它们有相同的名字但参数不同。