【问题标题】:Qt object deletion causing crashQt 对象删除导致崩溃
【发布时间】:2013-11-20 19:26:24
【问题描述】:

我有一个 QTableWidget,当点击某个单元格时会弹出一个 QDialog。关闭 QDialog 后,QDialog 被删除。当我再次尝试单击单元格时,我的程序崩溃了。 getDaInx() 和 getDaSMAC() 返回 QStringLists。它们应该与我遇到的问题完全无关。以下是源代码:

QDialog *removeDialog;

// connect in MainWindow constructor
connect(ui->theTable, SIGNAL(cellClicked(int,int)), this, SLOT(handleCellClick(int,int)));

void MainWindow::handleCellClick(int row, int col)
{
    if (col == 9)
    {
        if (row > 0)
        {
            QGridLayout *removeLayout = new QGridLayout();

            for (int x = 1; x < getDaInx().length(); x++)
            {
                if (getDaInx().length() != getDaSMAC().length()) break;

                QString device = getDaSMAC()[x];
                QString inx = getDaInx()[x];

                QCheckBox *checkBox = new QCheckBox(QString("Remove    %1    %2").arg(inx).arg(device));
                if (x == row) checkBox->setChecked(true);
                checkBox->setParent(removeDialog);

                removeLayout->addWidget(checkBox, x, 0);
            }

            QPushButton *okBtn = new QPushButton("OK", removeDialog);
            QPushButton *cancelBtn = new QPushButton("Cancel", removeDialog);

            connect(okBtn, SIGNAL(clicked()), this, SLOT(handleRemoveDialogOk()));
            connect(cancelBtn, SIGNAL(clicked()), this, SLOT(handleRemoveDialogCancel()));

            int rowCount = removeLayout->rowCount();

            removeLayout->addWidget(okBtn, rowCount, 0);
            removeLayout->addWidget(cancelBtn, rowCount, 1);

            removeDialog = new QDialog(this);

            removeDialog->setLayout(removeLayout);

            removeDialog->exec();

            disconnect(okBtn, SIGNAL(clicked()), this, SLOT(handleRemoveDialogOk()));
            disconnect(cancelBtn, SIGNAL(clicked()), this, SLOT(handleRemoveDialogCancel()));

            delete removeDialog;
        }
    }
}

【问题讨论】:

  • 你是在调试器中运行的吗?为什么 removeDialog 不是局部变量?
  • removeDialog 不是局部变量,因为它正在 MainWindow::handleRemoveDialogOk() 中使用。
  • 调试器说什么?崩溃报告/堆栈跟踪?

标签: c++ qt object delete-operator


【解决方案1】:

尝试创建这些:

    QPushButton *okBtn = new QPushButton("OK", removeDialog);
    QPushButton *cancelBtn = new QPushButton("Cancel", removeDialog);

之后:

    removeDialog = new QDialog(this);

【讨论】:

  • 这段代码也是同样的情况:checkBox->setParent(removeDialog);
【解决方案2】:

你得到错误是因为你在初始化之前使用了 removeDialog 指针:

//...
checkBox->setParent(removeDialog);
//...
QPushButton *okBtn = new QPushButton("OK", removeDialog);
QPushButton *cancelBtn = new QPushButton("Cancel", removeDialog);
//...
removeDialog = new QDialog(this);

【讨论】:

  • 哈,我刚刚看到了。不知道为什么我以前没有看到。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-03-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-10-22
相关资源
最近更新 更多