QSignalMapper is deprecated

Today qt4 reference books in the platform above qt5, with QSignalMapper, the results are warned "QSignalMapper is deprecated".

After a search, found the appropriate instructions from reference: https://doc.qt.io/qt-5/qsignalmapper.html
This class Obsolete It IS IS Provided to the Keep Old Source code Working We Strongly Against of advise in.. using it in new code.
official suggested the use of lambda expression inside qt5 way.

Here is the old way:

class ButtonWidget : public QWidget
{
    Q_OBJECT

public:
    ButtonWidget(const QStringList &texts, QWidget *parent = 0);

signals:
    void clicked(const QString &text);

private:
    QSignalMapper *signalMapper;
};
ButtonWidget::ButtonWidget(const QStringList &texts, QWidget *parent)
    : QWidget(parent)
{
    signalMapper = new QSignalMapper(this);

    QGridLayout *gridLayout = new QGridLayout;
    for (int i = 0; i < texts.size(); ++i) {
        QPushButton *button = new QPushButton(texts[i]);
        connect(button, SIGNAL(clicked()), signalMapper, SLOT(map()));
        signalMapper->setMapping(button, texts[i]);
        gridLayout->addWidget(button, i / 3, i % 3);
    }

    connect(signalMapper, SIGNAL(mapped(QString)),
            this, SIGNAL(clicked(QString)));

    setLayout(gridLayout);
}

This class was mostly useful before lambda functions could be used as slots. The example above can be rewritten simpler without QSignalMapper by connecting to a lambda function.
下面是新的方式:

ButtonWidget::ButtonWidget(const QStringList &texts, QWidget *parent)
    : QWidget(parent)
{
    QGridLayout *gridLayout = new QGridLayout;
    for (int i = 0; i < texts.size(); ++i) {
        QString text = texts[i];
        QPushButton *button = new QPushButton(text);
        connect(button, &QPushButton::clicked, [=] { clicked(text); });
        gridLayout->addWidget(button, i / 3, i % 3);
    }
    setLayout(gridLayout);
}

Guess you like

Origin www.cnblogs.com/ramlife/p/10944248.html