我有这个代码:
myEdit = QLineEdit()
myQFormLayout.addRow("myLabelText", myEdit)
现在我必须myEdit
仅通过引用删除该行:
myQformLayout.removeRow(myEdit)
但是没有API。我可以使用.takeAt()
,但我怎样才能得到论点?如何找到标签索引或 的索引myEdit
?
您可以安排要删除的小部件及其标签(如果有的话),并让表单相应地自行调整。可以使用labelForField检索小部件的标签。
Python Qt 代码:
label = myQformLayout.labelForField(myEdit)
if label is not None:
label.deleteLater()
myEdit.deleteLater()
我的解决方案...
在头文件中:
QPointer<QFormLayout> propertiesLayout;
在 cpp 文件中:
// 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;
}
这实际上是一个很好的观点……没有明确的反向函数addRow()
。
要删除一行,您可以执行以下操作:
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
}
请注意,我在删除它们之前检索了所有项目。那是因为我不知道当一个项目被删除时他们的角色是否会改变。没有指定这种行为,所以我玩得很安全。在 qt 设计器中,当您从表单中删除一个项目时,该行上的另一个项目会占用所有空间(这意味着他的角色发生了变化......)。
也许某处有一个功能,我不仅重新发明了轮子,而且还做了一个坏了的轮子……