Qt connect QAction to function with arguments
Asked Answered
C

2

5

In my Qt 5.6 program I need to connect QMenu Click (QAction) to function and provide some arguments. I can connect to function without arguments and it is working:

connect(MyAction, &QAction::triggered, function);

But, when I'm trying to add some arguments:

connect(MyAction, &QAction::triggered, function(arguments));

I'm getting an error:

C2664: "QMetaObject::Connection QObject::connect(const QObject *,const char *,const char ,Qt::ConnectionType) const": can't convery arg 2 from "void (__thiscall QAction:: )(bool)" to "const char *"

My example function:

void fuction(char x, char y, int z);

Thank you for any advice.

Clancy answered 19/4, 2016 at 17:44 Comment(0)
T
13

function(arguments) is a function call, you want to bind the function to the arguments and create new callable object instead, using std::bind:

connect(MyAction, &QAction::triggered, std::bind(function, arguments));

or you can use a lambda function:

connect(MyAction, &QAction::triggered, [this]()
{
    function(arguments);
});
Tours answered 19/4, 2016 at 17:49 Comment(0)
V
4

You want to use std::bind as in:

connect(MyAction, &QAction::triggered, std::bind(&function, x, y, z));
Vasomotor answered 19/4, 2016 at 17:48 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.