2016-08-01 86 views
0

我試圖從查詢中添加數據到pyqt中的表部件,但我很難讓它把所有的行都放進去。現在我的代碼只返回數據的第一列和第三列他們!真的可以在這裏使用一些幫助! 共有5列和7055行Python PyQt和Psycopg2與TableWidget

我的代碼:

import psycopg2 
from PyQt4 import QtCore, QtGui 

def populate(self): 
con = psycopg2.connect("dbname=postgres user=username host=servername password=passowrd") 
cur = con.cursor() 
cur.execute("""SELECT * FROM doarni.bins_v2""") 
data = cur.fetchall() 
a = len(data) #rows 
b = len(data[0]) #columns 
self.ui.tableWidget.setSortingEnabled(True) 
self.ui.tableWidget.setRowCount(a) 
self.ui.tableWidget.setColumnCount(b) 
self.ui.tableWidget.setHorizontalHeaderLabels(['column1', 'column2', 'column3', 'column4', 'column5']) 
i = 1 #row 
j = 0 #column 
for j in range(a): 
    for i in range(b): 
     item = QtGui.QTableWidgetItem(data[j][i]) 
     self.ui.tableWidget.setItem(j, i, item) 
self.ui.tableWidget.sortByColumn(0, QtCore.Qt.DescendingOrder) 

回答

-1

試試這個代碼也被配置爲顯示Unicode字符串:

rows = cur.fetchall() 
self.tableWidget.setRowCount(len(rows)) 
qs=QtCore.QString() 
r=0 
for row in rows: 
    r=r+1 
    col= 0 
    for itm in row: 
     if type(itm)==type('a'): 
      item = qs.fromUtf8(itm, size=-1) 
      qs=QtCore.QString() 
     else: 
      item = str(itm) 
     self.tableWidget.setItem(r, col, QtGui.QTableWidgetItem(item)) 
     col = col+1