2015-11-19 33 views
0

也有可能有兩種不同的選擇顏色?我該怎麼做?你知道當你選擇一個單元格時,可以使用樣式表設置選定的顏色,但是因爲我使用的是表格視圖,所以我想知道我的視圖是否可以查詢我的模型。例如,我有一個變量來存儲選擇。如果用戶選擇一個值「1」,當他選擇一個單元格時它將是紅色,當他從下拉列表中選擇「2」時,當他選擇單元格時它將是藍色的。這可能嗎?(我的表格將同時顯示兩種不同的選定單元格顏色,因爲不同的顏色應該有不同的含義)。如何在QTableView中有不同的選擇顏色?

我有下面的代碼,但它返回一個奇怪的結果。

我的數據()函數:

if (role == Qt::DisplayRole) 
{ 
Return data[row][col]; 
} 
Else if (role = Qt::DecorationRole) 
{ 
//if (selectionVar == 0) 
return QVariant(QColor(Qt::red)); 
//else if(....) 
} 

的結果是,我在細胞中紅細胞與複選框。我不知道爲什麼會這樣。難道我做錯了什麼?

回答

0

是的,這是可能的!

如果您不想使用當前樣式,您將不得不實現您自己的QStyledItemDelegate(或),但不建議使用)。在那裏你可以繪製任何你想要的(包括不同的選擇顏色)。要使用模型的特殊功能,請使用自定義項目角色或將QModelIndex::model()轉換爲您自己的模型實現。 (如果需要更多的細節,我可以發佈更多)

編輯一個簡單的例子:

在你的模型做的事:

QVariant MyModel::data(const QModelIndex &index, int role) const 
{ 
    switch(role) { 
    //... 
    case (Qt::UserRole + 3)://as an example, can be anything greater or equal to Qt::UserRole 
     return (selectionVar == 0); 
    //... 
    } 
} 

創建新的委託類的地方:

class HighlightDelegate : public QItemDelegate //QStyledItemDelegate would be better, but it wasn't able to change the styled highlight color there 
{ 
public: 
    HighlightDelegate(QObject *parent); 
    void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const Q_DECL_OVERRIDE; 
}; 

HighlightDelegate::HighlightDelegate(QObject *parent) : 
    QItemDelegate(parent) 
{} 

void HighlightDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const 
{ 
    QStyleOptionViewItem opt = option; 

    if(index.model()->data(index, Qt::UserRole + 3).toBool())//same here 
     opt.palette.setColor(QPalette::Highlight, Qt::red); 

    this->QItemDelegate::paint(painter, opt, index); 
} 

...並告訴視圖使用代理人:

this->ui->itemView->setItemDelegate(new HighlightDelegate(this)); 

而那就是它!這個(如你所見)是使用QItemDelegate創建的。似乎不可能用QStyledItemDelegate創建它,因爲它將忽略QPalette::Highlight(至少在窗口中)。

+0

對不起,我不太瞭解如何使用qitemdelegate,你能給我一個簡短的例子,我如何在我的情況下實現它?謝謝(y) –

+0

這看起來不錯..我試過了,但我仍然有這個問題,當我點擊時,像圖標這樣的複選框出現在我的單元格內。另外,當我切換我的選擇時,當我點擊其他地方時,已經選擇的單元也會改變顏色。我的代碼n的結果如圖所示。 –

+0

Table-> setItemDelegate(new HighlightDelegate(this));表 - >則setModel(網格); –

相關問題