Hello,

I'm overloading the QStyledItemDelegate::paint() function to enable the display of text and/or icons (depending on user preference) in a table column. I have the feature working exactly as I intended. However, getting the text and icons to align with the other data in the row required me to add / subtract pixels from the rect position (denoted by the "Offset" variables in the code below).

I suppose this will work, but it makes me nervous, as I fear I may have implemented a device-dependent solution, thus different video cards or platforms may render everything differently, making my adjustments worthless. Is there a device independent way to match the alignment of painted text / graphics to the alignemnt of values of the adjacent cells? Or can anyone assuage my fears that my approach is going to be ok, regardless of platform / video hardware?

Obligatory code:

Qt Code:
  1. void CSVWorld::RecordStatusDelegate::paint (QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const
  2. {
  3. painter->save();
  4.  
  5. QFont font = QApplication::font();
  6. font.setPointSize(10);
  7.  
  8. QFontMetrics fm(font);
  9.  
  10. QString text = "";
  11. QIcon *icon = 0;
  12.  
  13. switch (index.data().toInt())
  14. {
  15. //ICON SELECTION LOGIC HERE
  16. }
  17.  
  18. QRect textRect = option.rect;
  19. QRect iconRect = option.rect;
  20. int displayables = 0;
  21.  
  22. //for icon-only (1), default option.rect centers icon left-to-right
  23. //otherwise, size option.rect to fit the icon, forcing left-alignment with text
  24.  
  25. iconRect.setTop (iconRect.top() + mIconTopOffset); //device-dependent?
  26. iconRect.setBottom (iconRect.top() + mIconSize);
  27.  
  28. if (displayables == 0 && (icon) )
  29. {
  30. iconRect.setRight (iconRect.left() + mIconSize);
  31. textRect.setLeft (iconRect.right() + (mIconSize/4) * 3);
  32. textRect.setRight (textRect.left() + fm.width(text));
  33. }
  34. else
  35. textRect.setLeft (textRect.left() + mTextLeftOffset ); //device-dependent?
  36.  
  37. textRect.setTop (textRect.top() + ((option.rect.height() - fm.height()) / 2) + mTextTopOffset); //device-dependent?
  38.  
  39. if (displayables == 0 || displayables == 1)
  40. {
  41. if (icon)
  42. painter->drawPixmap(iconRect.center(),icon->pixmap(mIconSize, mIconSize));
  43. }
  44.  
  45. // icon + text or text only, or force text if no icon exists for status
  46. if (displayables == 0 || displayables == 2 || !(icon) )
  47. {
  48. painter->setFont(font);
  49. painter->drawText(textRect,text);
  50. }
  51.  
  52. painter->restore();
  53.  
  54. }
To copy to clipboard, switch view to plain text mode