Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on Jul 4th, 2012  |  syntax: None  |  size: 1.86 KB  |  hits: 25  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. How to use Qt Delegates for custom painting?
  2. def dragMoveEvent(self, event):
  3.     pos = event.pos()
  4.     item = self.myTreeWidget.itemAt(pos)
  5.  
  6.     # If hovered over an item during drag, set UserRole = 1
  7.     if item:
  8.         index = self.myTreeWidget.indexFromItem(item)
  9.         self.myTreeWidget.model().setData(index, 1, Qt.UserRole)
  10.  
  11.     # reset UserRole to 0 for all other indices
  12.     for i in range(self.myTreeWidget.model().rowCount()):
  13.         _index = self.myTreeWidget.model().index(i, 0)
  14.         if not item or index != _index:
  15.             self.myTreeWidget.model().setData(_index, 0, Qt.UserRole)
  16.  
  17.  
  18. class MyDelegate(QStyledItemDelegate):
  19.  
  20.     def paint( self, painter, option, index ):
  21.         QStyledItemDelegate.paint(self, painter, option, index)
  22.         painter.save()
  23.         data = index.model().data( index, Qt.UserRole ).toInt()
  24.             # if UserRole = 1 draw custom line
  25.         if data[1] and data[0] == 1:
  26.             line = QLine( option.rect.topLeft(), option.rect.topRight() )
  27.             painter.drawLine( line )
  28.         painter.restore()
  29.        
  30. class TestStyle : public QProxyStyle
  31. {
  32. public:
  33.     TestStyle(QStyle *baseStyle = 0) : QProxyStyle(baseStyle) {}
  34.  
  35.     void drawPrimitive(PrimitiveElement element, const QStyleOption *option, QPainter *painter, const QWidget *widget) const
  36.     {
  37.         if (element == QStyle::PE_IndicatorItemViewItemDrop)
  38.         {
  39.             //?? do nothing or do custom painting here
  40.         }
  41.         else
  42.         {
  43.             QProxyStyle::drawPrimitive(element, option, painter, widget);
  44.         }
  45.     }
  46. };
  47.  
  48. ..
  49.  
  50. ui->treeView->setStyle(new TestStyle(ui->treeView->style()));
  51.        
  52. class TestTreeView : public QTreeView
  53. {
  54. public:
  55.     explicit TestTreeView(QWidget *parent = 0) : QTreeView(parent) {}
  56.  
  57.     void paintEvent(QPaintEvent * event)
  58.     {
  59.         QPainter painter(viewport());
  60.         drawTree(&painter, event->region());
  61.     }
  62. };