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

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...