今天参考 qt4 的书籍,在 qt5 的平台上面,用了 QSignalMapper,结果收到警告“ QSignalMapper is deprecated"。

经过一番查找,找到了相应的说明, 参考自:https://doc.qt.io/qt-5/qsignalmapper.html This class is obsolete. It is provided to keep old source code working. We strongly advise against using it in new code. 官方建议 qt5 里面使用 lambda 方式表达。

下面是旧的方式:

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

标签: Qt

添加新评论