2009-09-11 85 views
4

所以這裏的故事:定製QStyledItemDelegate:加入大膽的項目

我有一個使用QSqlQueryModel填滿它一個而QListView。因爲有些項目應該根據模型隱藏列的值以粗體顯示,所以我決定製作自己的自定義委託。我正在使用PyQT 4.5.4,因此繼承自QStyledItemDelegate是根據文檔去的方法。我得到了它的工作,但它有一些問題。

這裏是我的解決方案:

class TypeSoortDelegate(QStyledItemDelegate): 

    def paint(self, painter, option, index): 
     model = index.model() 
     record = model.record(index.row()) 
     value= record.value(2).toPyObject() 
     if value: 
      painter.save() 
      # change the back- and foreground colors 
      # if the item is selected 
      if option.state & QStyle.State_Selected: 
       painter.setPen(QPen(Qt.NoPen)) 
       painter.setBrush(QApplication.palette().highlight()) 
       painter.drawRect(option.rect) 
       painter.restore() 
       painter.save() 
       font = painter.font 
       pen = painter.pen() 
       pen.setColor(QApplication.palette().color(QPalette.HighlightedText)) 
       painter.setPen(pen) 
      else: 
       painter.setPen(QPen(Qt.black)) 

      # set text bold 
      font = painter.font() 
      font.setWeight(QFont.Bold) 
      painter.setFont(font) 
      text = record.value(1).toPyObject() 
      painter.drawText(option.rect, Qt.AlignLeft, text) 

      painter.restore() 
     else: 
      QStyledItemDelegate.paint(self, painter, option, index) 

我現在面臨的問題是:

  1. 正常(非粗體)項目是 稍微縮進(幾個像素)。 這可能是一些默認的 行爲。我可以在 中縮進我的物品,但是在不同的平臺下會發生什麼,然後 ?
  2. 正常情況下,當我選擇項目時,周圍有一個帶有虛線的小邊框(默認Windows的東西?)。這裏我也可以畫出來,但我想盡可能保持原樣。

現在的問題:

是否有另一種方法來創建一個自定義的委託,只有當改變某些條件得到滿足的字體粗細和葉所有其餘不變?

我也試過:

if value: 
    font = painter.font() 
    font.setWeight(QFont.Bold) 
    painter.setFont(font) 
QStyledItemDelegate.paint(self, painter, option, index) 

但是,這似乎並沒有影響到外觀都沒有。沒有錯誤,只是默認行爲,沒有大膽的項目。

歡迎任何建議!

回答

3

我沒有測試這一點,但我認爲你可以這樣做:

class TypeSoortDelegate(QStyledItemDelegate): 

def paint(self, painter, option, index): 
    get value... 
    if value: 
     option.font.setWeight(QFont.Bold) 

    QStyledItemDelegate.paint(self, painter, option, index)