1

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?

eyllanesc
  • 235,170
  • 19
  • 170
  • 241
Kamerton
  • 75
  • 7
  • As a general rule, do not declare `QObject` derived classes in main.cpp or if possible in any cpp, this way you have to manually include the moc files. – dtech Aug 03 '17 at 10:29

3 Answers3

2

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.
eyllanesc
  • 235,170
  • 19
  • 170
  • 241
1

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.

Nikolai Shalakin
  • 1,349
  • 2
  • 13
  • 25
0

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

M0rk
  • 56
  • 1