class Table(QtGui.QDialog):
def __init__(self, parent=None):
super(Table, self).__init__(parent)
layout = QtGui.QGridLayout()
self.table = QtGui.QTableWidget()
self.table.setRowCount(20)
self.table.setColumnCount(3)
layout.addWidget(self.table)
self.enterDataInTable()
self.setLayout(layout)
def enterDataInTable(self):
for row in range(0,20):
for column in range(0,3):
self.table.setItem(row, column, QtGui.QTableWidgetItem("cell %s-%s"%(row+1,column+1)))
此代码生成一个表,20行和3列,每一个内的数据告诉我它的位置。 我想,而不是有我的数据库列和行标题,里面包括他们的信息。 这将是使用SQLite 3.我将如何能够在这里插入数据库,并适当地连接呢?
Qt拥有连接到数据库准备使用的tablemodels。
校验
http://pyqt.sourceforge.net/Docs/PyQt4/qsqltablemodel.html
和site-packages\PyQt4\examples\sql
在PyQt的安装(这就是它的安装在我的机器上)的文件夹。
那么一个更好的解决方案来解决这个问题是通过使用模型视图编程。 下面是使用模型视图中的溶液。
class MyTableModel(QtCore.QAbstractTableModel):
def __init__(self,dbDir,parent=None):
QtCore.QabstractTableModel.__init__(self,parent)
dbConnection = sqlite3.connect(dbDir,isolation_level=None)
cursor=dbConnection.cursor()
dbConnection.execute("""SELECT * FROM tablename""")
data=cursor.fetchall()
data =[[]]
count1=0
for i in data:
count2 = 0
for x in i:
data[count1][count2] =x
count2 +=1
self.__data=data
self.__header=[" First "," Second "," Thirdt " ]
def rowCount( self, parent ):
return len(self.__data)
def columnCount( self , parent ):
return len(self.__data[0])
def flags( self,index):
return QtCore.Qt.ItemIsEnabled |QtCore.Qt.ItemIsSelectable
def data ( self , index , role ):
if role == QtCore.Qt.DisplayRole:
row = index.row()
column = index.column()
value = self.__data[row][column]
return value.name()
def headerData(self , section , orientation , role):
if role == QtCore.Qt.DisplayRole:
if orientation == QtCore.Qt.Horizontal:
return self.__header[section]
class Table(QtGui.QDialog):
def __init__(self, parent=None):
super(Table, self).__init__(parent)
layout = QtGui.QGridLayout()
self.MyTableMModel = MyTableModel(table_directory) # pass directory in which table exists
self.table = QtGui.QTableView()
self.table.setModel(self.MyTableModel)
layout.addWidget(self.table)
self.setLayout(layout)