PDA

View Full Version : How to subclass QTableWidgetItem



codemonkey
4th October 2009, 10:04
Hi everyone.
I've managed to compile a program that uses a subclass to QTableWidgetItem, but there are still some issues that needs to be sorted out.

First here is the code


class QInt64Item : public QTableWidgetItem
{
public:
QInt64Item(qint64 data=0);
QVariant data(int role) const;
bool operator< ( const QInt64Item& other ) const;
protected:
qint64 m_data;
};


And here is the rest of the code



#include "qint64item.h"

QInt64Item::QInt64Item(qint64 data)
{
m_data = data;
this->setFlags(Qt::NoItemFlags);
this->setFlags(Qt::ItemIsEnabled);
this->setSelected(false);
}

QVariant QInt64Item::data(int role) const
{
if (role==Qt::EditRole)
return m_data;
else
return QString::number(m_data);
}

bool QInt64Item::operator< ( const QInt64Item& other ) const
{
return m_data < other.m_data;
}


And here I use it


QInt64Item* new64Item;
new64Item = new QInt64Item(my_int64_variable);
new64Item->setForeground(QBrush(Qt::black));
m_ui->MyTable->setItem(row, 0, new64Item);


I've attached what it lookslike (dump.jpeg) but I should add that I want all text to be aligned to the right, no checkboxes, and sorting does not sort numerically when clicking in the header.

So I'm very grateful for any hints on this issue :)

jpn
4th October 2009, 10:09
Hi,

You might want to start with revising Int64Item::data(). It makes no sense to return a QString for all the other roles than Qt::EditRole. There are such roles as Qt::SizeHintRole, Qt::CheckStateRole, Qt::DecorationRole, Qt::AlignmentRole etc... returning a QString for those might confuse Qt.

codemonkey
4th October 2009, 10:26
Thanks, it starts to look much better now that I've changed the code to this:



QVariant QInt64Item::data(int role) const
{
if (role==Qt::EditRole)
return m_data;
else if (role==Qt::CheckStateRole)
return Qt::Unchecked;
else if (role==Qt::DisplayRole)
return m_data;
else if (role==Qt::TextAlignmentRole)
return Qt::AlignRight;
else
return QTableWidgetItem::data(role);
}


But I cant find anything on how to get rid of the check box. My best guess is that it's a call to setFlags() but how?

jpn
4th October 2009, 11:47
Try returning QVariant() for Qt::CheckStateRole (or just remove the Qt::CheckStateRole block). Also, notice that setFlags() doesn't work this way:


item->setFlags(A);
item->setFlags(B); // overrides whatever was previously set

But it takes a combination flags:


item->setFlags(A | B);

codemonkey
4th October 2009, 12:11
Thanks, removing the block solved it.