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 e
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
class MainWindow(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()
def populate(self):
nrows, ncols = 5, 2
self.table_widget.setSortingEnabled(False)
self.table_widget.setRowCount(nrows)
self.table_widget.setColumnCount(ncols)
for i in range(nrows):
for j in range(ncols):
item = QtGui.QTableWidgetItem('%s%s' % (i, j))
self.table_widget.setItem(i, j, item)
self.updateSignal.emit()
self.table_widget.setSortingEnabled(True)
def update_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_())