2013-11-20 116 views
1

我有一個QTableWidget,當某個單元格被點擊時調出一個QDialog。關閉QDialog後,QDialog被刪除。當我嘗試再次單擊單元格時,我的程序崩潰。 getDaInx()和getDaSMAC()返回QStringLists。它們應該與我所遇到的問題完全無關。這裏是源代碼:Qt對象刪除導致崩潰

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; 
     } 
    } 
} 
+1

你在調試器中運行過嗎?爲什麼不是removeDialog一個局部變量? –

+0

removeDialog不是局部變量,因爲它在MainWindow :: handleRemoveDialogOk()中被使用。 –

+1

調試器說什麼?崩潰報告/堆棧跟蹤? – Till

回答

2

因爲你用removeDialog指針你得到錯誤,你初始化之前:

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

哈耶,我剛剛看到。不知道爲什麼我以前沒有看到。 –

3

嘗試創建這些:

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

在此之後:

removeDialog = new QDialog(this); 
+3

此代碼處於相同的情況:_checkBox-> setParent(removeDialog); _ – Zlatomir