Connecting a button to an arbitrary function

The attempt itself to write a program in Qt connecting a function with a button in Qt5.

#include <QApplication> #include <QtGui> #include <QPushButton> static void insert() { qDebug() << "pressed"; } int main(int argc,char *argv[]) { QApplication app(argc,argv); QPushButton *button=new QPushButton("button"); button->setGeometry(50,100,150,80); QObject::connect(button,&QPushButton::clicked,insert()); button->show(); } 

But I get errors like main.cc:23:39: error: in this context main.cc:23:55: error: misuse of void make expression: * [main.o] Error 1

Please, help...

+5
source share
2 answers

In Qt 5, you need to use the new qt system and the slot system . The connection will look like this:

 QObject::connect(button,&QPushButton::clicked,insert); <-- no parentheses. 

This has already been said, but you need to call app.exec(); to start processing the event loop. Otherwise, the connection will never start.

Also, if you are in release mode, you may not see qDebug() output

+8
source

* see below.

First of all, you cannot connect a signal to a function, you must connect it to a slot of a class, and an instance of this class must also be provided in QObject::connect .

So, the first thing to do is define a class with a slot:

 // file 'Ch' #ifndef __C_H__ #define __C_H__ #include <QtGui> class C : public QObject{ Q_OBJECT public slots: static void insert() { qDebug() << "pressed"; } }; #endif 

Note that this class must inherit from QObject and have the Q_OBJECT keyword inside it. You must put this class declaration in a *.h file (you cannot have Q_OBJECT in *.cpp files because Qt will not see it).

Now that you have a class with a slot, you can use QObject::connect , the correct way:

  QObject::connect(button, SIGNAL(clicked()), &c, SLOT(insert())); 

Please note that you must use SIGNAL() macros for signals and SLOT() macros for slots when connecting them.

So, the code in main.cpp should be as follows:

  #include "Ch" int main(int argc,char *argv[]) { QApplication app(argc,argv); QPushButton *button=new QPushButton("button"); button->setGeometry(50,100,150,80); C c; QObject::connect(button, SIGNAL(clicked()), &c, SLOT(insert())); button->show(); return app.exec(); } 

You see how I provide an instance of the receiver object ( &c ) of the connect() function, you must do this even if your function is static .

And finally, you must app.exec(); because otherwise your program will not have a message loop.

EDIT:

I skipped that the question was about Qt 5. For Qt 5.0, the answer is incorrect.

+2
source

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


All Articles