-1

I want to connect a pushbutton to a client::prework(). After trivial debugging I find that client::prework() is not being called (no portion of it is being executed), but the QObject::connect call returns true.

client.h

class client : public QObject
{
   //some declarations
   public slots:
   int prework();
};

client.cpp

void client::prework()
{
  //implementation

}

mainwindow.cpp

MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
   ui->setupUi(this);
   QWidget * wdg = new QWidget(this);
   QVBoxLayout *vlay = new QVBoxLayout(wdg);
   QPushButton *btn1 = new QPushButton("connectme");
   vlay->addWidget(btn1);
   client obj1;
   qDebug()<<"h";
   QObject::connect(btn1,SIGNAL(clicked()),&obj1,SLOT(prework()));
// obj1.prework();
 }
Mat
  • 202,337
  • 40
  • 393
  • 406
user3819404
  • 611
  • 6
  • 18
  • 4
    You have forgotten to add `Q_OBJECT` macro to the `client` declaration. See: http://stackoverflow.com/questions/1368584/qt-question-what-does-the-q-object-macro-do-why-do-all-qt-objects-need-this-ma – Nejat Feb 09 '15 at 06:42
  • You declare `prework` to return `int` in the header, but in your .cpp you define it as `void`. This is a typo, right? – thuga Feb 09 '15 at 08:01

1 Answers1

0
MainWindow::MainWindow(QWidget *parent) : ...
{
   ... 
   client obj1;
   ...
 } //  1

The line marked with // 1 is the line where obj1 gets destroyed. Local variables do not outlive the scope in which they were created. (And the QObject destructor ensures that signals are disconnected.)

You need to make that object a member of your main window class if you want it to outlive the constructor.

Mat
  • 202,337
  • 40
  • 393
  • 406
  • I made the object global and it worked but is there a way i don't have to make the object global? – user3819404 Feb 09 '15 at 06:53
  • What do you mean exactly by global? I indicated to make it a member of your class, that's not "global" by usual definitions. If you don't want it as a member of your class (directly or as a pointer), you need to store it elsewhere and be extremely careful that it outlives the instances of your class where it is used. – Mat Feb 09 '15 at 06:55
  • you mean `obj1` should be made a member of `client` class? – user3819404 Feb 09 '15 at 07:40
  • @user3819404 No, he means it should be a [member](http://en.wikipedia.org/wiki/Member_variable) of the `MainWindow` class. – thuga Feb 09 '15 at 07:59