Qt C++ connect QPushButton click

user2920222 picture user2920222 · May 24, 2014 · Viewed 13.1k times · Source

I have just started developing using QtGUI and I have checked out some tutorials and documentation, and by what I've read this should work.

#define CONNECT QObject::connect

void test();
QPushButton *lpTestBtn;
int main(int argc, char *argv[])
{
   QApplication a(argc, argv);
   QtProject w;
   w.show();

   lpTestBtn = w.window()->findChild<QPushButton*>("TestBtn");
   CONNECT(lpTestBtn, SIGNAL(clicked()),qApp,SLOT(test()));

   return a.exec();
}

void test()
{
    lpTestBtn->setText("Hi");
}

But test() never gets called. Also, lpTestBtn is not null and is found correctly.

I have tried the following changes

CONNECT(lpTestBtn, SIGNAL(clicked()),qApp->activeWindow(),SLOT(test()));

CONNECT(lpTestBtn, SIGNAL(clicked()),w.window(),SLOT(test()));

I know I can just do QtProject::on_TestBtn_clicked(); but I'd like to get it working using CONNECT,SIGNAL and SLOT.

Answer

Michael Kohne picture Michael Kohne · May 24, 2014

1) QApplication doesn't have a test() slot in it. You need to make your own class, inheriting QApplication, and give that class a test() slot. What you've done is create a regular function, which won't help.

2) You didn't check the return value of connect, which means you didn't see that it was giving you an error, which would probably have given you some clues.