Python Qt:用户定义对象的列表
我想使用Qt为用户定义的对象集合提供一个图形界面。例如,我可能有以下python类Python Qt:用户定义对象的列表,python,qt,Python,Qt,我想使用Qt为用户定义的对象集合提供一个图形界面。例如,我可能有以下python类 class Person(object): def __init__(self, name, age): self.name = name self.age = age 以及实例的链接列表 people = [Person('John', 60), Person('Laura', 33)] 现在,我想使用Qt来显示人物中元素的可浏览列表。也许我想允许当用户单击列表中的人
class Person(object):
def __init__(self, name, age):
self.name = name
self.age = age
以及实例的链接列表
people = [Person('John', 60), Person('Laura', 33)]
现在,我想使用Qt来显示人物
中元素的可浏览列表。也许我想允许当用户单击列表中的人名时,某些信息显示在各种文本框中
Qt文档包含了一个与我自己的情况非常匹配的示例,但是本教程缺少两个关键的内容
谢谢我从未使用过Python,但我认为该端口保留了Qt处理MVC的基本方式。在这种情况下,我不确定Qt的文档有多少改进,特别是在
QListView
中。在Qt的MVC中,您可以自由地使用任何您想要的作为存储数据的底层数据结构。您提供的(这是关键)是基本函数(在QAbstractListModel
中为纯虚拟函数),这些函数告诉QListView如何访问数据,并在需要时修改数据。您还需要实现一个基本函数rowCount
,这是不言自明的
当您在
QAbstractListModel
子类中实现了这些时,只需使用QListView::setModel
为QListView
设置模型,一切都应该正常工作。我给你的是C++,但我希望你能把它翻译成Python Qt,非常简单。 < p>下面的代码可以做我想做的。我使用Qt设计器创建了一个包含以下元素的ui
- firstNameLineEdit-QLineEdit:在此处输入一个人的名字
- lastNameLineEdit-QLineEdit:在此处输入一个人的姓氏
- addPersonButton-QPushButton:按此按钮可添加新的Person对象。从行编辑中检索名字和姓氏
- displayButton-QPushButton:将所有现有Person实例的列表打印到控制台以进行调试
- listView-QListView:显示Person对象名称的视图
import PyQt4.QtCore as QtCore
import PyQt4.QtGui as QtGui
import PyQt4.uic as uic
import sys
class Person(object):
def __init__(self, firstName, lastName):
self.firstName = firstName
self.lastName = lastName
class MyWidget(QtGui.QMainWindow):
def __init__(self, people):
QtGui.QMainWindow.__init__(self)
uic.loadUi('MyWidget.ui', self)
self.people=people
self.addPersonButton.clicked.connect(self.addPerson)
self.displayButton.clicked.connect(self.display)
self.model = simpleModel(self.people)
self.listView.setModel(self.model)
self.show()
def display(self):
for i,p in enumerate(self.people):
print "Person %i: %s %s"%(i, p.firstName, p.lastName)
def addPerson(self):
firstName = str(self.firstNameLineEdit.text())
lastName = str(self.lastNameLineEdit.text())
p = Person(firstName, lastName)
self.model.insertRow(p)
class simpleModel(QtCore.QAbstractListModel):
def __init__(self, dataList, parent=None):
super(simpleModel, self).__init__(parent)
self.list = dataList
def rowCount(self, parent=QtCore.QModelIndex()):
return len(self.list)
def insertRow(self, data, parent=QtCore.QModelIndex()):
self.beginInsertRows(parent, self.rowCount(), self.rowCount())
self.list.append(data)
self.endInsertRows()
def data(self, index, role):
if role == QtCore.Qt.DisplayRole:
person = self.list[index.row()]
return QtCore.QVariant("%s %s"%(person.firstName,person.lastName))
elif role == QtCore.Qt.UserRole:
person = self.list[index.row()]
return person
return QtCore.QVariant()
def main():
people=[Person('John','Doe')]
app = QtGui.QApplication(sys.argv)
ex = MyWidget(people)
sys.exit(app.exec_())
if __name__ == '__main__':
main()
谢谢,这很有用。我认为通过使用QabStretchListModel,我可以解决这个问题。如果我得到了一些工作,我会张贴在这里的来源。如果有人会在C++中为QT页面写一个例子,那也会很好。