PDA

View Full Version : QItemDelegate with QLabel for QTableView



Maxubuntu23
10th May 2010, 14:49
Hello!

Currently I'm developing a program with accesses a MySQL-database and with this I encountered one little Problem:

The program displays one table by using a QSqlQueryModel and a QTableView. There is one column which contains doubles. I want these doubles to be displayed via a QItemDelegate which contains a QLabel.

Here is my code:

Header

class LabelDelegate : public QItemDelegate
{
Q_OBJECT

public:
LabelDelegate(QObject* parent = 0);

QWidget* createEditor(QWidget *parent, const QStyleOptionViewItem& option, const QModelIndex& index) const;
void setEditorData(QWidget* editor, const QModelIndex& index) const;
};

Code

QWidget* LabelDelegate::createEditor(QWidget* parent, const QStyleOptionViewItem&, const QModelIndex&) const
{
QLabel* label = new QLabel(parent);

return label;
}

void LabelDelegate::setEditorData(QWidget* editor, const QModelIndex& index) const
{
double value = index.model()->data(index, Qt::EditRole).toInt();

QLabel* label = static_cast<QLabel*>(editor);

label->setText(QString::number(value) + " €");
}

Now I do this:

tableview->setItemDelegateForColumn(1, new LabelDelegate);

But the values are still displayed normally, I can't see the '€' Symbol.

Does anybody have an idea how to fix this?

Thanks!

MasterBLB
10th May 2010, 15:04
Yup.Reimplement the QItemDelegate:: paint() function,this one is responsible for drawing the content.
Besides,QLineEdit is a default editor created for QTableView,so reimplementing setEditorData and createEditor is unnecesary.

faldzip
10th May 2010, 17:25
items are displayed used paint() method in delegate. Editor is used for editing data - and QLabel is not good for this as you can't input data to it! Look at the Star Delegate example in Qt docs to get know how to use paint() and editor methods in delegate. You can Also inherit from QSqlTableModel and add euro char in data() method or implement proxy model which will add euro char to model's data.