繁体   English   中英

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 继承的类,并在该方法中实现一个文本被更改的插槽。

#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();
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM