2014-12-31 33 views
0

自2008年从诺Dielmann PyQt的邮件列表上的以下问题一直没有得到答复:如何在QStyledItemDelegate中绘制样式化的焦点矩形?

[..] 我有一个QStyledItemDelegate子类实现paint()来得出一些QTableView中单元格的内容。如果其中一个单元格获得了焦点,如何使它绘制焦点矩形?我试过这个:

class MyDelegate(QStyledItemDelegate): 
    ... 
    def paint(self, painter, option, index): 
     ... 
     painter.save() 
     if option.state & QStyle.State_HasFocus: 
      self.parent().style().drawPrimitive(QStyle.PE_FrameFocusRect, option, painter) 
     ... 
     painter.restore() 

但是这根本就没有做什么。没有错误,没有焦点框架。我只想让QStyle系统以某种方式绘制通常的对焦框,如果我的自定义绘制的单元格中有一个具有焦点。 QStyle文档告诉我创建一个QStyleOptionFocusRect并使用initFrom()。但initFrom()需要一个QWidget,在这种情况下我没有。

我只是不明白。

什么是平常的方式来获得焦点帧通过自定义代表涂QTableView中的细胞?[..]

回答

0

我遇到了同样的问题。经过很多挫折之后,我发现答案被埋在了弃用的QStyledItem类中。下面是基于该代码的PyQt/PySide解决方案:

class MyDelegate(QtGui.QStyledItemDelegate): 
    ... 
    def drawFocus(self, painter, option, rect, widget=None): 
     if (option.state & QtGui.QStyle.State_HasFocus) == 0 or not rect.isValid(): 
      return 
     o = QtGui.QStyleOptionFocusRect() 
     # no operator= in python, so we have to do this manually 
     o.state = option.state 
     o.direction = option.direction 
     o.rect = option.rect 
     o.fontMetrics = option.fontMetrics 
     o.palette = option.palette 

     o.state |= QtGui.QStyle.State_KeyboardFocusChange 
     o.state |= QtGui.QStyle.State_Item 
     cg = QtGui.QPalette.Normal if (option.state & QtGui.QStyle.State_Enabled) else QtGui.QPalette.Disabled 
     o.backgroundColor = option.palette.color(cg, QtGui.QPalette.Highlight if (option.state & QtGui.QStyle.State_Selected) else QtGui.QPalette.Window) 
     style = widget.style() if widget else QtGui.QApplication.style() 
     style.drawPrimitive(QtGui.QStyle.PE_FrameFocusRect, o, painter, widget) 

    def paint(self, painter, option, index): 
     painter.save() 
     # ... draw your delegate here, or call your widget's render method ... 
     painter.restore() 

     painter.save() 
     # omit the last argument if you're not drawing a widget 
     self.drawFocus(painter, option, option.rect, widget) 
     painter.restore()