Qt 接口或抽象类和 qobject_cast()

发布于 2024-09-19 10:04:17 字数 318 浏览 13 评论 0原文

我有一组相当复杂的 C++ 类,它们是从 Java 重写的。所以每个类都有一个继承类,然后它还实现一个或多个抽象类(或接口)。

是否可以使用 qobject_cast() 从类转换为接口之一?如果我从 QObject 派生所有接口,则会由于不明确的 QObject 引用而收到错误。但是,如果我只有从 QObject 继承的基类,则无法使用 qobject_cast(),因为它与 QObject 一起运行。

我希望能够在插件和 DLL 之间通过其接口引用类。

I have a fairly complex set of C++ classes that are re-written from Java. So each class has a single inherited class, and then it also implements one or more abstract classes (or interfaces).

Is it possible to use qobject_cast() to convert from a class to one of the interfaces? If I derive all interfaces from QObject, I get an error due to ambiguous QObject references. If however, I only have the base class inherited from QObject, I can't use qobject_cast() because that operates with QObjects.

I'd like to be able to throw around classes between plugins and DLLs referred to by their interfaces.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

£噩梦荏苒 2024-09-26 10:04:17

经过一番研究和阅读qobject_cast 文档,我发现了这一点:

qobject_cast() 也可以用于
与接口结合;看到
即插即用详细绘制示例。

以下是示例的链接: 即插即用油漆

在挖掘示例中的 interfaces 标头之后,我找到了 Q_DECLARE_INTERFACE 宏,它应该可以让你做你想做的事情。

首先,不要从您的接口继承QObject。对于您拥有的每个接口,请使用如下所示的 Q_DECLARE_INTERFACE 声明:

class YourInterface
{
public:
    virtual void someAbstractMethod() = 0;
};

Q_DECLARE_INTERFACE(YourInterface, "Timothy.YourInterface/1.0")

然后在您的类定义中,使用 Q_INTERFACES 宏,如下所示:

class YourClass: public QObject, public YourInterface, public OtherInterface
{
    Q_OBJECT
    Q_INTERFACES(YourInterface OtherInterface)

public:
    YourClass();

    //...
};

经过所有这些麻烦,以下代码可以工作:

YourClass *c = new YourClass();
YourInterface *i = qobject_cast<YourInterface*>(c);
if (i != NULL)
{
    // Yes, c inherits YourInterface
}

After some research and reading the qobject_cast documentation, I found this:

qobject_cast() can also be used in
conjunction with interfaces; see the
Plug & Paint example for details.

Here is the link to the example: Plug & Paint.

After digging up the interfaces header in the example, I found the Q_DECLARE_INTERFACE macro that should let you do what you want.

First, do not inherit QObject from your interfaces. For every interface you have, use the Q_DECLARE_INTERFACE declaration like this:

class YourInterface
{
public:
    virtual void someAbstractMethod() = 0;
};

Q_DECLARE_INTERFACE(YourInterface, "Timothy.YourInterface/1.0")

Then in your class definition, use the Q_INTERFACES macro, like this:

class YourClass: public QObject, public YourInterface, public OtherInterface
{
    Q_OBJECT
    Q_INTERFACES(YourInterface OtherInterface)

public:
    YourClass();

    //...
};

After all this trouble, the following code works:

YourClass *c = new YourClass();
YourInterface *i = qobject_cast<YourInterface*>(c);
if (i != NULL)
{
    // Yes, c inherits YourInterface
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文