简体   繁体   中英

How to simply delete row in QFormLayout programatically

I have this code:

myEdit = QLineEdit()
myQFormLayout.addRow("myLabelText", myEdit)

Now I have to remove the row by reference to myEdit only:

myQformLayout.removeRow(myEdit)

But there is no API for that. I can use .takeAt() , but how can I get the argument? How do I find the label index, or the index of myEdit ?

You can just schedule the widget and its label (if it has one) for deletion, and let the form adjust itself accordingly. The label for the widget can be retrieved using labelForField .

Python Qt code:

    label = myQformLayout.labelForField(myEdit)
    if label is not None:
        label.deleteLater()
    myEdit.deleteLater()

my solution...

in header file:

QPointer<QFormLayout> propertiesLayout; 

in cpp file:

// Remove existing info before re-populating.
while ( propertiesLayout->count() != 0) // Check this first as warning issued if no items when calling takeAt(0).
{
    QLayoutItem *forDeletion = propertiesLayout->takeAt(0);
    delete forDeletion->widget();
    delete forDeletion;
}

This is actually a very good point... there is no explicit reverse function for addRow() .

To remove a row you can do the following:

QLineEdit *myEdit;
int row;
ItemRole role;
//find the row
myQFormLayout->getWidgetPosition( myEdit, &row, &role);
//stop if not found  
if(row == -1) return;

ItemRole otheritemrole;
if( role == QFormLayout::FieldRole){
    otheritemrole = QFormLayout::LabelRole;
}
else if( role == QFormLayout::LabelRole){
    otheritemrole = QFormLayout::FieldRole;
}

//get the item corresponding to the widget. this need to be freed
QLayoutItem* editItem = myQFormLayout->itemAt ( int row, role );

QLayoutItem* otherItem = 0;

//get the item corresponding to the other item. this need to be freed too
//only valid if the widget doesn't span the whole row
if( role != QFormLayout::SpanningRole){
    otherItem = myQFormLayout->itemAt( int row, role );
}

//remove the item from the layout
myQFormLayout->removeItem(editItem);
delete editItem;

//eventually remove the other item
if( role != QFormLayout::SpanningRole){
     myQFormLayout->removeItem(otherItem);
     delete otherItem 
}

Note that I retrieve all the items before removing them. That's because I don't know if their role will change when an item is removed. This behavior is not specified so I am playing safe. In qt designer, when you remove an item from a form, the other item on the row take all the space (which means his role changes...).

Maybe there is a function somewhere and not only I reinvented the wheel but I made a broken one...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM