替换已弃用的 QtSignalMapper 类以在 Qt5 中转发信号 [英] Replacing deprecated QtSignalMapper class to forward Signals in Qt5

查看:65
本文介绍了替换已弃用的 QtSignalMapper 类以在 Qt5 中转发信号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这段代码,它为 Qt 4 编写了一个 mdi 窗口:

I have this code which makes a mdi window written for Qt 4:

class MdiWindow : public QMainWindow
{
    Q_OBJECT
public:
    MdiWindow( QWidget *parent = nullptr)

...
private:
    QWorkspace* workspace
    QSignalMapper* mapper
}


MdiWindow::MdiWindow( QWidget *parent ) : QMainWindow( parent )
{
  ...

  workspace = new QWorkspace;
  setCentralWidget( workspace );

  connect( workspace, SIGNAL(windowActivated(QWidget *)), this, SLOT(enableActions()));
  mapper = new QSignalMapper( this );
  connect( mapper, SIGNAL(mapped(QWidget*)), workspace, SLOT(setActiveWindow(QWidget*)) );

  ....
}

根据 QT 文档 QWorkspace 应替换为 QMdiArea.

According to the QT documentation QWorkspace should be replaced with QMdiArea.

我这样做了,并像这样写了第一个连接:

I did that and wrote the first connect like this:

connect(workspace, &QMdiArea::subWindowActivated,
        this, &MdiWindow::enableActions);

但是 QSignalMapper 也被弃用了.

那么我该如何更新这一行:

So how can I update this line:

mapper = new QSignalMapper( this );
connect( mapper, SIGNAL(mapped(QWidget*)), workspace, SLOT(setActiveWindow(QWidget*)) );

我读到 QSignalMapper 可以用 lamdas 替换,但在这种情况下如何?如果我理解正确 mapper 将所有信号从这里转发到 workspace

I read QSignalMapper can be replaced with lamdas but how in this case? If i understand right mapper forwards all the signals from this to the active window of workspace

推荐答案

以前您使用 QSignalMapper::setMapping() 来确保在 SLOT() 被调用.现在你可以把这个逻辑封装在一个 Lamba 中,所以如果你这样做了(比如在 Qt 示例):

Previously you used QSignalMapper::setMapping() to make sure that you'd be sent data you need when the SLOT() was called. Now you can just encapsulate this logic inside a lamba, so if you did (like in Qt example):

     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]);
     }
     connect(signalMapper, SIGNAL(mapped(const QString &)),
             this, SIGNAL(clicked(const QString &)));

你现在可以做(有点):

you can now do (somewhat):

     for (int i = 0; i < texts.size(); ++i) {
         QPushButton *button = new QPushButton(texts[i]);
         connect(button, &QPushButton::clicked, [=]() {
             emit clicked(texts[i]);
         });
     }

如果没有使用 setMapping(),那么它可能已经直接连接到 SLOT().

If the setMapping() is not being used, then it probably could have been connected directly to a SLOT() already.

这篇关于替换已弃用的 QtSignalMapper 类以在 Qt5 中转发信号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