QGraphicsWidget 作为 QObject 的子项

QGraphicsWidget as a child of QObject

本文关键字:QObject 作为 QGraphicsWidget      更新时间:2023-10-16

这是否有可能具有QObjects和(例如)QGraphicsWidgets的树状结构?我的意思是,我不能像这样编写初始化列表:

class MyButton : public QGraphicsWidget
{
    Q_OBJECT
public:
    MyButton(int buttonId, QObject *parent = 0) : QObject(parent)
    {
    }

然后,像

myButton = new MyButton(id, myObject);

我应该做.setParent还是什么?

更新:查看实际分配:

class myObject : public QObject
{
    Q_OBJECT
public:
    MyObject(QObject *parent = 0) : QObject(parent) {
        }
    MyButton *myButton;
    void showButton(){
        myButton = new MyButton(id, this); //no matching function for call to 'MyButton::MyButton(MyObject* const)'
//note:   no known conversion for argument from 'MyObject* const' to 'QGraphicsObject*'
    }
};

我认为您在图形场景中混淆了 QObject 父/子层次结构父级和parent item parent。如果你想要前者,你确实需要使用通常的setParent机制。

无论哪种方式,基类构造尝试都是错误的。将其替换为:

MyButton(int buttonId, QGraphicsItem *parent = 0) : QGraphicsWidget(parent)

此外,如果您使用Qt 5,您可能希望签出Q_NULLPTR而不是0NULLnullptr和其他变体。

如果希望图形项成为父项,则需要使用同时继承QGraphicsItemQObjectQGraphicsObject。它们可以用于育儿目的。

此外,由于QGraphicsWidget继承QGraphicsObject,因此可以直接用于两种育儿机制。