2014-01-26 53 views
0
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.我將如何能夠插入數據庫並適當地連接它?如何將我的數據庫插入到我的QTableWidget表中?

回答

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) 
+0

不需要重新發明輪子:http://pyqt.sourceforge.net/Docs/PyQt4/qsqltablemodel.html – sebastian

+0

@sebastian:真的,它只是我以前沒有用過它。所以給了我所知道的解決方案。 – TheCreator232

相關問題