Qt4 连接按钮中单击的信号不会触发标签中的设置文本



应用程序运行正常,但clicked()信号没有触发标签的setText()。有什么提示吗?

#include <QApplication>
#include <QLabel>
#include <QPushButton>
#include <QHBoxLayout>
#include <QWidget>
#include <QObject>
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
QWidget *window = new QWidget;
QLabel *label = new QLabel("hello");
QPushButton *button = new QPushButton;
button->setText("change");
QObject::connect(button, SIGNAL(clicked()), label, SLOT(setText("<h1>hello</h1>")));
QHBoxLayout *layout = new QHBoxLayout;
layout->addWidget(label);
layout->addWidget(button);
window->setLayout(layout);
window->show();
return app.exec();
}

连接内的参数必须指示信号和插槽之间的签名,也就是说,它们必须指示发送信号和接收插槽的对象的类型。在这种情况下,放置"<h1>hello</h1>"是没有意义的。一个可能的解决方案是创建一个继承自QLabel的类,并在该方法中实现一个用于更改文本的槽。

#include <QApplication>
#include <QLabel>
#include <QPushButton>
#include <QHBoxLayout>
#include <QWidget>
#include <QObject>
class Label: public QLabel{
Q_OBJECT
public:
using QLabel::QLabel;
public slots:
void updateText(){
setText("<h1>hello</h1>");
}
};
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
QWidget window;
Label *label = new Label("hello");
QPushButton *button = new QPushButton;
button->setText("change");
QObject::connect(button, SIGNAL(clicked()), label, SLOT(updateText()));
QHBoxLayout *layout = new QHBoxLayout;
layout->addWidget(label);
layout->addWidget(button);
window.setLayout(layout);
window.show();
return app.exec();
}
#include "main.moc"

在Qt5和Qt6中,不再需要实现这些类,因为可以使用lambda函数。

#include <QApplication>
#include <QLabel>
#include <QPushButton>
#include <QHBoxLayout>
#include <QWidget>
#include <QObject>

int main(int argc, char *argv[])
{
QApplication app(argc, argv);
QWidget window;
QLabel *label = new QLabel("hello");
QPushButton *button = new QPushButton;
button->setText("change");
QObject::connect(button, &QPushButton::clicked, label, [label](){
label->setText("<h1>hello</h1>");
});
QHBoxLayout *layout = new QHBoxLayout;
layout->addWidget(label);
layout->addWidget(button);
window.setLayout(layout);
window.show();
return app.exec();
}

最新更新