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

qt4 the clicked signal in the connect button doesn't trigger the settext in the label

应用程序运行正常,但 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 的 class,并在该方法中实现一个文本更改位置。

#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 中,不再需要实现 classes,因为可以使用 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();
}