Skip to content Skip to sidebar Skip to footer

Python Pyqt - Qtablewidget, Json, And Emitsignal Causing Blank Cells

I am using PyQt for a simple application that reads from a log file with JSON formatted strings, and outputs them nicely in a table. Everything is working as expected except when

Solution 1:

I think solution is to disable sorting while populating table by calling QTableWidget.setSortingEnabled(False), and then restore sorting.

Example code:

#!/usr/bin/env python# -*- coding: utf-8 -*-import sys
from PyQt4 import QtCore, QtGui

classMainWindow(QtGui.QWidget):
    updateSignal = QtCore.pyqtSignal()
    def__init__(self, parent=None):
        super(MainWindow, self).__init__(parent)
        self.table_widget = QtGui.QTableWidget()
        self.button = QtGui.QPushButton('Populate')
        self.button.clicked.connect(self.populate)
        layout = QtGui.QVBoxLayout()
        layout.addWidget(self.table_widget)
        layout.addWidget(self.button)
        self.setLayout(layout)
        self.updateSignal.connect(self.update_table)
        self.populate()

    defpopulate(self):
        nrows, ncols = 5, 2
        self.table_widget.setSortingEnabled(False)
        self.table_widget.setRowCount(nrows)
        self.table_widget.setColumnCount(ncols)
        for i inrange(nrows):
            for j inrange(ncols):
                item = QtGui.QTableWidgetItem('%s%s' % (i, j))
                self.table_widget.setItem(i, j, item)
        self.updateSignal.emit()
        self.table_widget.setSortingEnabled(True)

    defupdate_table(self):
        self.table_widget.sortItems(0,QtCore.Qt.DescendingOrder)


if __name__ == "__main__":
    app = QtGui.QApplication(sys.argv)
    wnd = MainWindow()
    wnd.resize(640, 480)
    wnd.show()
    sys.exit(app.exec_())

Solution 2:

I've been working on something similar, but was not setting up a sort. I tried both ways, and both worked for me.

My list, is a list of dictionaries, so slightly different from yours.

I have created a tabledialog class, that contains my table widget, and this function, is called from my main window:

defsetuptable(self, alist):

    # setup variables
    rows = len(alist)
    cols = len(alist[0])
    keys = ['number', 'name', 'phone', 'address'] # for dictonary order# setup cols, rows
    self.tableWidget.setRowCount(rows)
    self.tableWidget.setColumnCount(cols)

    # insert datafor row inrange(rows):
        for col inrange(cols):
            item = QtGui.QTableWidgetItem()
            item.setText(alist[row][keys[col]] or'') # or '' for any None values
            table.setItem(row, col, item)

    keys = [item.title() for item in keys]  # capitalize
    self.tableWidget.setHorizontalHeaderLabels(keys) # add header names
    self.tableWidget.horizontalHeader().setDefaultAlignment(QtCore.Qt.AlignLeft) # set alignment
    self.tableWidget.resizeColumnsToContents() # call this after all items have been inserted

    self.tableWidget.sortItems(1,QtCore.Qt.AscendingOrder)

Also tried using, at the end of my tablesetup function:

self.emit(QtCore.SIGNAL("loadingDone"))

and setup the slot in my main window, in the init section:

# setup the dialogimport dialogtable
self.tabledialog = dialogtable.dialogtable()

# signal from table dialog
self.tabledialog.connect(self.tabledialog,QtCore.SIGNAL("loadingDone"),self.tableSort)

And the function called:

deftableSort(self):
    self.tabledialog.tableWidget.sortItems(1,QtCore.Qt.AscendingOrder)

My tablewidget setup functions:

# set table widget attributesself.tableWidget.setEditTriggers(QtGui.QAbstractItemView.DoubleClicked) # use NoEditTriggers to disable editingself.tableWidget.setAlternatingRowColors(True)
    self.tableWidget.setSelectionMode(QtGui.QAbstractItemView.NoSelection)
    self.tableWidget.verticalHeader().setDefaultSectionSize(18) # tighten up the row sizeself.tableWidget.horizontalHeader().setStretchLastSection(True) # stretch last column to edgeself.tableWidget.setSortingEnabled(True) # allow sorting

I don't bother ever set sorting to false, as the answer above mine recommends.

Post a Comment for "Python Pyqt - Qtablewidget, Json, And Emitsignal Causing Blank Cells"