在QObject派生类中实例化QWidget派生类

问题描述 投票:0回答:1

出于某种原因,如果您尝试将QObject派生类作为rparent传递给QWidget派生类,则Qt编译器不会编译。

在QObject派生类中为QWidget派生类提供父项的正确方法是什么?我在考虑以下解决方案:

  • 使用带有QWidget类的智能指针,而不是将对象赋予父对象。
  • 从QWidget而不是QObject派生(听起来不对我,因为这个类不是一个小部件)。
  • 将QWidget实例传递给已经拥有父级的QObject驱动类,正如我在下面的示例中尝试演示的那样:
#include <QApplication>
#include <QtWidgets>

class ErrorMsgDialog;
class Controller;
class MainWindow;

// This is the QWidget class used in the QObject derived class (DataReadController)
class ErrorMsgDialog : public QDialog
{
    Q_OBJECT

public:
    explicit ErrorMsgDialog(QWidget *parent = nullptr)
        : QDialog(parent)
    {
        errorLbl = new QLabel("An unknown read error occured!");
        QHBoxLayout* layout = new QHBoxLayout;
        layout->addWidget(errorLbl);
        setLayout(layout);
        setWindowTitle("Error!");
        setGeometry(250, 250, 250, 100);
    }
    ~ErrorMsgDialog() { qDebug() << "~ErrorMsgDialog() destructed"; }

private:
    QLabel* errorLbl;
};

// QObject derived class - I want to instatiate Qwidget derived classes here, with this class as parent
class DataReadController
    : public QObject
{
    Q_OBJECT
public:
    DataReadController(QWidget* pw, QObject *parent = nullptr)
        : QObject(parent)
    {
        m_errorMsgDialog = new ErrorMsgDialog(pw);
        //m_errorMsgDialog = QSharedPointer<ErrorMsgDialog>(m_errorMsgDialog);
        //m_dataReader = new DataReader(this); m_dataReader->moveToThread(m_dataReaderThread); connect(....etc

        //simulate that DataReader emits an error msg
        QTimer::singleShot(2000, [&]() {
            onErrorTriggered();
        });
    }

public slots:
    void onNewDataArrived() {}

    // called if reader emits an error message
    void onErrorTriggered() { m_errorMsgDialog->show(); }
private:
    ErrorMsgDialog* m_errorMsgDialog;
    //QSharedPointer<ErrorMsgDialog> m_errorMsgDialog;
    //DataReader* m_dataReader;// DataReader is not shown here, it would be moved to a different thread and provide some data
};

// MainWindow
class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    MainWindow(QWidget *parent = nullptr)
        : QMainWindow(parent)
    {
        parentWidget = new QWidget(this);   
        m_dataReadController = new DataReadController(parentWidget, this);
        setGeometry(200, 200, 640, 480);

        //Close after 5 seconds.
        QTimer::singleShot(5000, [&]() {
            close();
        });
    }

private:
    QWidget* parentWidget; // QWidget to pass to OBject derive class for parenting QWidgets
    DataReadController* m_dataReadController;
};

// Main
int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    MainWindow w;
    w.show();

    return a.exec();
}

#include "main.moc"

如果我将QSharedPointer与ErrorMsgDialog一起使用,则此测试会崩溃。有关方法的任何建议吗?也许我建议的解决方案都不是最好的做法?

qt memory-management parent-child
1个回答
1
投票

在C ++中,动态创建对象的正确存储和生命周期管理并不容易。经过长时间的挣扎,我开始喜欢某些技术,我仍然使用它非常成功:

  1. 局部变量(由范围管理的存储和生命周期)
  2. 非指针成员变量
  3. 具有明确所有权(共享指针)或非所有权(弱指针)的智能指针。

有了这个,我几乎完全禁止了我的源代码中的原始指针,导致更多的维护更友好的代码和更少烦人的调试。

当然,当外部库(例如小部件集)发挥作用时,我就会被他们的API所束缚。

关于gtkmm 2.4,上述技术也很好用。 gtkmm提供

  • 可共享对象的智能指针
  • 有关儿童小部件的小部件的某种所有权。

当我切换到Qt时,我在教程样本中看到了所有news和原始指针,这让我有些害怕。经过一些实验,我得出的结论是,我将能够像以前在gtkmm中那样编写功能完备的Qt应用程序 - 几乎不需要new(再次)将小部件定义为局部变量(例如在main()中)或从QWidget派生(直接或间接)的其他类的成员变量。

除此之外,随着时间的推移,我意识到了Object Trees & Ownership的一般Qt概念,但我必须承认我在日常业务中很少依赖它。

关于OP的具体问题:

QWidget源自QObject。因此,QObjects的通常所有权原则适用。此外,QWidget期望另一个QWidget作为父母。 QWidget可能是任何QObjects的父母,但反之亦然。

