我已经在这段代码上使用了几天,只是停留在如何从QLineEdit(list1)删除选定的行上。我知道通过使用QStandardModel可以使用removeRow()删除某个索引处的行,但是我似乎无法弄清楚如何确定所选行的特定索引。谢谢!
import sys
from PyQt5.QtWidgets import(QApplication,QListWidget,QTreeView,
QTreeWidget,QLabel,QLineEdit,QWidget, QPushButton,
QHBoxLayout,QVBoxLayout, QLineEdit, QListView)
from PyQt5.QtGui import QStandardItemModel, QStandardItem
class MainWindow(QWidget):
def __init__(self):
super().__init__()
self.setWindowTitle("CS2316 Help Desk Queue")
self.button1=QPushButton("Add",self,enabled=False)
self.button2=QPushButton("Remove",self,enabled=False)
self.LabelA=QLabel("TAs on duty")
self.text1=QLineEdit()
self.list1=QListView(self)
self.list1.resize(260,260)
self.list1.TopToBottom
self.LabelB=QLabel("Enter your Name")
self.model=QStandardItemModel(self.list1)
self.text2=QLineEdit()
if self.text2.textChanged[str]:
self.text2.textChanged[str].connect(lambda: self.button1.setEnabled(self.text2.text()!=""))
if self.list1.clicked:
self.list1.clicked.connect(lambda: self.button2.setEnabled(True))
self.button1.clicked.connect(self.add1)
self.button2.clicked.connect(self.remove)
hbox1 = QHBoxLayout()
hbox1.addWidget(self.LabelA)
hbox1.addWidget(self.text1)
vbox1=QVBoxLayout()
vbox1.addWidget(self.list1)
hbox2=QHBoxLayout()
hbox2.addWidget(self.LabelB)
hbox2.addWidget(self.text2)
vbox2=QVBoxLayout()
vbox2.addWidget(self.button1)
vbox2.addWidget(self.button2)
vbox=QVBoxLayout()
vbox.addLayout(hbox1)
vbox.addLayout(vbox1)
vbox.addLayout(hbox2)
vbox.addLayout(vbox2)
self.setLayout(vbox)
self.show()
def add1(self):
name=self.text2.text()
newname=QStandardItem(name)
self.model.appendRow(newname)
self.list1.setModel(self.model)
self.text2.clear()
def remove(self):
for index in range(self.model.rowCount()):
if self.list1.clicked:
self.model.removeRow(index)
self.list1.setModel(self.model)
if __name__ == '__main__':
app = QApplication(sys.argv)
main = MainWindow()
main.show()
sys.exit(app.exec_())
选择功能具有视图,因此您可以通过selectedIndexes()
方法获取所选行的QModelIndex,并且QModelIndex关联了可用于删除它的行号:
def remove(self):
indexes = self.list1.selectedIndexes()
if indexes:
index = indexes[0]
self.model.removeRow(index.row())