qtablewidget 中的空值

Null values in qtablewidget

我在 PYQT5 上开发了一个集成了 posgtresql 的桌面应用程序。我偶然发现 table 不显示值的情况:

源代码:

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())

我看不懂。问题是什么? 谢谢!

光标对象没有属性结果。 在您的代码结果中是一个包含 cursor.fetchall() 的 return 值的元组列表,查询是 cursor.execute() 的 return 值。 cursor.execute() return 总是 None (参见 documentation)。你只需要循环结果,这里有 2 个例子:

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)