正常new的指针,信号槽如下写法肯定没问题的
-
ContHeightPropertyDialog *dia =
new
ContHeightPropertyDialog(
this);
-
connect(dia, &ContHeightPropertyDialog::execClicked,
this, [ = ]()
-
{
-
qDebug() <<
"execClicked";
-
});
-
int code = dia->
exec();
使用智能指针是否也能向上面一样信号连接了,经过测试发现了几个坑
错误1:connect参数1,直接写成智能指针变量
代码写成如下
-
QScopedPointer<ContHeightPropertyDialog> dia(new ContHeightPropertyDialog(this));
-
connect(dia, &ContHeightPropertyDialog::execClicked,
this, [ = ]()
-
{
-
qDebug() <<
"execClicked";
-
});
-
int code = dia->
exec();
这时你将出现如下报错
error: C2664: “QMetaObject::Connection QObject::connect(const QObject *,const char *,const char *,Qt::ConnectionType) const”: 无法将参数 1 从“QScopedPointer<ContHeightPropertyDialog,QScopedPointerDeleter<T>>”转换为“const ProcessPropertyEditor *”
with
[
T=ContHeightPropertyDialog
]
正确的写法:使用.data()
-
QScopedPointer<ContHeightPropertyDialog> dia(new ContHeightPropertyDialog(this));
-
connect(dia.
data(), &ContHeightPropertyDialog::execClicked,
this, [ = ]()
-
{
-
qDebug() <<
"execClicked";
-
});
-
int code = dia->
exec();
错误2:connect参数4,lamba表达式采用传值的方式,调用public 函数
代码写成如下
-
QScopedPointer<ContHeightPropertyDialog> dia(new ContHeightPropertyDialog(this));
-
connect(dia.
data(), &ContHeightPropertyDialog::execClicked,
this, [ = ]()
-
{
-
qDebug() <<
"execClicked";
-
dia->
showResult(
QStringLiteral(
"高度差: 11"));
-
});
这时你将出现如下报错,如果是直接new的对象,这么写肯定是没问题的
error: C2248: “QScopedPointer<ContHeightPropertyDialog,QScopedPointerDeleter<T>>::QScopedPointer”: 无法访问 private 成员(在“QScopedPointer<ContHeightPropertyDialog,QScopedPointerDeleter<T>>”类中声明)
with
[
T=ContHeightPropertyDialog
]
正确的写法:lambda表达式改为传引用
-
QScopedPointer<ContHeightPropertyDialog> dia(new ContHeightPropertyDialog(this));
-
connect(dia, &ContHeightPropertyDialog::execClicked,
this, [ & ]()
-
{
-
qDebug() <<
"execClicked";
-
dia->
showResult(
QStringLiteral(
"高度差: 11"));
-
});
转载:https://blog.csdn.net/qq_40602000/article/details/128400783