qtablewidget中的空值

时间:2017-06-18 17:53:18

标签: postgresql python-3.x pyqt qtablewidget

我在PYQT5上开发了一个桌面应用程序,并集成了posgtresql。我偶然发现了表格没有显示值的情况:

looks like on screen

源代码:

def createTable(self):
    self.tableWidget = QTableWidget()

    conn = psycopg2.connect('host=localhost port=5432 dbname=postgres user=postgres password=12345678')

    cursor = conn.cursor()
    query = cursor.execute("SELECT * FROM wave_params")
    result = cursor.fetchall()
    for i in result:
        print(i)

    rows = len(result)
    columns = len(result[0])
    self.tableWidget.setColumnCount(columns)
    self.tableWidget.setRowCount(rows)

    index = 0
    while query != None:
        self.tableWidget.setItem(index,0, QTableWidgetItem(query.result[0]))
        # self.tableWidget.setItem(index, 1, QTableWidgetItem(str(query.value(1))))
        # self.tableWidget.setItem(index, 2, QTableWidgetItem(str(query.value(2))))
        index = index + 1



    # table selection change
    self.tableWidget.doubleClicked.connect(self.on_click)

@pyqtSlot()
def on_click(self):
    print("\n")
    for currentQTableWidgetItem in self.tableWidget.selectedItems():
        print(currentQTableWidgetItem.row(), currentQTableWidgetItem.column(), currentQTableWidgetItem.text())

我无法理解。问题是什么? 谢谢!

1 个答案:

答案 0 :(得分:0)

游标对象没有属性结果。 在您的代码中,结果是包含返回值cursor.fetchall()的元组列表,query是cursor.execute()的返回值。 cursor.execute()始终返回None (见documentation)。你只需要循环结果,这里有两个例子:

def createTable(self):
    self.tableWidget = QTableWidget(self)

    psycopg2.connect('host=localhost port=5432 dbname=postgres user=postgres password=12345678')

    cursor = conn.cursor()
    query = cursor.execute("SELECT * FROM ladestelle")
    result = cursor.fetchall()

    rows = len(result)
    columns = len(result[0])
    self.tableWidget.setColumnCount(columns)
    self.tableWidget.setRowCount(rows)

    for i, r in enumerate(result):
        self.tableWidget.setItem(i, 0, QTableWidgetItem(r[0]))
        self.tableWidget.setItem(i, 1, QTableWidgetItem(str(r[1])))
        self.tableWidget.setItem(i, 2, QTableWidgetItem(str(r[2])))
    '''
    # or simpler
    for r in range(rows):
        for c in range(columns):
            self.tableWidget.setItem(r, c, QTableWidgetItem(str(result[r][c])))
    '''

    self.tableWidget.doubleClicked.connect(self.on_click)