【问题标题】:Why are the QLabels being overwritten and not deleted? - see image为什么 QLabels 被覆盖而不是被删除? - 见图片
【发布时间】:2014-06-14 23:02:24
【问题描述】:

我的 UI 的 QGridLayout 有问题。在这里,我尝试创建响应用户加载的文件的 UI。第一次加载时,QGridLayout 会更新以反映文件的内容,一切都很好。但是,下次加载文件时,应该删除网格内的小部件(调用 deleteLater() 来执行此操作)。正在发生的事情是它们刚刚被覆盖。

图片可能会有所帮助 - 这是您在重复加载两个不同文件后看到的内容。你可以看到'Transmit Messages'和'Field'文本很好。

我使用的代码如下。如果有人觉得这里没有发现错误,而是在代码的其他地方发现了错误,我可以发布更多。但似乎在这里找到了令人反感的逻辑。特别是,每次调用都创建一个新的 QLabel 是否有问题?

def populateTxField(self):
    # First delete the old contents
    rowcount = self.txGrid.rowCount()
    for i in range(1, rowcount):
        try:
            # Note that these widgets are QLabel type
            self.txGrid.itemAtPosition(i, 4).widget().deleteLater()
            self.txGrid.itemAtPosition(i, 3).widget().deleteLater()
        except AttributeError:
            # If widget has already been deleted, ignore the error
            pass

    key = self.firstTxMessageInfo.currentText()
    self.txQLabel_LineContainer = []  # store QLineEdits here

    # Now add all of the widgets to the transmission QGridLayout
    row = 1   # counter for adding to txGrid row
    for field in self.dataBack.messages[key].fields.keys():
        newLabel = QtWidgets.QLabel()        # Creating a new widget here...
        newLabel.setText(field)              # Is this problematic?
        newLineEdit = QtWidgets.QLineEdit()

        # Append to the following list to access from txActivateHandler.
        self.txQLabel_LineContainer.append((newLabel, newLineEdit))

        # Now update the grid with the new widgets
        self.txGrid.addWidget(newLabel,    row, 3)
        self.txGrid.addWidget(newLineEdit, row, 4)
        row += 1

【问题讨论】:

  • 按照 Sebastain 的建议,在添加新的小部件之前删除旧的小部件(在您的情况下为标签)

标签: qt pyqt qt5 pyqt5


【解决方案1】:

在删除之前尝试删除小部件:

myWidget = self.txGrid.itemAtPosition(i, 4).widget() 
self.txGrid.removeWidget(myWidget); 
myWidget.deleteLater()

【讨论】:

  • 谢谢,效果很好!没有完全理解先删除后删除的顺序。
  • 第二行代码是可选的,当你想从这个网格布局中删除myWidget 并想添加到其他布局时可以使用它。您可以删除第二行。
  • 合乎逻辑虽然我也会这么说,但事实并非如此,因为这是他的例子,有问题self.txGrid.itemAtPosition(i, 4).widget().deleteLater()。布局似乎保留了对小部件的引用。
猜你喜欢
  • 1970-01-01
  • 2014-06-05
  • 1970-01-01
  • 1970-01-01
  • 2015-03-21
  • 1970-01-01
  • 1970-01-01
  • 2015-09-11
  • 2011-09-22
相关资源
最近更新 更多