Question

I have written a program in Qt, it works fine, but clicking on push buttons does not work. When I use Q_OBJECT just after the class declaration, it gives me compilation errors.

Here is my code:

    #include <QApplication>
    #include <QPushButton>
    #include <QLabel>
    #include <QWidget>

    class Communicate : public QWidget
    {
     // Q_OBJECT

      public:
        Communicate(QWidget *parent = 0);

      private slots:
        void OnPlus();
        void OnMinus();

      private:
        QLabel *label;

    };

    Communicate::Communicate(QWidget *parent)
        : QWidget(parent)
    {
      QPushButton *plus = new QPushButton("+", this);
      plus->setGeometry(50, 40, 75, 30);

      QPushButton *minus = new QPushButton("-", this);
      minus->setGeometry(50, 100, 75, 30);

      label = new QLabel("0", this);
      label->setGeometry(190, 80, 20, 30);

      connect(plus, SIGNAL(clicked()), this, SLOT(OnPlus()));
      connect(minus, SIGNAL(clicked()), this, SLOT(OnMinus()));
    }

    void Communicate::OnPlus()
    {
      int val = label->text().toInt();
      val++;
      label->setText(QString::number(val));
    }

    void Communicate::OnMinus()
    {
      int val = label->text().toInt();
      val--;
      label->setText(QString::number(val));
    }

    int main(int argc, char *argv[])
    {
      QApplication app(argc, argv);

      Communicate window;

      window.setWindowTitle("Communicate");
      window.show();

      return app.exec();
    }
Was it helpful?

Solution 2

Use O_QBJECT macro and to correct the errors you get you can either:

1) Declare your QWidget/QObject derived class in it's own .h file and define it in it's own .cpp file.

2) include the .moc file generated by moc after your class definition in the .cpp you have (add something like #include "xxxx.moc")

LE: also you want to use layouts instead of use the setGeometry to place your widgets into a window, read more here

OTHER TIPS

You need to run files that contain the Q_OBJECT macro through moc, and compile and link it's output together with the rest of your applications. Depending on your buildsystem this happens automatically (qmake) or by adding one line or so (cmake)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top