因此,我建议以下所有权:

  • MainWindowDataReadController的父母
  • MainWindowErrorMsgDialog(在DataReadController创建)的父母。

DataReadController将指向ErrorMsgDialog的指针存储为原始指针。 (我相信QSharedPointer提供的所有权将与MainWindow的所有权相冲突。)

(如上所述,在我自己的编程中,我会尝试完全阻止指针并使用(非指针)成员变量。但是,恕我直言,这是风格和个人偏好的问题。)

OP testQParentship.cc的修改样本:

#include <QtWidgets>

class Label: public QLabel {
  private:
    const QString _name;
  public:
    Label(const QString &name, const QString &text):
      QLabel(text),
      _name(name)
    { }

    virtual ~Label()
    {
      qDebug() << _name + ".~Label()";
    }
};

class HBoxLayout: public QHBoxLayout {
  private:
    const QString _name;
  public:
    HBoxLayout(const QString &name):
      QHBoxLayout(),
      _name(name)
    { }

    virtual ~HBoxLayout()
    {
      qDebug() << _name + ".~HBoxLayout()";
    }
};

class ErrorMsgDlg: public QDialog {
  private:
    const QString _name;
  public:
    ErrorMsgDlg(const QString &name, QWidget *pQParent):
      QDialog(pQParent),
      _name(name)
    {
      QHBoxLayout *pQBox = new HBoxLayout("HBoxLayout");
      pQBox->addWidget(
        new Label("Label", "An unknown read error occured!"));
      setLayout(pQBox);
      setWindowTitle("Error!");
    }

    virtual ~ErrorMsgDlg()
    {
      qDebug() << _name + ".~ErrorMsgDlg()";
    }
};

class DataReadCtrl: public QObject {
  private:
    const QString _name;
    ErrorMsgDlg *const _pDlgErrorMsg;

  public:
    DataReadCtrl(const QString &name, QWidget *pQParent):
      QObject(pQParent),
      _name(name),
      _pDlgErrorMsg(
        new ErrorMsgDlg(name + "._pDlgErrorMsg", pQParent))
    {
      //simulate that DataReader emits an error msg
      QTimer::singleShot(2000, [&]() {
        onErrorTriggered();
      });
    }

    virtual ~DataReadCtrl()
    {
      qDebug() << _name + ".~DataReadCtrl()";
    }

    void onErrorTriggered()
    {
      _pDlgErrorMsg->show();
    }
};

class MainWindow: public QMainWindow {
  private:
    const QString _name;
    DataReadCtrl *_pCtrlReadData;

  public:
    MainWindow(const char *name):
      QMainWindow(),
      _name(name),
      _pCtrlReadData(nullptr)
    {
      _pCtrlReadData
        = new DataReadCtrl(_name + "._pCtrlReadData", this);
      //Close after 5 seconds.
      QTimer::singleShot(5000, [&]() {
        qDebug() << _name + ".close()";
        close();
      });
    }

    virtual ~MainWindow()
    {
      qDebug() << _name + ".~MainWindow()";
    }
};

int main(int argc, char **argv)
{
  qDebug() << "Qt Version:" << QT_VERSION_STR;
  QApplication app(argc, argv);
  // setup GUI
  MainWindow winMain("winMain");
  winMain.show();
  // runtime loop
  return app.exec();
}

和一个最小的Qt项目文件testQParentship.pro

SOURCES = testQParentship.cc

QT += widgets

在Windows 10上的cygwin64中编译和测试:

$ qmake-qt5 testQParentship.pro

$ make && ./testQParentship
g++ -c -fno-keep-inline-dllexport -D_GNU_SOURCE -pipe -O2 -Wall -W -D_REENTRANT -DQT_NO_DEBUG -DQT_WIDGETS_LIB -DQT_GUI_LIB -DQT_CORE_LIB -I. -isystem /usr/include/qt5 -isystem /usr/include/qt5/QtWidgets -isystem /usr/include/qt5/QtGui -isystem /usr/include/qt5/QtCore -I. -I/usr/lib/qt5/mkspecs/cygwin-g++ -o testQParentship.o testQParentship.cc
g++  -o testQParentship.exe testQParentship.o   -lQt5Widgets -lQt5Gui -lQt5Core -lGL -lpthread 
Qt Version: 5.9.4

Snapshot of testQParentship

QTimer::singleshot()MainWindow到期后,主窗口关闭。诊断的输出说明了对象树被正确破坏(而不是在OS释放进程内存时“抛出”)。

"winMain.close()"
"winMain.~MainWindow()"
"winMain._pCtrlReadData.~DataReadCtrl()"
"winMain._pCtrlReadData._pDlgErrorMsg.~ErrorMsgDlg()"
"HBoxLayout.~HBoxLayout()"
"Label.~Label()"
© www.soinside.com 2019 - 2024. All rights reserved.