在QtableWidget中显示数据库中的数据

时间:2017-03-13 11:16:40

标签: python postgresql qtablewidget

我有这个代码gui QtableWidget

from PyQt4.QtCore import *

from PyQt4.QtGui import *
import sys
data = {'col1':['1','2','3'], 'col2':['4','5','6'], 'col3':['7','8','9']}

class MyTable(QTableWidget):
def __init__(self, data, *args):
    QTableWidget.__init__(self, *args)
    self.data = data
    self.setmydata()
    self.resizeColumnsToContents()
    self.resizeRowsToContents()

def setmydata(self):

    horHeaders = []
    for n, key in enumerate(sorted(self.data.keys())):
        horHeaders.append(key)
        print key
        for m, item in enumerate(self.data[key]):
            newitem = QTableWidgetItem(item)
            self.setItem(m, n, newitem)
    self.setHorizontalHeaderLabels(horHeaders)

def main(args):
app = QApplication(args)
table = MyTable(data, 5, 3)
table.show()
  sys.exit(app.exec_())

if __name__=="__main__":
main(sys.argv)

谁显示这个 enter image description here 我有这个代码

import psycopg2
conn = psycopg2.connect(database="sammy", user="postgres", password="a",      host="localhost", port="5432")
print "Opened database successfully"
cur = conn.cursor()
cur.execute("SELECT * from conn")
rows = cur.fetchall()
for row in rows:
   print "ID = ", row[0]
   print "NAME = ", row[1]
   print "password = ", row[2] ,"\n"

谁从数据库显示此数据

enter image description here

我是python中的初学者 我想在QtableWidget中显示seconde数据 我应该在第一个代码中改变什么来进行数据显示或其他方式

非常感谢

1 个答案:

答案 0 :(得分:2)

[您可以从SQL结果中构建数据字典。只是模仿示例中的列表字典

import psycopg2
conn = psycopg2.connect(database="sammy", user="postgres", password="a",      host="localhost", port="5432")
print "Opened database successfully"
cur = conn.cursor()
cur.execute("SELECT * from conn")
rows = cur.fetchall()

ID,NAME,password = [],[],[]
for row in rows:
   ID = ID + [row[0]]
   NAME = NAME + [row[1]]
   password = password + [row[2]]

然后修改QTableWidget代码

data = {'col1':['1','2','3'], 'col2':['4','5','6'], 'col3':['7','8','9']}
是的 data = {'ID':ID, 'NAME':NAME, 'password':password}