问题描述
应用程序运行正常,但 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,argv);
QWidget window;
QLabel *label = new QLabel("hello");
QPushButton *button = new QPushButton;
button->setText("change");
QObject::connect(button,&QPushButton::clicked,[label](){
label->setText("<h1>hello</h1>");
});
QHBoxLayout *layout = new QHBoxLayout;
layout->addWidget(label);
layout->addWidget(button);
window.setLayout(layout);
window.show();
return app.exec();
}