以数字方式排序QTableWidget项目
在使用PyQt4中的QTableWidget时,如果启用了排序功能,表格里的项目会被当作字符串来排序。
比如说,假设有一个变量是这样的:variable = [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)))
但是这样做并没有成功。我到底哪里出错了呢?
1 个回答
3
如果你想在 QtGui.QTableWidgetItem
的构造函数中传递任何变量,那这个变量必须是 QtCore.QString
或者是 Python 字符串。
要解决这个问题,你可以创建一个自定义的 QtGui.QTableWidgetItem
,然后实现一个检查小于的功能(在 Python 中,这个功能是 object.__lt__(self, other)
),具体做法是重写 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_())