Bessa
Bessa

Reputation: 117

Implement slots in derived class - qt4/c++

I'm trying to make the example Communicate (which can be found at the web-tutorial First program in qt4), but in a different way: the buttons 'plus' and 'minus' are not built at the constructor, but by calling a member function of the child class, that inherits the QWidget class attributes:

myWidget class from mywidget.h

#ifndef _MYWIDGET_H
#define _MYWIDGET_H
#include <QApplication>
#include <QDesktopWidget>
#include <QWidget>
#include <QIcon>
#include <QPushButton>
#include <QLabel>
class myWidget : public QWidget{

    public:
        myWidget(QWidget *parent = 0);

        void setPMButton(int,int,int,int,int,int);
    private:
        QLabel *label;
    private slots:
        void OnPlus();
        void OnMinus();   
};
#endif

Method's implementations from Mywidget.cpp

#include "mywidget.h"
myWidget::myWidget(QWidget *parent) : QWidget(parent){
    label = new QLabel("0", this);
    label->setGeometry(190, 80, 20, 30);
}
void myWidget::OnPlus(){
    int val = label->text().toInt();
    val++;
    label->setText(QString::number(val));
}
void myWidget::OnMinus(){
    int val = label->text().toInt();
    val--;
    label->setText(QString::number(val));
}
void myWidget::setPMButton(int x1, int y1, int x2, int y2, int w, int h){
    QPushButton *plus = new QPushButton("+", this);
    plus->setGeometry(x1, y1, w, h);

    QPushButton *minus = new QPushButton("-", this);
    minus->setGeometry(x2, y2, w, h);

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

And in the main file test.cpp, it is written:

#include "mywidget.h"
int main(int argc, char *argv[]){

    QApplication app(argc, argv);

        myWidget window;

        window.setPMButton(50,120,50,200,75,30);        
        window.show();

    return app.exec();
}

But once I run the application, it shows the window, but the buttons don't work. At the terminal it shows the message:

Object::connect: No such slot QWidget::OnPlus()
Object::connect: No such slot QWidget::OnMinus()

Is there any way to make this work?

Upvotes: 0

Views: 551

Answers (1)

dschulz
dschulz

Reputation: 4796

You forgot to add the Q_OBJECT macro.

#includes here
...

class myWidget : public QWidget{

Q_OBJECT   ///      <---- Here

public:
    myWidget(QWidget *parent = 0);

...
...

Upvotes: 1

Related Questions