2017-09-04 327 views
0

我正在研究一個小型的PyQt4任務管理器。類似的問題在這裏請求Change QTableWidget default selection color, and make it semi transparent。從這篇文章,我嘗試setStyleSheet選擇背景顏色不透明度,但突出顯示仍然覆蓋單元格背景顏色。有沒有人可以幫助我展示如何將其改變爲邊框顏色?下面PyQt4中的選擇高亮顯示QTableWidget使用完整的塊顏色填充所選單元格的背景

圖片是我目前的結果

enter image description here

這是我願意達到的,因爲你看,突出selectionis只是覆蓋的背景顏色,但不會忽略它。

enter image description here

最後,希望我的問題是每個人都十分清楚,如果發現任何不清楚或錯誤,請您讓我知道,我會以最快的速度解決越好! 謝謝!

+0

我建議提高你的問題,鏈接是參考和輔助,描述你想要的東西,並把你已經嘗試了什麼。 – eyllanesc

+0

我的問題已更新,謝謝您的建議! – Coleone

+0

你工作了嗎? – eyllanesc

回答

0

更改顏色的一種方法是使用委託。

爲此,我們必須獲取當前的背景顏色,由於QTableWidget具有自己的顏色作爲背景,因此獲取背景顏色的任務非常乏味,它還具有添加到QTableWidgets和其他類型元素的顏色我的答案目前支持有限,但這個想法是可擴展的。

顏色要被顯示爲選定元素的背景是背景顏色和顏色的平均選擇不當,在這種情況下,我們選擇顏色#cbedff

我已經實現所有的以上在下面的類:

class TableWidget(QTableWidget): 
    def __init__(self, *args, **kwargs): 
     QTableWidget.__init__(self, *args, **kwargs) 

     class StyleDelegateForQTableWidget(QStyledItemDelegate): 
      color_default = QColor("#aaedff") 

      def paint(self, painter, option, index): 
       if option.state & QStyle.State_Selected: 
        option.palette.setColor(QPalette.HighlightedText, Qt.black) 
        color = self.combineColors(self.color_default, self.background(option, index)) 
        option.palette.setColor(QPalette.Highlight, color) 
       QStyledItemDelegate.paint(self, painter, option, index) 

      def background(self, option, index): 
       item = self.parent().itemFromIndex(index) 
       if item: 
        if item.background() != QBrush(): 
         return item.background().color() 
       if self.parent().alternatingRowColors(): 
        if index.row() % 2 == 1: 
         return option.palette.color(QPalette.AlternateBase) 
       return option.palette.color(QPalette.Base) 

      @staticmethod 
      def combineColors(c1, c2): 
       c3 = QColor() 
       c3.setRed((c1.red() + c2.red())/2) 
       c3.setGreen((c1.green() + c2.green())/2) 
       c3.setBlue((c1.blue() + c2.blue())/2) 

       return c3 

     self.setItemDelegate(StyleDelegateForQTableWidget(self)) 

實施例:

if __name__ == '__main__': 
    app = QApplication(sys.argv) 
    w = TableWidget() 
    w.setColumnCount(10) 
    w.setRowCount(10) 
    for i in range(w.rowCount()): 
     for j in range(w.columnCount()): 
      w.setItem(i, j, QTableWidgetItem("{}".format(i * j))) 
      if i < 8 and j < 8: 
       color = QColor(qrand() % 256, qrand() % 256, qrand() % 256) 
       w.item(i, j).setBackground(color) 
    w.show() 
    sys.exit(app.exec_()) 

放棄了:

enter image description here

選擇:

enter image description here