QItemDelegate with QLabel for QTableView
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
Code:
{
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
Code:
QWidget* LabelDelegate
::createEditor(QWidget* parent,
const QStyleOptionViewItem
&,
const QModelIndex
&) const {
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:
Code:
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!
Re: QItemDelegate with QLabel for QTableView
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.
Re: QItemDelegate with QLabel for QTableView
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.