Donald Duck Donald Duck - 6 months ago 24
C++ Question

Put arguments in slots in Qt

I've made a class named MyWindow which inherits from QWidget to create a window. Here is the content of mywindow.h:

class MyWindow: public QWidget{
MyWindow(QString title,QString icon,int w = 600,int h = 400);
int getWidth() const;
int getHeight() const;
public slots:
void openDialogBox(QString title,QString message);
int m_width;
int m_height;

There is a openDialogBox slot which takes the title and the message of the dialog box as arguments.

I've made a menu bar which basically looks like this:

MyWindow myWindow("Example window",QCoreApplication::applicationDirPath() + "/icon.png");
QMenuBar menuBar(&myWindow);
QMenu *fileMenu = new QMenu("&File");
QAction *fileMenu_open = fileMenu->addAction("&Open");

In the last line, I would like to send arguments to the slot
. I tried to do:

MyWindow::connect(fileMenu_open,&QAction::triggered,&myWindow,&MyWindow::openDialogBox("Title","Hello, this is a message"));

but it didn't work (I don't need you to explain why it didn't work, I already know why). How to do this properly so that it works?


Since you are using the New Signal Slot Syntax, I would suggest using a c++11 lambda instead of a slot, and call the desired function inside your slot, here is how your connect call would look like:

QObject::connect(fileMenu_open, &QAction::triggered, &myWindow, [&myWindow](){
    myWindow.openDialogBox("Title","Hello, this is a message");

Note that openDialogBox is not required to be a slot this way, it can be any normal function.

If your compiler does not support C++11 lambda expression, you might have to declare a slot that does not take any argument, and connect to that slot. And inside that slot call your function with the desired arguments. . .