我正在尝试使用 lambda 函数将参数(对 QMainWindow 的引用)传递给槽回调方法。这是一个最小的例子:
#include "Start.hpp"
int main(int argc, char *argv[ ])
{
auto start = Start{argc, argv};
return start.start();
}
int Start::start() {
QApplication app(argc_, argv_);
QMainWindow window;
window.setWindowTitle("MainWindow");
QPushButton *button = new QPushButton("Start", &window);
QObject::connect(
button,
SIGNAL(released()),
this,
[this, &window](QMainWindow&){this->displayWidget(window);}
);
window.setCentralWidget(button);
window.resize(400, 300);
window.show();
return app.exec();
}
void Start::displayWidget(QMainWidow &window)
{
QMessageBox msgBox {&window};
msgBox.setText("The button was clicked.");
msgBox.exec();
}
头文件
Start.hpp
在哪里
#ifndef START_HPP
#define START_HPP
#include <QAction>
#include <QApplication>
#include <QPushButton>
#include <QDebug>
#include <QMainWindow>
#include <QObject>
class Start : public QObject {
Q_OBJECT
public:
Start(int argc, char* argv[]) : argc_{argc}, argv_{argv} {}
int start();
private:
int argc_;
char **argv_;
private slots:
void displayWidget(QMainWindow &window);
};
#endif
当使用 qmake 编译此程序时,我收到以下错误消息:
Start.cpp: In member function ‘int Start::start()’:
Start.cpp:14:21: error: no matching function for call to ‘Start::connect(QPushButton*&, const char*, Start*, Start::start()::<lambda(QMainWindow&)>)’
14 | QObject::connect(
您不能混合旧的(已被 C++ 类淘汰)和“新的”(自十多年前的 Qt 5 起)连接语法。连接到 lambda 仅适用于新语法。
此外,
released()
信号没有参数,因此 lambda 也不能有参数。
这应该是有效的:
QObject::connect(
button,
&QPushButton::released,
this,
[this, &window](){this->displayWidget(window);}
);