我试图将 Qt 插槽成员函数传递给静态函数并收到编译器错误。我认为因为参数类型
slotfunction
是错误的。
这是我的问题的一个非常简短的代码示例:
typedef void (MainWindow::*slotfunction)();
QAction* AddAction(QMenu* menu
, QString name
, QObject* receiver
, slotfunction slotFkt
) {
QAction* action = new QAction(name, receiver);
QObject::connect(action, &QAction::triggered, receiver, slotFkt);
menu->addAction(action);
return action;
}
MainWindow::MainWindow(QWidget* parent)
: QMainWindow(parent) {
QMenu* fileMenu = menuBar()->addMenu(tr("File"));
AddAction(fileMenu, tr("New"), this, &MainWindow::onFileNew);
}
错误是:
mainwindow.cpp(24): error C2665: 'QObject::connect': none of the 4 overloads could convert all the argument types
C:\Qt\5.15.2\msvc2015_64\include\QtCore/qobject.h(481): note: could be 'QMetaObject::Connection QObject::connect(const QObject *,const char *,const char *,Qt::ConnectionType) const'
C:\Qt\5.15.2\msvc2015_64\include\QtCore/qobject.h(225): note: or 'QMetaObject::Connection QObject::connect(const QObject *,const QMetaMethod &,const QObject *,const QMetaMethod &,Qt::ConnectionType)'
C:\Qt\5.15.2\msvc2015_64\include\QtCore/qobject.h(222): note: or 'QMetaObject::Connection QObject::connect(const QObject *,const char *,const QObject *,const char *,Qt::ConnectionType)'
C:\Qt\5.15.2\msvc2015_64\include\QtCore/qobject.h(242): note: or 'QMetaObject::Connection QObject::connect<void(__cdecl QAction::* )(bool),slotfunction>(const QAction *,Func1,const MainWindow *,Func2,Qt::ConnectionType)'
with
[
Func1=void (__cdecl QAction::* )(bool),
Func2=slotfunction
]
mainwindow.cpp(24): note: while trying to match the argument list '(QAction *, void (__cdecl QAction::* )(bool), QObject *, slotfunction)'
根据G.M.的建议,解决方案如下:
QAction* AddAction(QMenu* menu
, QString name
, QString tooltip
, QObject* receiver
, std::function<void()> slotFkt
) {
QAction* action = new QAction(name, receiver);
action->setToolTip(tooltip);
QObject::connect(action, &QAction::triggered, receiver, slotFkt);
menu->addAction(action);
return action;
}
MainWindow::MainWindow(QWidget* parent) {
QMenu* menu = menuBar()->addMenu(tr("File"));
AddAction(menu, tr("New"), tr("Create a new file"), this, [&]() {onFileNew();});
}
slots
void MainWindow::onFileNew() {
}