2012-02-15 114 views

回答

2

你做錯了什麼。如果您禁用了一個小部件,它會變灰,並且不會收到用戶鼠標點擊和鍵盤輸入。

+0

我沒有禁用小部件。我只是設置項目標誌沒有Qt :: ItemIsEnabled標誌。 QTreeView小部件接收mousePressEvent,但不會選擇該項目。 – 2012-02-15 13:39:20

+1

在文檔中明確指出:Qt :: ItemIsEnabled用戶可以與項目交互。因此,如果您將其設置爲「未啓用」,這意味着用戶無法與該項目交互,他無法選擇或編輯該項目。 – Dmitriy 2012-02-15 14:07:12

+1

還有ItemIsSelectable,取消設置應該有助於防止程序選擇。 – 2012-02-15 14:30:31

3

從我的理解,你想「禁用」的項目,但同時,能夠選擇它。在模型上僞造相當容易。

if (role == Qt::BackgroundRole){ 
    return QVariant(QApplication::palette()->color(QPalette::Inactive, QPalette::Window); 
} 

這會將您的項目繪製爲灰色,並且仍然可以選擇它。

0

我剛剛有類似的問題(我需要複製禁用的項目)。這裏是解決方案,爲殘疾人物品設置正確的風格(不忽略任何樣式表)。

爲您的模型創建自定義項目委託。

/// Returns false only if item needs to be rendered as disabled. 
bool isIndexEnabled(const QModelIndex &index) 
{ 
    // Implement this function. 
} 

class ItemDelegate : public QStyledItemDelegate { 
public: 
    explicit ItemDelegate(QObject *parent = nullptr) 
     : QStyledItemDelegate(parent) {} 

protected: 
    void initStyleOption(
     QStyleOptionItemView *option, const QModelIndex &index) const override 
    { 
     QStyledItemDelegate::initStyleOption(option, index); 
     if (!isIndexEnabled(index)) 
      option->state &= ~QStyle::State_Enabled; 
    } 
}; 

將新項目代理設置爲您的模型。

auto itemDelegate = new ItemDelegate(model) 
model->setItemDelegate(itemDelegate);