Reputation:
I am stuck on how to remove a selected row from the QLineEdit (list1). I understand that by using QStandardModel I can use removeRow() to remove a row at a certain index, but I can't seem to figure out how to determine the specific index of the selected row.
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_())
Upvotes: 1
Views: 441
Reputation: 243983
The selection feature has the view so you can get the QModelIndex of the selected rows through selectedIndexes()
method, and the QModelIndex has associated the row number that can be used to remove it:
def remove(self):
indexes = self.list1.selectedIndexes()
if indexes:
index = indexes[0]
self.model.removeRow(index.row())
Upvotes: 1