PDA

View Full Version : Problem with QItemDelegate



chandan
15th April 2010, 13:55
Hi everyone,
How can I change the size of the font of the item in a list using QItemDelegate's paint method? I have tried to change the painter font in the paint method but it is not reflecting the changes in the list view.
Please help me.
Thanks in advance.

Lykurg
15th April 2010, 14:12
Can we see your code? Without it is hard to tell. Use QStyleOptionViewItem and set the font there.

chandan
15th April 2010, 14:15
Thanks for your reply.
Here is my code and I want to change the font using painter of the paint method. Is it possible please?
void CCameraUICustomDelegate::paint(QPainter *painter,
const QStyleOptionViewItem &option,
const QModelIndex &index) const{
QVariant variant = index.data();
/*QPainter *qPainter = new QPainter;*/
//QString stringData = variant.toString();
painter->save();
painter->setFont(QFont("Times", 30, QFont::Bold));
painter->restore();

QStyledItemDelegate::paint(painter,option,index);
}

Lykurg
15th April 2010, 14:21
With save and restore everything in between is lost! So your code wont work. Try
painter->setFont(QFont("Times", 30, QFont::Bold));
QStyledItemDelegate::paint(painter,option,index);
If that does not work, alter as told option.

Lykurg
15th April 2010, 14:23
Ehm, and did you try QWidget::setFont() on your QListView/QListWidget?

chandan
15th April 2010, 14:25
Still it is not working. Is there any other way to do that please?

chandan
15th April 2010, 14:29
May be in the future I have to make some more changes in my list. That's why I have to subclass QStyledDelegate. So I have to change the font in the paint method.

Lykurg
15th April 2010, 14:35
So did you alter option? And you can alternatively draw all yourself without calling the base function. Then you can change the painter like you want.

chandan
15th April 2010, 14:42
I did alter option but didn't work. I will try to implement the whole function myself. Anyway thanks for your help.

Lykurg
15th April 2010, 15:04
Well, to be honest, I don't think you have really tried it, because it works fine. It is more likely you use wrong code. But without seeing anything.... The simple setFont solution with a custom delegate works perfect:
#include <QtGui>

class delegate : public QStyledItemDelegate
{
public:
delegate(QObject* parent = 0) : QStyledItemDelegate(parent)
{}

void paint(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const
{
QStyledItemDelegate::paint(painter, option, index);
}
};

int main(int argc, char* argv[])
{
QApplication a(argc, argv);

QStringList list;
list << "a" << "b" << "c";

QListWidget w;
w.setFont(QFont("Courier", 30));
delegate d;
w.setItemDelegate(&d);
w.addItems(list);
w.show();

QListView lv;
lv.setFont(QFont("Courier", 30));
lv.setItemDelegate(&d);
QStringListModel m;
m.setStringList(list);
lv.setModel(&m);
lv.show();


return a.exec();
}