我有一个QModel和QListview,显示了全局变量(列表)中的项。通过向其中添加项目来更新此列表。我有两个问题:
installEvent
和@setter
进入列表,但不知道如何去做。from PyQt5 import QtWidgets, QtCore, QtGui
import sys
Mylist = ['Apple','Orange','lemon']
Quantity = ['5','2','7']
class Window(QtWidgets.QWidget):
def __init__(self, mylist, mylist2):
super(Window, self).__init__()
# mylist
self.mylist = mylist
self.mylist2 = mylist2
# layout
Layout = QtWidgets.QVBoxLayout(self)
# Model and listview
self.viewL = QtWidgets.QListView()
self.model = QtGui.QStandardItemModel()
"""Q1: How to make QStandardItemModel with a second column with header
e.g. headres['name', 'Quantity']
"""
# Add items
for Name in self.mylist:
item = QtGui.QStandardItem(Name)
item.setCheckable(True)
item.setCheckState(QtCore.Qt.Unchecked)
self.model.appendRow(item)
""" How to add from 2nd list to 2nd column
"""
# set the model
self.viewL.setModel(self.model)
#
button = QtWidgets.QPushButton('Add Item')
button.clicked.connect(self.onClick)
#
Layout.addWidget(self.viewL)
Layout.addWidget(button)
self.show()
def onClick(self, index):
self.mylist.append('mango')
self.mylist2.append('10')
""" How to emit a signal on on appending a list, then update the model and listview
"""
app=QtWidgets.QApplication(sys.argv)
window=Window(mylist=Mylist, mylist2=Quantity)
sys.exit(app.exec_())
答案 0 :(得分:1)
QListView仅支持一列,因此,如果要多列然后使用QTableView,则另一方面,无需创建信号来添加项目,只需将信息添加到模型中即可:>
from PyQt5 import QtWidgets, QtCore, QtGui
import sys
class Window(QtWidgets.QWidget):
def __init__(self, first_column, second_column, parent=None):
super(Window, self).__init__(parent)
self.view = QtWidgets.QTableView(
showGrid=False, selectionBehavior=QtWidgets.QAbstractItemView.SelectRows
)
self.view.horizontalHeader().setStretchLastSection(True)
self.model = QtGui.QStandardItemModel()
self.model.setHorizontalHeaderLabels(["name", "quantity"])
self.view.setModel(self.model)
for first_text, second_text in zip(first_column, second_column):
item_1 = QtGui.QStandardItem(first_text)
item_1.setCheckable(True)
item_1.setCheckState(QtCore.Qt.Unchecked)
item_2 = QtGui.QStandardItem(second_text)
self.model.appendRow([item_1, item_2])
button = QtWidgets.QPushButton("Add Item")
button.clicked.connect(self.onClick)
# layout
layout = QtWidgets.QVBoxLayout(self)
#
layout.addWidget(self.view)
layout.addWidget(button)
def onClick(self):
item_1 = QtGui.QStandardItem("mango")
item_1.setCheckable(True)
item_1.setCheckState(QtCore.Qt.Unchecked)
item_2 = QtGui.QStandardItem("10")
self.model.appendRow([item_1, item_2])
if __name__ == "__main__":
Mylist = ["Apple", "Orange", "lemon"]
Quantity = ["5", "2", "7"]
app = QtWidgets.QApplication(sys.argv)
window = Window(Mylist, Quantity)
window.show()
sys.exit(app.exec_())
``