你需要的是QSqlTableModel,使用ListView而不是ListWidget。所以您只需使用数据库文件加载模型并将模型连接到ListView。然后在listView中,使用setModelColumn()函数设置要在视图中显示的模型列。在
这里有一个你可以做的例子。在from PyQt4 import QtCore, QtGui,QtSql
import os
try:
_fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
_fromUtf8 = lambda s: s
CONFIG_DATABASE_PATH = "./"
CONFIG_DATABASE_NAME = "comboboxexample.db"
class Ui_Form(object):
def setupUi(self, Form):
Form.setObjectName(_fromUtf8("Form"))
Form.resize(640, 480)
filename = os.path.join(CONFIG_DATABASE_PATH,CONFIG_DATABASE_NAME)
self.db = QSqlDatabase.addDatabase("QSQLITE")
self.db.setDatabaseName(filename)
self.model = QtSql.QSqlTableModel(self, self.db)
self.model.setTable('items') # enter the table name
self.model.setEditStrategy(QtSql.QSqlTableModel.OnManualSubmit)
self.splitter = QtGui.QSplitter(Form)
self.splitter.setGeometry(QtCore.QRect(10, 30, 621, 441))
self.splitter.setOrientation(QtCore.Qt.Horizontal)
self.splitter.setObjectName(_fromUtf8("splitter"))
self.listView = QtGui.QListView(self.splitter)
self.listView.setObjectName(_fromUtf8("listView"))
self.listView.setModel(self.model)
# enter the column number which you want to display
self.listView.setModelColumn(1)
self.textEdit = QtGui.QTextEdit(self.splitter)
self.textEdit.setObjectName(_fromUtf8("textEdit"))
self.retranslateUi(Form)
QtCore.QObject.connect(self.listView, QtCore.SIGNAL("clicked(QModelIndex)"),self.ListClicked_2)
QtCore.QMetaObject.connectSlotsByName(Form)
def retranslateUi(self, Form):
Form.setWindowTitle(QtGui.QApplication.translate("Form", "Form", None, QtGui.QApplication.UnicodeUTF8))
def ListClicked_2( self, qmodelindex ):
# then take the data from the model and display it in the textEdit
self.textEdit.setText(qmodelindex.data(QtCore.Qt.DisplayRole).toString())