htmldelegate.cpp 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. /*
  2. mephi-tasks — a client to NRNU MEPhI Redmine server
  3. Copyright (C) 2015 Dmitry Yu Okunev <dyokunev@ut.mephi.ru> 0x8E30679C
  4. */
  5. #include "htmldelegate.h"
  6. #include <QPainter>
  7. #include <QTextDocument>
  8. #include <QAbstractTextDocumentLayout>
  9. HTMLDelegate::HTMLDelegate()
  10. {
  11. }
  12. /*
  13. * The next code is an adapted copy of code from:
  14. * http://stackoverflow.com/questions/1956542/how-to-make-item-view-render-rich-html-text-in-qt
  15. *
  16. * Authors (in order of contribution decrease):
  17. * * serge-gubenko,
  18. * * satanas,
  19. * * Dmitry Yu Okunev <dyokunev@ut.mephi.ru>.
  20. *
  21. * The code is licensed by "CC BY-SA 3.0 with attribution required" according
  22. * to "stackoverflow.com"'s footer.
  23. *
  24. */
  25. void HTMLDelegate::paint ( QPainter* painter, const QStyleOptionViewItem & option, const QModelIndex &index ) const
  26. {
  27. QStyleOptionViewItemV4 options = option;
  28. initStyleOption ( &options, index );
  29. painter->save();
  30. QTextDocument doc;
  31. doc.setHtml ( options.text );
  32. options.text = "";
  33. options.widget->style()->drawControl ( QStyle::CE_ItemViewItem, &options, painter );
  34. // shift text right to make icon visible
  35. QSize iconSize = options.icon.actualSize ( options.rect.size() );
  36. painter->translate ( options.rect.left() + iconSize.width(), options.rect.top() );
  37. QRect clip ( 0, 0, options.rect.width() + iconSize.width(), options.rect.height() );
  38. //doc.drawContents(painter, clip);
  39. painter->setClipRect ( clip );
  40. QAbstractTextDocumentLayout::PaintContext ctx;
  41. // set text color to red for selected item
  42. //if (option.state & QStyle::State_Selected)
  43. // ctx.palette.setColor(QPalette::Text, QColor("red"));
  44. ctx.clip = clip;
  45. doc.documentLayout()->draw ( painter, ctx );
  46. painter->restore();
  47. }
  48. QSize HTMLDelegate::sizeHint ( const QStyleOptionViewItem & option, const QModelIndex & index ) const
  49. {
  50. QStyleOptionViewItemV4 options = option;
  51. initStyleOption ( &options, index );
  52. QTextDocument doc;
  53. doc.setHtml ( options.text );
  54. doc.setTextWidth ( options.rect.width() );
  55. return QSize ( doc.idealWidth(), doc.size().height() );
  56. }