gpt4 book ai didi

python - 如何从 QListWidget 中删除 ListWidget 项目

转载 作者:太空宇宙 更新时间:2023-11-03 18:29:51 25 4
gpt4 key购买 nike

ListWidget 中有 5 个项目。按下按钮打印当前项目及其索引。似乎应该有足够的信息来从 ListWidget 中删除/删除该项目。

问题:如何从 ListWidget 中删除当前选定的列表项?

from PyQt4 import QtGui, QtCore
import sys, os

class Dialog_01(QtGui.QMainWindow):
def __init__(self):
super(QtGui.QMainWindow,self).__init__()

myQWidget = QtGui.QWidget()
myBoxLayout = QtGui.QVBoxLayout()
myQWidget.setLayout(myBoxLayout)
self.setCentralWidget(myQWidget)

self.listWidgetA = QtGui.QListWidget()
for i in range(5):
QtGui.QListWidgetItem( 'Item '+str(i), self.listWidgetA )

self.listWidgetA.itemClicked.connect(self.item_clicked)

myBoxLayout.addWidget(self.listWidgetA)

myButton=QtGui.QPushButton("Delete")
myBoxLayout.addWidget(myButton)
myButton.clicked.connect(self.deleteItem)

def item_clicked(self, arg):
print '\n\t selectedItem', arg
print '\n\t indexFromItem', self.listWidgetA.indexFromItem(arg)

def deleteItem(self):
print '\n\t\t currentItem:', self.listWidgetA.currentItem()
print '\n\t\t currentIndex:', self.listWidgetA.currentIndex()


if __name__ == '__main__':
app = QtGui.QApplication(sys.argv)
dialog_1 = Dialog_01()
dialog_1.show()
dialog_1.resize(480,320)
sys.exit(app.exec_())

最佳答案

这里是工作代码,显示了删除列表项的两种方法。谢谢大家!

from PyQt4 import QtGui, QtCore
import sys, os

class Dialog_01(QtGui.QMainWindow):
def __init__(self):
super(QtGui.QMainWindow,self).__init__()

myQWidget = QtGui.QWidget()
myBoxLayout = QtGui.QVBoxLayout()
myQWidget.setLayout(myBoxLayout)
self.setCentralWidget(myQWidget)

self.listWidgetA = QtGui.QListWidget()
for i in range(5):
QtGui.QListWidgetItem( 'Item '+str(i), self.listWidgetA )

self.listWidgetA.itemClicked.connect(self.item_clicked)

myBoxLayout.addWidget(self.listWidgetA)

myButtonA=QtGui.QPushButton("Delete Item Using Approach A")
myBoxLayout.addWidget(myButtonA)
myButtonA.clicked.connect(self.deleteItemA)

myButtonB=QtGui.QPushButton("Delete Item Using Approach B")
myBoxLayout.addWidget(myButtonB)
myButtonB.clicked.connect(self.deleteItemB)



def item_clicked(self, arg):
print '\n\t selectedItem', arg
print '\n\t indexFromItem', self.listWidgetA.indexFromItem(arg)


def deleteItemA(self):
item = self.listWidgetA.takeItem(self.listWidgetA.currentRow())
item = None


def deleteItemB(self):
model = self.listWidgetA.model()
for selectedItem in self.listWidgetA.selectedItems():
qIndex = self.listWidgetA.indexFromItem(selectedItem)
print 'removing : %s' %model.data(qIndex).toString()
model.removeRow(qIndex.row())


if __name__ == '__main__':
app = QtGui.QApplication(sys.argv)
dialog_1 = Dialog_01()
dialog_1.show()
dialog_1.resize(480,320)
sys.exit(app.exec_())

关于python - 如何从 QListWidget 中删除 ListWidget 项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22547264/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com