Unable to connect signal to function inside main ()

I know that to use the Qt mechanism in the class of signals and slots inside the class, the class must include the Q_OBJECT macro, but I'm trying to use the signals and slots in main() without using any class.

Here is my code:

 #include <QApplication> #include <QWidget> #include <QTextEdit> #include <QtGui> void saveText(); int main(int argv, char **args) { QApplication app(argv, args); QTextEdit textEdit; QPushButton saveButton("Save!"); QPushButton exitButton("Exit!"); QObject::connect(&exitButton,SIGNAL(clicked()),qApp,SLOT(quit())); QObject::connect(&saveButton,SIGNAL(clicked()),qApp,SLOT(saveText())); QVBoxLayout vlyt; vlyt.addWidget(&textEdit); vlyt.addWidget(&exitButton); vlyt.addWidget(&saveButton); QWidget mainWindow; mainWindow.setLayout(&vlyt); mainWindow.show(); return app.exec(); } void saveText() { exit(0); } 

Here is the window generated by the graphical interface:

GUI window

From the above code, the exit button is connected to quit() , which is a Qt function when it is pressed. The save button assigned to saveText() is configured to exit, but does not.

Please tell me where I made a mistake in understanding signals and slots in Qt.

+6
source share
3 answers

Qt4 ...

All classes that inherit from QObject or one of its subclasses (for example, QWidget) can contain signals and slots. 1

So, you cannot use slots placed outside of QObject children.

You can connect signals to slots that are in classes, where the derivative of QObject . Put your slot in a class that is in a separate .h / .cpp file:

 class MyClass : public QObject { Q_OBJECT ... public slots: void saveText(); }; 

According to Qt5: New signal slot syntax in Qt 5 . You can connect to these types of global functions. (Thanks to @thuga comments)

+7
source

I will just give an example here.

main.cpp:

 #include <QCoreApplication> #include <iostream> #include <QObject> #include "siggen.h" void handler(int val){ std::cout << "got signal: " << val << std::endl; } int main(int argc, char *argv[]) { SigGen siggen; QObject::connect(&siggen, &SigGen::sgAction, handler); siggen.action(); QCoreApplication a(argc, argv); std::cout << "main prog start" << std::endl; return a.exec(); } 

siggen.h:

 #ifndef SIGGEN_H #define SIGGEN_H #include <QObject> class SigGen : public QObject { Q_OBJECT public: explicit SigGen(QObject *parent = 0); void action(void); signals: void sgAction(int value); }; #endif // SIGGEN_H 

siggen.cpp:

 #include "siggen.h" SigGen::SigGen(QObject *parent) : QObject(parent) {} void SigGen::action() { emit sgAction(42); } 
+1
source
 connect(&saveButton, &QPushButton::clicked, [](){saveText();}); // qt5.9.6 
0
source

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


All Articles