Question

I'm creating a QTableWidget, displaying some information out of a Structure i've created. However, I only seem to be able to display Strings in the table, and not integers or doubles.

So as a solution, I casted my doubles and integers to Strings, and they display perfect in my table. But now I can't use the sortfunction properly, because it sorts the Strings alphabetically, and I want my integers to be sorted by value.

How it is now: 15 16 2 33 4 66 8 How it should be: 2 4 8 15 16 33 66

So basically, i'm looking for a way to add integers to my QTableView. Any ideas?

Here's my current code:

ui->tableWidget->setRowCount(lijst.size());
ui->tableWidget->setColumnCount(4);
ui->tableWidget->setColumnWidth(0,200);
QStringList TableHeader;
TableHeader<<"Object"<<"Frames"<<"Views"<<"Percent";
ui->tableWidget->setHorizontalHeaderLabels(TableHeader);

for(int i = 0; i< lijst.size();i++)
{
    ui->tableWidget->setItem(i, 0, new QTableWidgetItem(lijst[i].name));
    ui->tableWidget->setItem(i, 1, new QTableWidgetItem(tr("%1").arg(lijst[i].nroFrames));
    ui->tableWidget->setItem(i, 2, new QTableWidgetItem(tr("%1").arg(lijst[i].nroViews)));
    ui->tableWidget->setItem(i, 3, new QTableWidgetItem(tr("%1").arg(lijst[i].percent)));
}

Thanks!

Was it helpful?

Solution

You can implement your own QTableWidget item that will handle comparison in a special way. For example:

class TableItem : public QTableWidgetItem
{
public:
    TableItem(const QString & text)
        :
            QTableWidgetItem(text)
    {}

    TableItem(int num)
        :
            QTableWidgetItem(QString::number(num))
    {}

    bool operator< (const QTableWidgetItem &other) const
    {
        if (other.column() == 1) {
            // Compare cell data as integers for the second column.
            return text().toInt() < other.text().toInt();
        }
        return other.text() < text();
    }
};

With this, you will simply have to create TableItem instead of QTableWidgetItem:

ui->tableWidget->setItem(i, 1, new TableItem(tr("%1").arg(lijst[i].nroFrames));

or

ui->tableWidget->setItem(i, 1, new TableItem(lijst[i].nroFrames);

OTHER TIPS

Another option (easier I think) is to create an empty QTableWidgetItem and then set the data:

QTableWidgetItem *theItem = new QTableWidgetItem();
int myNumber = 43;
theItem->setData(Qt::EditRole, myNumber); //Accepts a QVariant
theTableWidget->setItem(0, 0, theItem); 

Please, don't use QTablewidgetItem or QTableWidget, instead use QTableView and QAbstractTableModel - the maintenance cost is way smaller and the code is saner.

classes:

  • YourTableView - the raw data
  • YourSortModel - the model that will do the sorting / filtering
  • QTableView - that will display your stff.

It's hard to initiate on the Model View on Qt, but as soon as you understand the basics you won't go back to manually dealling with the widgets.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top