How to simply delete a line in QFormLayout programmatically

I have this code:

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

Now I need to delete the line only with the myEdit link:

 myQformLayout.removeRow(myEdit) 

But there is no API for this. I can use .takeAt() , but how can I get the argument? How to find tag index or myEdit index?

+7
source share
3 answers

You can simply plan the widget and its label (if any) for deletion, and let the shape change accordingly. The label for the widget can be restored using labelForField .

Pton Qt Code:

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

my decision...

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

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

To delete a line, 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 } 

Please note that I retrieve all the elements before deleting them. This is because I do not know if their role will change when the item is deleted. This behavior is not specified, so I'm playing safe. In qt design, when you remove an element from a form, another element per line takes up all the space (which means its role is changing ...).

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

0
source

All Articles