problem with the Sorting in a QTableWidget

0

I'm putting together a table with QTableWidget in PyQt5 ..

I set the sortingEnabled to True , but the problem is that it does not sort the numbers well.

For example, if I'm 20, 201 and 30, sort them as follows:

descendente: 30, 201, 20

ascendente: 20, 201, 30

Code:

    self.tabla = QTableWidget()
    self.tabla.setColumnCount(6)
    self.tabla.setRowCount(1)
    self.tabla.setShowGrid(True)
    self.tabla.setHorizontalHeaderLabels(('Venta','Marca','Plataforma','Cantidad','Valor','Fecha'))
    self.tabla.setStyleSheet('background-color:#d6f9ff; border-radius: 20px; border: 2px solid gray;')
    self.tabla.horizontalHeader().setSectionResizeMode(0, QHeaderView.ResizeToContents)
    self.tabla.horizontalHeader().setSectionResizeMode(1, QHeaderView.Stretch)
    self.tabla.horizontalHeader().setSectionResizeMode(2, QHeaderView.Stretch)
    self.tabla.horizontalHeader().setSectionResizeMode(3, QHeaderView.ResizeToContents)
    self.tabla.horizontalHeader().setSectionResizeMode(4, QHeaderView.ResizeToContents)
    self.tabla.horizontalHeader().setSectionResizeMode(5, QHeaderView.ResizeToContents)
    self.tabla.setSelectionMode(QAbstractItemView.SingleSelection)
    self.tabla.setEditTriggers(self.tabla.NoEditTriggers)
    self.tabla.setSortingEnabled(True)
    self.tabla.verticalHeader().hide()
    layout.addWidget(self.tabla,2,0,1,10)

    check_table()
    row_count = 1
    for index, row in enumerate(get_all_ventas()):
        self.tabla.setRowCount(row_count)
        for index2, attr in enumerate(row):
            self.tabla.setItem(index,index2,QTableWidgetItem(str(attr)))
        row_count += 1

For me the problem is that actually the numbers are strings , the issue is that if I add them to the table as int , the table does not show them .. What should I do?

    
asked by ffaa00 14.11.2018 в 18:36
source

1 answer

0

Extracted from SO in English

On the line you enter the QTableWidgetItem : self.tabla.setItem(index,index2,QTableWidgetItem(str(attr)))

You can do the following:

qtwi = QTableWidgetItem()
qtwi.setData(Qt.EditRole, QVariant(index2))
self.tabla.setItem(index, index2, qtwi)

As you comment the problem lies in that when adding the element as a string will treat it as such, to treat it as a data you have to use the setData .

    
answered by 21.11.2018 / 09:47
source