Qt signal with enumeration as parameter

I am trying to pass enum as a value to a slot in my program, but I am having some problems. In my header file, I created an enumeration:

Q_ENUMS(button_type); enum button_type {button_back, button_up, button_down, button_ok}; Q_DECLARE_METATYPE(button_type); 

And in my .cpp file, I'm trying to pass it to the slot:

 QObject::connect(buttons->ui.pushButton_back, SIGNAL(clicked()), this, SLOT(input_handler(button_back))); 

But when I compile the code, I get:

 Object::connect: No such slot main_application::input_handler(button_back) in main_application.cpp:44 Object::connect: (sender name: 'pushButton_back') Object::connect: (receiver name: 'main_applicationClass') 

It compiles and works fine unless I pass the input_handler argument.

I also read that I need to call qRegisterMetaType, but I can not understand that the syntax is correct. Here is what I tried:

 qRegisterMetaType<button_type>("button_type"); 

but I get this error:

 main_application.h:15:1: error: specializing member '::qRegisterMetaType<button_type>' requires 'template<>' syntax 

Can anyone shed some light on this for me?

Thanks!

Marlon

+1
source share
3 answers

The signal and slot must have the same parameters. You want to use QSignalMapper.

edit Here is an example from my application. It creates 10 menu actions, each of which is connected to one gotoHistoryPage slot, but each of them is called with a different int value.

 m_forwardMenu = new QMenu(); for(int i = 1; i<=10; i++) { QAction* action = m_forwardMenu->addAction(QString("%1").arg(i)); m_forwardActions.push_back(action); m_signalMapper->setMapping(action, i); connect(action, SIGNAL(triggered()), m_signalMapper, SLOT(map())); } ui.forwardButton->setMenu(m_forwardMenu); connect(m_signalMapper, SIGNAL(mapped(int)), this, SLOT(gotoHistoryPage(int))); 
+3
source

You pass a macro SLOT() value when it expects a type. More fundamentally, this does not make any sense, since what you are trying to achieve is to skip the slot constant. Why not just use button_back in the slot function directly?

You can define a slot that takes the value of button_type , but then you will need to connect it to a signal that passes it as a parameter.

What are you really trying to do?

+1
source
 Object::connect: No such slot main_application::input_handler(button_back) 

Of course there is, because the signature is main_application::input_handler(button_type) , and button_back is the value, not the type. And even you make the correct signature, you will not be able to connect this signal and slot due to a mismatch of their signature.

In addition, you can always use the QObject::sender() function to find out which button was clicked.

0
source

Source: https://habr.com/ru/post/1443867/


All Articles