启用排序时,在PyQt4中使用QTableWidget,项目按字符串排序。
变量= [1,2,3,4,5,11,22,33]
生成订单
1 11 2 22 3 33 4 5
我目前正在使用以下代码填写表格
tableWidgetData.setItem(0, 0, QtGui.QTableWidgetItem(variable))
我试过,因为我认为变量只是按字符串排序,因为它们是字符串
tableWidgetData.setItem(0, 0, QtGui.QTableWidgetItem(int(variable)))
但这不可能。我在哪里错了?
答案 0 :(得分:3)
如果有任何事情在QtGui.QTableWidgetItem
构造函数中传递变量,我必须QtCore.QString
只能进行python sring。
要解决此问题,请创建自定义QtGui.QTableWidgetItem
并通过object.__lt__(self, other)
覆盖小于(或我们知道在python中bool QTableWidgetItem.__lt__ (self, QTableWidgetItem other)
)的检查案例。
实施例
import sys
import random
from PyQt4 import QtCore, QtGui
class QCustomTableWidgetItem (QtGui.QTableWidgetItem):
def __init__ (self, value):
super(QCustomTableWidgetItem, self).__init__(QtCore.QString('%s' % value))
def __lt__ (self, other):
if (isinstance(other, QCustomTableWidgetItem)):
selfDataValue = float(self.data(QtCore.Qt.EditRole).toString())
otherDataValue = float(other.data(QtCore.Qt.EditRole).toString())
return selfDataValue < otherDataValue
else:
return QtGui.QTableWidgetItem.__lt__(self, other)
class QCustomTableWidget (QtGui.QTableWidget):
def __init__ (self, parent = None):
super(QCustomTableWidget, self).__init__(parent)
self.setColumnCount(2)
self.setRowCount(5)
for row in range(self.rowCount()):
self.setItem(row, 0, QCustomTableWidgetItem(random.random() * 1e4))
self.setItem(row, 1, QtGui.QTableWidgetItem(QtCore.QString(65 + row)))
self.setSortingEnabled(True)
myQApplication = QtGui.QApplication([])
myQCustomTableWidget = QCustomTableWidget()
myQCustomTableWidget.show()
sys.exit(myQApplication.exec_())