在Qt Combobox中禁用项目

20 c++ qt

我找不到在Qt组合框中禁用单个项目的标准方法.在Qt中有没有设施可以让我失踪?

kla*_*ndl 16

如果您的组合框使用的是QStandardItemModel(默认情况下它),那么您可以远离Qt::UserRole -1黑客(请参阅上面答案中 Desmond所指的博客文章):

const QStandardItemModel* model = qobject_cast<const QStandardItemModel*>(ui->comboBox->model());
QStandardItem* item = model->item(1);

item->setFlags(disable ? item->flags() & ~(Qt::ItemIsSelectable|Qt::ItemIsEnabled)
                       : Qt::ItemIsSelectable|Qt::ItemIsEnabled));
// visually disable by greying out - works only if combobox has been painted already and palette returns the wanted color
item->setData(disable ? ui->comboBox->palette().color(QPalette::Disabled, QPalette::Text)
                      : QVariant(), // clear item data in order to use default color
              Qt::TextColorRole);
Run Code Online (Sandbox Code Playgroud)

上面的代码是我对博客文章的评论的修订和更通用的解决方案.


小智 13

为什么破解..我们知道模型是QStandardItemModel ...

model = dynamic_cast< QStandardItemModel * >( combobox->model() );
item = model->item( row, col );
item->setEnabled( false );
Run Code Online (Sandbox Code Playgroud)

干净,优雅,没有黑客......


Des*_*ume 7

取自这里:

// Get the index of the value to disable
QModelIndex index = ui.comboBox->model()->index(1, 0); 

// This is the effective 'disable' flag
QVariant v(0);

// the magic
ui.comboBox->model()->setData(index, v, Qt::UserRole - 1);
Run Code Online (Sandbox Code Playgroud)

要再次启用:

QVariant v(1 | 32);
Run Code Online (Sandbox Code Playgroud)

使用的模型将flags单词映射到Qt::UserRole - 1- 这就是使这段代码有效的原因.它不是适用于任意模型的通用解决方案.

  • 它所需要的只是从模型的`flags()`方法返回`Qt :: ItemIsEnabled`.`Qt :: UserRole - 1`是一个你不应该依赖的可怕黑客(它不是一个公开的,有记录的角色).更不用说`1 |了 32`甚至不使用符号名称. (9认同)
  • 它无效.制作自己的列表模型(或代理模型)要好得多,它会正确地返回`flags`. (3认同)