Kamerton
Kamerton

Reputation: 75

Class inherited from QLabel, why custom slot is not called?

I made class inherited from QLabel. This class also have public slot, that should change label caption. I "call" this SLOT with clicked() SIGNAL of button. So nothing happened when I press the button.

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

class Label : public QLabel
{
public:
    Label(QString a) : QLabel(a){}

public slots:
    void change()
    {
        this->setNum(2);
    }
};

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

    QPushButton* button = new QPushButton("Button");
    Label* lbl = new Label("Label");

    button->show();
    lbl->show();

    QObject::connect(button, SIGNAL(clicked(bool)), lbl, SLOT(change()));

    return a.exec();
}

What should I do to change caption from slot?

Upvotes: 1

Views: 1471

Answers (3)

Nikolai Shalakin
Nikolai Shalakin

Reputation: 1484

Add Q_OBJECT after

class Label : public QLabel
{

and then you should

either place your Label class declaration to a .h file or write #include "main.moc" after main function declaration.

Upvotes: 1

eyllanesc
eyllanesc

Reputation: 243897

In order for the signals and slots to be recognized, the classes must use the Q_OBJECT macro in the private part.

Another thing to do is to include "main.moc", for more information on this point read this.

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

class Label : public QLabel
{
    Q_OBJECT
public:
    Label(const QString &text, QWidget *parent = Q_NULLPTR, Qt::WindowFlags f = Qt::WindowFlags()) :
     QLabel(text, parent, f){}

public slots:
    void change()
    {
        setNum(2);
    }
};

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

    QPushButton* button = new QPushButton("Button");
    Label* lbl = new Label("Label");

    button->show();
    lbl->show();

    QObject::connect(button, SIGNAL(clicked()), lbl, SLOT(change()));

    return a.exec();
}

#include "main.moc"

At the end of making these changes you must execute the following:

  1. Press clean all in the Build menu.
  2. then run qmake in the same menu.
  3. And you just compose your project.

Upvotes: 2

M0rk
M0rk

Reputation: 56

try to get the return value from your connect call an check it for true or false. Add Q_OBJECT Macro to the beginning of your derived class. Add some debug output to your slot like

qDebug()<<"This is my slot.";

Maybe this would help to get a little further.

Best regards

Upvotes: 0

Related Questions