问题
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*)) );
....
}
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);
But what about QSignalMapper
also that is also deprecated.
So how can I update this line:
mapper = new QSignalMapper( this );
connect( mapper, SIGNAL(mapped(QWidget*)), workspace, SLOT(setActiveWindow(QWidget*)) );
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
回答1:
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]);
});
}
If the setMapping()
is not being used, then it probably could have been connected directly to a SLOT()
already.
来源:https://stackoverflow.com/questions/56399947/replacing-deprecated-qtsignalmapper-class-to-forward-signals-in-qt5