Qt 如何以编程方式简单地删除QFormLayout中的行
我有以下代码:Qt 如何以编程方式简单地删除QFormLayout中的行,qt,layout,pyqt,Qt,Layout,Pyqt,我有以下代码: myEdit = QLineEdit() myQFormLayout.addRow("myLabelText", myEdit) 现在,我必须仅通过引用myEdit删除该行: myQformLayout.removeRow(myEdit) 但目前还没有相关的API。我可以使用.takat(),但如何获取参数?如何找到标签索引或myEdit的索引?这实际上是一个很好的观点。。。addRow()没有明确的反向函数 要删除行,可以执行以下操作: QLineEdit *myEdit;
myEdit = QLineEdit()
myQFormLayout.addRow("myLabelText", myEdit)
现在,我必须仅通过引用myEdit
删除该行:
myQformLayout.removeRow(myEdit)
但目前还没有相关的API。我可以使用
.takat()
,但如何获取参数?如何找到标签索引或myEdit的索引?这实际上是一个很好的观点。。。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 designer中,当您从窗体中删除一个项时,另一个项将显示在
这一行占据了所有的空间(这意味着他的角色发生了变化…)
也许某个地方有一个功能,我不仅重新发明了轮子,而且还制造了一个坏的…您可以安排删除小部件及其标签(如果有),并让表单进行相应的调整。可以使用检索小部件的标签 Python Qt代码:
label = myQformLayout.labelForField(myEdit)
if label is not None:
label.deleteLater()
myEdit.deleteLater()
我的解决方案
在头文件中:
QPointer<QFormLayout> propertiesLayout;
你应该/必须使用指针(我假设这是C++代码)。试试ReaveWiGET(MyEdgEd)OK,所以我应该调用Dealth.UpDebug(),因为它看起来只在DeleTelEnter()之后才好。对不起,我不明白你的意思。在调用
deleteLater()
之前,您在做什么?@borovsky。当一个小部件被删除时,Qt也会递归地删除它的所有子部件(这就是为什么确保小部件总是有一个父部件是一个好主意)。在Python方面,垃圾收集器最终将进行清理。但是,如果保留对对象(例如实例属性)的引用,您可能希望自己显式删除它。一旦Qt删除了C++部分,Python部分就变得不可用了,所以如果你想用它做任何事情,你将得到运行时错误。
// 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;
}