如何将我的数据库插入我的QTableWidget表?

时间:2014-01-26 18:21:03

标签: python database sqlite pyqt4 qtablewidget

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.我如何在这里插入数据库并正确连接?

2 个答案:

答案 0 :(得分:1)

通过使用模型视图编程,解决此问题的更好解决方案。这是使用模型视图的解决方案。

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)

答案 1 :(得分:1)

Qt具有连接到数据库的现成的表模型。

检查

http://pyqt.sourceforge.net/Docs/PyQt4/qsqltablemodel.html

在PyQt安装中

site-packages\PyQt4\examples\sql(它在我的机器上安装的位置)文件夹。