4
我在pyqt中的佈局有一些問題。關閉佈局中的項目後,如果layout.count()返回舊項目數量,所以我認爲.close()並沒有真正從佈局中移除項目。這是一個完整的工作示例。什麼是從pyqt佈局中刪除項目的最佳方式
import sys
from PyQt4 import QtGui,QtCore
class LayoutTest(QtGui.QWidget):
def __init__(self):
super(LayoutTest, self).__init__()
self.vvbox = QtGui.QVBoxLayout()
self.dvbox = QtGui.QVBoxLayout()
vbox = QtGui.QVBoxLayout()
vbox.addLayout(self.vvbox)
vbox.addLayout(self.dvbox)
self.setLayout(vbox)
self.add_button = QtGui.QPushButton("Add Items")
self.edit_button = QtGui.QPushButton("Remove Items")
self.chk_button = QtGui.QPushButton("Check Items")
self.vvbox.addWidget(self.add_button)
self.vvbox.addWidget(self.edit_button)
self.vvbox.addWidget(self.chk_button)
self.connect(self.add_button, QtCore.SIGNAL("clicked()"), self.addButtons)
self.connect(self.edit_button, QtCore.SIGNAL("clicked()"), self.removeButtons)
self.connect(self.chk_button, QtCore.SIGNAL("clicked()"), self.checkItems)
self.setGeometry(300, 200, 400, 300)
def keyPressEvent(self, event):
if event.key() == QtCore.Qt.Key_Escape:
self.close()
def addButtons(self):
for i in range(0, 5):
self.r_button = QtGui.QPushButton("Button %s " % i)
self.dvbox.addWidget(self.r_button)
def removeButtons(self):
for cnt in range(self.dvbox.count()):
self.dvbox.itemAt(cnt).widget().close()
def checkItems(self):
QtGui.QMessageBox.information(self, 'Count',"You have %s Items in Layout" % self.dvbox.count(), QtGui.QMessageBox.Ok)
def run():
app = QtGui.QApplication(sys.argv)
ex = LayoutTest()
ex.show()
sys.exit(app.exec_())
if __name__ == "__main__":
run()
只需在添加按鈕中單擊兩次,然後刪除按鈕。然後只需檢查項目。關閉後也會讓你在佈局中有n件物品。
那麼除了關閉之外,從佈局中移除小部件的最佳方式是什麼?
我想我找到了一個解決方案,但不知道它有多高效。這是我的解決方案 def removeButtons(self): counter = self.dvbox.count() for cnt in range(counter): w = self.dvbox.itemAt(self.dvbox.count() - 1) .widget() self.dvbox.removeWidget(w) w.close() – Achayan