如何使用Qt5.12创建一个一次性连接(即第一次激活时会自动断开连接)?我正在寻找一种优雅的解决方案,而无需过多的冗长,以明确传达其含义。
我当前正在使用
QObject::connect(instance,Class::signal,this,[this](){
QObject::disconnect(instance,Class::signal,this,0);
/* ... */
});
仅在没有其他信号连接时有效。
这篇帖子https://forum.qt.io/post/328402建议
QMetaObject::Connection * const connection = new QMetaObject::Connection;
*connection = connect(_textFadeOutAnimation, &QPropertyAnimation::finished, [this, text, connection](){
QObject::disconnect(*connection);
delete connection;
});
即使在存在其他连接的情况下也可以工作,但又不是很优雅。
在SO上有几个与此主题有关的问题,但是似乎没有一种解决方案对我有用。例如,https://stackoverflow.com/a/42989833/761090使用伪对象:
QObject *dummy=new QObject(this);
QObject::connect(instance,Class::signal,[dummy](){
dummy->deleteLater();
});
产生运行时警告:
QObject: Cannot create children for a parent that is in a different thread.
(Parent is ClassInstance(0x561c14ce3a60), parent's thread is QThread(0x561c14e1b050), current thread is QThread(0x561c14c2b530)
模板化解决方案(https://stackoverflow.com/a/26554206/761090的第二部分)无法使用c ++ 17进行编译。
还有更好的建议吗?
编辑:我将其作为请求的Qt错误跟踪程序:https://bugreports.qt.io/browse/QTBUG-74547提交。
答案 0 :(得分:1)
我从OP问题中采用了(对我而言)最有前途的方法
QMetaObject::Connection * const connection = new QMetaObject::Connection;
*connection = connect(_textFadeOutAnimation, &QPropertyAnimation::finished, [this, text, connection](){
QObject::disconnect(*connection);
delete connection;
});
,然后考虑如何将其包装到函数中。实际上,它必须是模板函数才能使其可用于任何Qt信号:
template <typename Sender, typename Emitter, typename Slot, typename... Args>
QMetaObject::Connection connectOneShot(
Sender *pSender, void (Emitter::*pSignal)(Args ...args), Slot slot)
{
QMetaObject::Connection *pConnection = new QMetaObject::Connection;
*pConnection
= QObject::connect(pSender, pSignal,
[pConnection, slot](Args... args)
{
QObject::disconnect(*pConnection);
delete pConnection;
slot(args...);
});
return *pConnection;
}
我在MCVE中尝试过:
#include <functional>
#include <QtWidgets>
template <typename Sender, typename Emitter, typename Slot, typename... Args>
QMetaObject::Connection connectOneShot(Sender *pSender, void (Emitter::*pSignal)(Args ...args), Slot slot)
{
QMetaObject::Connection *pConnection = new QMetaObject::Connection;
*pConnection
= QObject::connect(pSender, pSignal,
[pConnection, slot](Args... args)
{
QObject::disconnect(*pConnection);
delete pConnection;
slot(args...);
});
return *pConnection;
}
template <typename Sender, typename Emitter,
typename Receiver, typename Slot, typename... Args>
QMetaObject::Connection connectOneShot(
Sender *pSender, void (Emitter::*pSignal)(Args ...args),
Receiver *pRecv, Slot slot)
{
QMetaObject::Connection *pConnection = new QMetaObject::Connection;
*pConnection
= QObject::connect(pSender, pSignal,
[pConnection, pRecv, slot](Args... args)
{
QObject::disconnect(*pConnection);
delete pConnection;
(pRecv->*slot)(args...);
});
return *pConnection;
}
void onBtnClicked(bool)
{
static int i = 0;
qDebug() << "onBtnClicked() called:" << ++i;
}
struct PushButton: public QPushButton {
int i = 0;
using QPushButton::QPushButton;
virtual ~PushButton() = default;
void onClicked(bool)
{
++i;
qDebug() << this << "PushButton::onClicked() called:" << i;
setText(QString("Clicked %1.").arg(i));
}
};
int main(int argc, char **argv)
{
qDebug() << "Qt Version:" << QT_VERSION_STR;
QApplication app(argc, argv);
// setup user interface
QWidget qWinMain;
QGridLayout qGrid;
qGrid.addWidget(new QLabel("Multi Shot"), 0, 1);
qGrid.addWidget(new QLabel("One Shot"), 0, 2);
auto addRow
= [](
QGridLayout &qGrid, const QString &qText,
QWidget &qWidgetMShot, QWidget &qWidgetOneShot)
{
const int i = qGrid.rowCount();
qGrid.addWidget(new QLabel(qText), i, 0);
qGrid.addWidget(&qWidgetMShot, i, 1);
qGrid.addWidget(&qWidgetOneShot, i, 2);
};
QPushButton qBtnMShotFunc("Click me!");
QPushButton qBtnOneShotFunc("Click me!");
addRow(qGrid, "Function:", qBtnMShotFunc, qBtnOneShotFunc);
PushButton qBtnMShotMemFunc("Click me!");
PushButton qBtnOneShotMemFunc("Click me!");
addRow(qGrid, "Member Function:", qBtnMShotMemFunc, qBtnOneShotMemFunc);
QPushButton qBtnMShotLambda("Click me!");
QPushButton qBtnOneShotLambda("Click me!");
addRow(qGrid, "Lambda:", qBtnMShotLambda, qBtnOneShotLambda);
QLineEdit qEditMShot("Edit me!");
QLineEdit qEditOneShot("Edit me!");
addRow(qGrid, "Lambda:", qEditMShot, qEditOneShot);
qWinMain.setLayout(&qGrid);
qWinMain.show();
// install signal handlers
QObject::connect(&qBtnMShotFunc, &QPushButton::clicked,
&onBtnClicked);
connectOneShot(&qBtnOneShotFunc, &QPushButton::clicked,
&onBtnClicked);
QObject::connect(&qBtnMShotMemFunc, &QPushButton::clicked,
&qBtnMShotMemFunc, &PushButton::onClicked);
connectOneShot(&qBtnOneShotMemFunc, &QPushButton::clicked,
&qBtnOneShotMemFunc, &PushButton::onClicked);
QObject::connect(&qBtnMShotLambda, &QPushButton::clicked,
[&](bool) {
qDebug() << "[&](bool) qBtnMShotLambda called.";
static int i = 0;
qBtnMShotLambda.setText(QString("Clicked %1.").arg(++i));
});
connectOneShot(&qBtnOneShotLambda, &QPushButton::clicked,
[&](bool) {
qDebug() << "[&](bool) for qBtnOneShotLambda called.";
static int i = 0;
qBtnOneShotLambda.setText(QString("Clicked %1.").arg(++i));
});
QObject::connect(&qEditMShot, &QLineEdit::editingFinished,
[&]() {
qDebug() << "[&]() for qEditMShot called. Input:" << qEditMShot.text();
qEditMShot.setText("Well done.");
});
connectOneShot(&qEditOneShot, &QLineEdit::editingFinished,
[&]() {
qDebug() << "[&]() for qEditOneShot called. Input:" << qEditOneShot.text();
qEditOneShot.setText("No more input accepted.");
qEditOneShot.setEnabled(false);
});
// run
return app.exec();
}
相应的Qt项目:
SOURCES = testQSignalOneShot.cc
QT += widgets
在Windows 10的VS2017中测试:
在cygwin64(X11)中使用g ++进行了测试:
$ qmake-qt5 testQSignalOneShot.pro
$ make && ./testQSignalOneShot
g++ -c -fno-keep-inline-dllexport -D_GNU_SOURCE -pipe -O2 -Wall -W -D_REENTRANT -DQT_NO_DEBUG -DQT_WIDGETS_LIB -DQT_GUI_LIB -DQT_CORE_LIB -I. -isystem /usr/include/qt5 -isystem /usr/include/qt5/QtWidgets -isystem /usr/include/qt5/QtGui -isystem /usr/include/qt5/QtCore -I. -I/usr/lib/qt5/mkspecs/cygwin-g++ -o testQSignalOneShot.o testQSignalOneShot.cc
g++ -o testQSignalOneShot.exe testQSignalOneShot.o -lQt5Widgets -lQt5Gui -lQt5Core -lGL -lpthread
Qt Version: 5.9.4
onBtnClicked() called: 1
onBtnClicked() called: 2
onBtnClicked() called: 3
QPushButton(0xffffcb60) PushButton::onClicked() called: 1
QPushButton(0xffffcb60) PushButton::onClicked() called: 2
QPushButton(0xffffcba0) PushButton::onClicked() called: 1
[&](bool) qBtnMShotLambda called.
[&](bool) qBtnMShotLambda called.
[&](bool) for qBtnOneShotLambda called.
[&]() for qEditMShot called. Input: "abc123"
[&]() for qEditMShot called. Input: "def456"
[&]() for qEditMShot called. Input: "Well done."
[&]() for qEditOneShot called. Input: "abc456"
注意:
我必须承认此解决方案有一点缺陷。如果单触发连接不是“触发”而是断开连接(例如,由于删除了发送方对象),则QMetaObject::Connection
不会被删除并会导致内存泄漏。我考虑了一会儿如何解决这个问题,却没有一个好主意。最后,我决定按原样发送此邮件。因此,请带一点盐食用-尚未“准备生产”。至少,它表明了这个想法。
最后,我解决了内存泄漏的问题。
关键在于必须将其传递给内部的“蹦床” lambda。
但是,通过值传递连接可以确保适当的存储管理,但目前尚未初始化。
通过引用传递它可以解决此问题,但这将捕获对局部变量(致命)的引用。
因此,使用new QMetaObject::Connection
的解决方案似乎是唯一可行的方法,因为可以按值传递指针,但此后可以更新实例。由于使用new
进行分配,因此应用程序可以控制QMetaObject::Connection
实例的生命周期。
但是,如果不发出信号怎么办。我的解决方案:否则,发件人对象可能负责删除它。在Qt中,这可以通过将QObject
“附加”到另一个(将后者设置为前者的父级)来实现。
基于此,这是一个改进的解决方案,我将QMetaObject::Connection
存储在派生自QObject
的包装器中:
#include <functional>
#include <QtWidgets>
struct ConnectionWrapper: QObject {
ConnectionWrapper(QObject *pQParent): QObject(pQParent) { }
ConnectionWrapper(const ConnectionWrapper&) = delete;
ConnectionWrapper& operator=(const ConnectionWrapper&) = delete;
virtual ~ConnectionWrapper()
{
qDebug() << "ConnectionWrapper::~ConnectionWrapper()";
}
QMetaObject::Connection connection;
};
template <typename Sender, typename Emitter, typename Slot, typename... Args>
QMetaObject::Connection connectOneShot(Sender *pSender, void (Emitter::*pSignal)(Args ...args), Slot slot)
{
ConnectionWrapper *pConn = new ConnectionWrapper(pSender);
pConn->connection
= QObject::connect(pSender, pSignal,
[pConn, slot](Args... args)
{
QObject::disconnect(pConn->connection);
delete pConn;
slot(args...);
});
return pConn->connection;
}
int main(int argc, char **argv)
{
qDebug() << "Qt Version:" << QT_VERSION_STR;
QApplication app(argc, argv);
// setup user interface
QWidget qWinMain;
QGridLayout qGrid;
auto addRow
= [](QGridLayout &qGrid, const QString &qText, QWidget &qWidgetMShot, QWidget &qWidgetOneShot)
{
const int i = qGrid.rowCount();
qGrid.addWidget(new QLabel(qText), i, 0);
qGrid.addWidget(&qWidgetMShot, i, 1);
qGrid.addWidget(&qWidgetOneShot, i, 2);
};
QPushButton qBtn("One Shot");
QPushButton qBtnDisconnect("Disconnect");
addRow(qGrid, "Disconnect Test:", qBtnDisconnect, qBtn);
qWinMain.setLayout(&qGrid);
qWinMain.show();
// install signal handlers
QMetaObject::Connection connectionBtn
= connectOneShot(&qBtn, &QPushButton::clicked,
[&](bool) {
qDebug() << "[&](bool) for qBtn called.";
static int i = 0;
qBtn.setText(QString("Clicked %1.").arg(++i));
});
QObject::connect(&qBtnDisconnect, &QPushButton::clicked,
[&](bool) {
QObject::disconnect(connectionBtn);
qDebug() << "qBtn disconnected.";
});
// run
return app.exec();
}
相应的Qt项目:
SOURCES = testQSignalOneShot2.cc
QT += widgets
我再次在VS2017(Windows 10“ native”)和带有X11的cygwin64上进行了测试。在后者的会话下方:
$ qmake-qt5 testQSignalOneShot2.pro
$ make && ./testQSignalOneShot2
/usr/bin/qmake-qt5 -o Makefile testQSignalOneShot2.pro
g++ -c -fno-keep-inline-dllexport -D_GNU_SOURCE -pipe -O2 -Wall -W -D_REENTRANT -DQT_NO_DEBUG -DQT_WIDGETS_LIB -DQT_GUI_LIB -DQT_CORE_LIB -I. -isystem /usr/include/qt5 -isystem /usr/include/qt5/QtWidgets -isystem /usr/include/qt5/QtGui -isystem /usr/include/qt5/QtCore -I. -I/usr/lib/qt5/mkspecs/cygwin-g++ -o testQSignalOneShot2.o testQSignalOneShot2.cc
g++ -o testQSignalOneShot2.exe testQSignalOneShot2.o -lQt5Widgets -lQt5Gui -lQt5Core -lGL -lpthread
Qt Version: 5.9.4
ConnectionWrapper::~ConnectionWrapper()
[&](bool) for qBtn called.
qBtn disconnected.
在这种情况下,我首先按下一个镜头,然后按下第二个 Disconnect 。再次测试相反的顺序:
$ make && ./testQSignalOneShot2
make: Nothing to be done for 'first'.
Qt Version: 5.9.4
qBtn disconnected.
ConnectionWrapper::~ConnectionWrapper()
在这种情况下,我退出应用程序之前没有出现ConnectionWrapper::~ConnectionWrapper()
的输出。 (可以理解–离开qBtn
的范围时,发件人main()
被删除。)
答案 1 :(得分:1)
还有一种更简单的方法:删除接收者以破坏连接。
auto receiver = new QObject(this);
connect(_textFadeOutAnimation, &QPropertyAnimation::finished, receiver, [this, text, receiver](){
receiver.deleteLater();
});
答案 2 :(得分:0)
前一段时间,我为单次连接编写了一个包装。似乎工作正常,也许对某些人有用。
Z::Z(const Z &X){
z1 = new int(*X.first() );
z2 = new int(*X.second() );
}
Z& operator=(const Z& X)
{
*z1 = *(X.z1);
*z2 = *(X.z2);
return *this;
}
用法示例:
template <typename SenderFunc, typename ReceiverFunc>
void singleShotConnect(const typename QtPrivate::FunctionPointer<SenderFunc>::Object* sender, SenderFunc signal, const QObject* context, ReceiverFunc receiverFunc){
auto connection = std::make_shared<QMetaObject::Connection>();
connection = QObject::connect(sender, signal, context, [connection, receiverFunc](auto ...args){
QObject::disconnect(*connection);
std::invoke(receiverFunc, args...);
});
};