飞道的博客

Qt智能指针信号槽连接问题

387人阅读  评论(0)

正常new的指针,信号槽如下写法肯定没问题的


  
  1. ContHeightPropertyDialog *dia = new ContHeightPropertyDialog( this);
  2. connect(dia, &ContHeightPropertyDialog::execClicked, this, [ = ]()
  3. {
  4. qDebug() << "execClicked";
  5. });
  6. int code = dia-> exec();

使用智能指针是否也能向上面一样信号连接了,经过测试发现了几个坑

错误1:connect参数1,直接写成智能指针变量

代码写成如下


  
  1. QScopedPointer<ContHeightPropertyDialog> dia(new ContHeightPropertyDialog(this));
  2. connect(dia, &ContHeightPropertyDialog::execClicked, this, [ = ]()
  3. {
  4. qDebug() << "execClicked";
  5. });
  6. 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()


  
  1. QScopedPointer<ContHeightPropertyDialog> dia(new ContHeightPropertyDialog(this));
  2. connect(dia. data(), &ContHeightPropertyDialog::execClicked, this, [ = ]()
  3. {
  4. qDebug() << "execClicked";
  5. });
  6. int code = dia-> exec();

错误2:connect参数4,lamba表达式采用传值的方式,调用public 函数

代码写成如下


  
  1. QScopedPointer<ContHeightPropertyDialog> dia(new ContHeightPropertyDialog(this));
  2. connect(dia. data(), &ContHeightPropertyDialog::execClicked, this, [ = ]()
  3. {
  4. qDebug() << "execClicked";
  5. dia-> showResult( QStringLiteral( "高度差: 11"));
  6. });

这时你将出现如下报错,如果是直接new的对象,这么写肯定是没问题的

error: C2248: “QScopedPointer<ContHeightPropertyDialog,QScopedPointerDeleter<T>>::QScopedPointer”: 无法访问 private 成员(在“QScopedPointer<ContHeightPropertyDialog,QScopedPointerDeleter<T>>”类中声明)
with
[
    T=ContHeightPropertyDialog
]

 正确的写法:lambda表达式改为传引用


  
  1. QScopedPointer<ContHeightPropertyDialog> dia(new ContHeightPropertyDialog(this));
  2. connect(dia, &ContHeightPropertyDialog::execClicked, this, [ & ]()
  3. {
  4. qDebug() << "execClicked";
  5. dia-> showResult( QStringLiteral( "高度差: 11"));
  6. });


转载:https://blog.csdn.net/qq_40602000/article/details/128400783
查看评论
* 以上用户言论只代表其个人观点,不代表本网站的观点或立场