2017-05-17 41 views
0

我的小部件添加到佈局,然後添加此佈局一行到另一個佈局:如何從佈局中刪除多行?

lbl = new QLabel(this); 
    currentResistorText += tr("Resistor") + tr("#") + QString::number(resistorCounter); 
    lbl->setText(currentResistorText); 

    newResistorLayout = new QHBoxLayout(); 

    lineEdit = new QLineEdit(this); 

    newResistorLayout->addWidget(lbl); 
    newResistorLayout->addWidget(lineEdit); 

    ui->resistorsLayout->insertRow(fieldCounter, newResistorLayout); 

我做插槽,因此可以添加多個行。

當我嘗試刪除一行它的作品。

下面是代碼:

ui->resistorsLayout->takeRow(ui->resistorLayout->rowCount() - 1); 

    delete lbl; 
    delete lineEdit; 
    delete newResistorLayout; 

如果我嘗試刪除第二行則計劃只是崩潰。我也嘗試使用removeRow()方法,但結果相同。我究竟做錯了什麼?我怎樣才能刪除多行?
我正在使用Qt 5.8。

回答

0

從Qt文檔:

[pure virtual] QLayoutItem * QLayout::takeAt(int index)

必須在子類中實現索引從佈局刪除佈局項目,並返回該項目。如果沒有這樣的項目,函數必須不做任何事情並返回0.項目從0開始連續編號。如果項目被刪除,其他項目將被重新編號。

下面的代碼片段展示了一個安全的方法從佈局中刪除所有項目:

QLayoutItem *child; 
while ((child = layout->takeAt(0)) != 0) { 
    ... 
    delete child; 
} 

希望它能幫助。