如何将qobject作为参数从信号传递到qt中的插槽 [英] how to pass qobject as argument from signal to slot in qt connect

查看:327
本文介绍了如何将qobject作为参数从信号传递到qt中的插槽的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的原始代码将QStringList从信号传递到插槽,然后返回QList。一切工作正常,但我需要将QStringList和QList都更改为2个不同的子类QObject。从那以后,我一直收到诸如此处首先需要综合方法之类的错误,否则它会崩溃而没有任何错误消息。

My original code passed a QStringList from the signal to the slot and then returned a QList. Everything worked fine but I needed to change both the QStringList and QList into 2 different subclassed QObjects. Since then I have been receiving errors like "synthesized method first required here" or it simply crashes without any error message.

我知道qt复制了队列中传递的所有参数。连接和qobject无法复制。因此,我认为我将在发出信号之前创建两个qobject,而不是返回qobject。然后,我将传递给每个对象的引用,在slot函数中修改其中之一,并使返回值无效。不幸的是,无论我如何编码信号和插槽功能,该应用程序仍然崩溃。如何编码信号/插槽函数并连接它们以将两个qobject作为参数传递或返回qobject?

I understand that qt copies all arguments passed in a queued connection and a qobject cannot be copied. So instead of returning a qobject I thought I would create both qobjects prior to emitting the signal. Then I would pass references to each object, modify one of them in the slot function and void the return value. Unfortunately the app still crashes no matter how I code the signal and slot functions. How can I code the signal/slot functions and connect them to either pass both qobjects as arguments or return a qobject?

MyQObject1 obj1("a","b","c");
MyQObject2 obj2();
emit sendSignal(&obj1, &obj2);
// or
MyQObject2 obj2 = emit sendSignal(&obj1);

connect(someObj, SIGNAL(sendSignal(const QObject&)), this, SLOT(receiveSignal(const QObject&)));

receiveSignal()函数不会直接创建或修改任何qobject。它必须先将qobjects传递给另一个函数,然后再修改obj2或创建并返回它。任何代码示例都将不胜感激。

The receiveSignal() function does not directly create or modify any qobject. It has to pass the qobjects to another function first which then either modifies obj2 or creates and returns it. Any code examples would be greatly appreciated.

推荐答案

通常 QObject 被传递通过指针,而不是通过引用(请注意, QObject 不能复制,也不能按值传递)。默认情况下, QObject * 被注册为元类型。因此,使用 QObject * 参数创建信号和插槽足以使它们工作:

Usually QObject is passed by pointer, not by reference (note that QObject cannot be copied and cannot be passed by value). QObject* is registered as a meta type by default. So creating a signal and a slot with QObject* argument is enough to get them work:

private slots:
  void test_slot(QObject* object);

signals:
  void test_signal(QObject* object);

初始化:

connect(this, SIGNAL(test_signal(QObject*)), this, SLOT(test_slot(QObject*)));

发射:

QObject* object = new QObject();
emit test_signal(object);

当然,信号和插槽可以位于不同的类别中。

Of course the signal and the slot could be in different classes.

这篇关于如何将qobject作为参数从信号传递到qt中的插槽的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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