2016-08-12 110 views
2

在我的應用程序中,當某些條件滿足時,我想在QComboBox中禁用某些項目(即不能選擇,鼠標懸停在上方時不亮,文本變灰)。禁用QComboBox中的特定項目

我確實發現有人在這裏問過同樣的問題:Disable Item in Qt Combobox 但是答案中的這些解決方案似乎都沒有實際工作(包括技巧)。

是否有體面和「正確」的方式來實現這一點?

編輯:

我找到了原因設置標誌在我的應用程序不會禁用的物品:由於某些原因,我不得不設置樣式QStyle::SH_ComboBox_UseNativePopup(見https://codereview.qt-project.org/#/c/82718/)。由於某些原因,此設置會阻止標誌設置。有沒有人有一個想法,爲什麼,以及如何解決?最小的測試示例包括(從@Mike的回答修改):上述

#include <QApplication> 
#include <QComboBox> 
#include <QStandardItemModel> 
#include <QProxyStyle> 

class ComboBoxStyle : public QProxyStyle 
{ 
public: 
    int styleHint (StyleHint hint, const QStyleOption * option = 0, const QWidget * widget = 0, QStyleHintReturn * returnData = 0) const override 
    { 
     if (hint == QStyle::SH_ComboBox_UseNativePopup) 
     { 
      return 1; 
     } 
     return QProxyStyle::styleHint(hint, option, widget, returnData); 
    } 
}; 

int main(int argc, char *argv[]) 
{ 
    QApplication a(argc, argv); 
    QComboBox comboBox; 

    // Setting this style would block the flag settings later on. 
    comboBox.setStyle(new ComboBoxStyle()); 

    comboBox.insertItem(0, QObject::tr("item1")); 
    comboBox.insertItem(1, QObject::tr("item2")); 

    QStandardItemModel* model = qobject_cast<QStandardItemModel*>(comboBox.model()); 
    QStandardItem* item= model->item(1); 
    item->setFlags(item->flags() & ~Qt::ItemIsEnabled); 

    comboBox.show(); 
    return a.exec(); 
} 
+0

你嘗試[這](http://stackoverflow.com/a/21740341/2666212)回答?如果你沒有在你的'QComboBox'中使用'setModel'(即你使用'addItem'添加你的項目),這應該適合你。 – Mike

回答

7

在我的評論鏈接的答案似乎是在談論一個老版本的Qt。我已經在Qt5.4和Qt5.6測試,也沒有必要設置顏色自己這裏,你只需要設置和/或清除Qt::ItemIsEnabled標誌,這裏有一個例子:

#include <QApplication> 
#include <QComboBox> 
#include <QStandardItemModel> 

int main(int argc, char *argv[]) 
{ 
    QApplication a(argc, argv); 
    QComboBox comboBox; 
    comboBox.addItem(QObject::tr("item1")); 
    comboBox.addItem(QObject::tr("item2")); 
    comboBox.addItem(QObject::tr("item3")); 
    QStandardItemModel* model = qobject_cast<QStandardItemModel*>(comboBox.model()); 
    bool disabled= true; 
    QStandardItem* item= model->item(2); 
    item->setFlags(disabled? item->flags() & ~Qt::ItemIsEnabled: 
          item->flags() | Qt::ItemIsEnabled); 
    comboBox.show(); 
    return a.exec(); 
} 
+0

請注意,這依賴於未記錄的行爲,即將後備模型轉換爲'QStandardItemModel'。這與包括私人標題相同的警告。 –

+0

作爲替代方法,顯式創建一個'QStandardItemModel'實例並首先將它設置在組合框上。 –

+0

@JonHarper,不,這不是無證的,請閱讀[this](https://doc.qt.io/qt-5/qcombobox.html#details)。 * QComboBox爲其彈出列表使用模型/視圖框架並存儲其項目。默認情況下,** QStandardItemModel **存儲項目,而QListView子類將顯示彈出列表*。 – Mike