qwidget.render drawing with offset in QStyledItemDelegate
I'm trying to create a delegate to draw custom widgets as elements in a listview on icon mode. I have it more or less working but I can't get the widgets to draw in the right place, it seems they are getting drawn considering (0,0) the origin on the main window not the origin of t开发者_如何学Pythonhe list view. What do I need to pass to render the widget on the right place? I know I can pass an offset... how can I calculate the offset between the main window and the listview?
This is my paint method on my delegate (derived from QStyledItemDelegate)
def paint(self, painter, option, index):
painter.save()
if option.state & QStyle.State_Selected:
painter.fillRect(option.rect, option.palette.highlight());
model = index.model()
myWidget = model.listdata[index.row()]
myWidget.setGeometry(option.rect)
myWidget.render(painter, option.rect.topLeft() )
painter.restore()
Thanks
/J
In case this is useful for someone else I'll post my solution...
I don't know if this is the best way of doing it, but I'm calculating the offset by mapping the orgin of my parent to the main window:
offset = self._parent.mapTo(self._mainWindow, QPoint(0,0))
myWidget.render(painter, option.rect.topLeft() + offset)
It works, so I'll use it until I find a better way for doing this.
You can render your Widget into a temporary pixmap and then draw the pixmap instead. That solves the shift issue:
def paint(self, painter, option, index):
pic = QPixmap( option.rect.width(), option.rect.height() )
w = ItemWidget()
w.setGeometry( option.rect )
w.render(pic)
painter.drawPixmap( option.rect, pic )
I use another alternative method, and it works.
painter.translate(option.rect.topLeft())
myWidget.render(painter, QtCore.QPoint(0, 0))
精彩评论