How to pass a parent pointer in a custom Qt class?

In Qt, you can pass a parent pointer as a parameter in the constructor. Here are the specific steps:

  1. Add a parameter in the constructor of a custom class, which is of the type of the parent pointer (usually QObject*).
  2. Assign this parameter to the constructor of the parent class in the initialization list.
  3. Pass the parent pointer to the constructor when creating a custom class object.

Here is an example code:

class MyCustomClass : public QObject
{
public:
    MyCustomClass(QObject* parent = nullptr) : QObject(parent)
    {
        // 构造函数的逻辑
    }
};

int main(int argc, char *argv[])
{
    QApplication app(argc, argv);

    QWidget* parentWidget = new QWidget();

    MyCustomClass* customObject = new MyCustomClass(parentWidget);
    
    // 其他代码

    return app.exec();
}

In the example above, pass QObject* parent as a parameter to the constructor, and then pass it to the constructor of the QObject class in the initialization list. Pass the parent pointer parentWidget to the constructor when creating a MyCustomClass object.

bannerAds