Z Mars Z Mars - 24 days ago 10
C++ Question

QT C++ - Signals and Slots: "No such slot QLabel..." even the SLOT function is existing in my class

So I am trying to learn Qt Framework with C++. I am in the middle of understanding signals and slots but I am having a hard time creating a customized slot. So as I follow some tutorials, my program ended up with the following error:


QObject::connect: No such slot QLabel::updateMessage() in main.cpp:28


Where updateMessage() is declared as a public slot inside my Test class

The following are some snippets from my code:

Test.h

class Test : public QObject
{
Q_OBJECT
public:
Test(void);
~Test(void);
void setMessage(char *tMsg);
char* getMessage();

QWidget *window;
QGridLayout *layout;
QLabel *lblMsg;
QPushButton *btnShow;


public slots:
void updateMessage();

private:
char msg[80];
QString str;

};


main.cpp

int main(int argc, char *argv[])
{
QApplication app(argc, argv);
Test t;
t.window->setWindowTitle("Testing Qt");
t.window->setLayout(t.layout);
t.window->show();
return app.exec();
}

Test::Test(void)
{
window = new QWidget;
lblMsg = new QLabel;
btnShow = new QPushButton("Show message");

connect(btnShow,SIGNAL(clicked()),lblMsg,SLOT(updateMessage()));
layout = new QGridLayout;
layout->addWidget(lblMsg);
layout->addWidget(btnShow);

char str1[] = "Hello, Qt World!";
setMessage(str1);
}


Test::~Test(void)
{

}

void Test::setMessage(char *tMsg)
{
memcpy(msg, tMsg, sizeof(msg));
}

char* Test::getMessage()
{
return msg;
}

void Test::updateMessage()
{
string strMsg(getMessage());
QString qstr = QString::fromStdString(strMsg);
lblMsg->setText(qstr);
delete msg;
}


HelloQtWorld.pro

######################################################################
# Automatically generated by qmake (3.0) Tue Nov 15 00:30:22 2016
######################################################################

TEMPLATE = app
TARGET = HelloQtWorld
INCLUDEPATH += .

# Input
HEADERS += stdafx.h Test.h
SOURCES += anotherClass.cpp \
main.cpp \
stdafx.cpp \
GeneratedFiles/qrc_helloqtworld.cpp
RESOURCES += helloqtworld.qrc


Can also someone try to explain for me how Signals and Slots work? Thank you in advance. :)

Answer

The problem is in this line:

connect(btnShow,SIGNAL(clicked()),lblMsg,SLOT(updateMessage()));

You are connecting with slot of QLabel instead of slot of your class.

This should be changed to

connect(btnShow,SIGNAL(clicked()),this,SLOT(updateMessage()));

You can find introduction into signals and slots in StackOverflow docs:

Signals and Slots

Pay attention at new Qt 5 syntax for signals and slots.