最近在设计一个测试平台,为菜单栏创建动作的时候,看到有 func1 slot 这个参数,随着好奇,通过度娘和实践,成功在QT中调用了它(仿函数)
打开QMenu的帮助文档,看到有以下十个原型:
QAction *QMenu::addAction(const QString &text)
QAction *QMenu::addAction(const QIcon &icon, const QString &text)
QAction *QMenu::addAction(const QString &text, const QObject *receiver, const char *member, const QKeySequence &shortcut = 0)
QAction *QMenu::addAction(const QIcon &icon, const QString &text, const QObject *receiver, const char *member, const QKeySequence &shortcut = 0)
QAction *QMenu::addAction(const QString &text, const QObject *receiver, PointerToMemberFunction method, const QKeySequence &shortcut = 0)
QAction *QMenu::addAction(const QString &text, Functor functor, const QKeySequence &shortcut = 0)
QAction *QMenu::addAction(const QString &text, const QObject *context, Functor functor, const QKeySequence &shortcut = 0)
QAction *QMenu::addAction(const QIcon &icon, const QString &text, const QObject *receiver, PointerToMemberFunction method, const QKeySequence &shortcut = 0)
QAction *QMenu::addAction(const QIcon &icon, const QString &text, Functor functor, const QKeySequence &shortcut = 0)
QAction *QMenu::addAction(const QIcon &icon, const QString &text, const QObject *context, Functor functor, const QKeySequence &shortcut = 0)
我需要动作拥有这四个元素:图标、动作名称、实现函数、快捷键
那么第九个菜单栏添加动作的函数原型就能直接实现(在网上看了其他网友的设计,全是使用创建动作对象,再一个个属性添加,最后来个关联,代码实在是臃肿不堪)
#include <QMenu>
#include <QDebug>
#include <functional>
#include <string>
#define Unicode(a) QString::fromLocal8Bit(a)
typedef std::function<void()> OnMessage;
void fun() { qDebug()<<"HelloSunck"<<endl; }
OnSunck onsunck( &fun );
QMenu* fileMenu = new QMenu(this);
fileMenu = ui->menuBar->addMenu(Unicode("文件(&F)"));
fileMenu->addAction(QIcon(":/image/res/new.png"),
Unicode("新建文档或工程(&N)"),
onsunck, QKeySequence::New);
参考blog:
std::function的用法
c++仿函数 functor
New Signal Slot Syntax
请教一下Qt里面的std::function的使用