gpt4 book ai didi

c++ - QT C++ - 信号和槽 : "No such slot QLabel..." even the SLOT function is existing in my class

转载 作者:行者123 更新时间:2023-11-30 01:41:54 27 4
gpt4 key购买 nike

所以我正在尝试使用 C++ 学习 Qt Framework。我正在了解信号​​和插槽,但我很难创建自定义插槽。因此,当我按照一些教程进行操作时,我的程序出现了以下错误:

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

updateMessage() 在我的Test 类中被声明为一个public slot

以下是我的代码的一些片段:

测试.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

也有人可以尝试为我解释信号和槽是如何工作的吗?先感谢您。 :)

最佳答案

问题出在这一行:

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

您正在连接 QLabel 的槽,而不是您类(class)的槽。

这里应该改成

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

注意信号和槽的新 Qt 5 语法。

关于c++ - QT C++ - 信号和槽 : "No such slot QLabel..." even the SLOT function is existing in my class,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40593794/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com