我正在尝试对数字(float& int)进行排序,这些数字被格式化为添加$和逗号等,并在添加到QTableWidgetItem之前转换为QString。但是对这些列进行排序不起作用,因为排序基于字符串数据。有没有办法将数据显示为String,但基于底层整数/浮点值对其进行排序。我正在做如下的事情:
self.constituentsTableWidget.setSortingEnabled(False)
for i in xrange(p.getNumInstruments()):
employee = p.getEmployee(i)
item = QTableWidgetItem(QString(unicode('{}'.format(re.sub("(\d)(?=(\d{3})+(?!\d))", r"\1,", "%.2f" % employee.WorkDays)))))
self.constituentsTableWidget.setItem(i, cols['WorkDays'], item)
self.constituentsTableWidget.setSortingEnabled(True)
非常感谢任何帮助。
由于 拉胡
答案 0 :(得分:0)
我只是这样做,继承QtGui.QTableWidgetItem
并创建自己的。接下来,覆盖方法bool QTableWidgetItem.lt (self, QTableWidgetItem other)以比较您自己的情况;
示例强>
import re
import sys
import random
from PyQt4 import QtCore, QtGui
class QCustomTableWidgetItem (QtGui.QTableWidgetItem):
def __init__ (self, value):
super(QCustomTableWidgetItem, self).__init__(QtCore.QString('%.2f $' % value))
def __lt__ (self, other):
if (isinstance(other, QCustomTableWidgetItem)):
selfDataValue = float(re.sub(r'[ $]', '', str(self.data(QtCore.Qt.EditRole).toString())))
otherDataValue = float(re.sub(r'[ $]', '', str(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_())
希望是有帮助的;