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)
干净,优雅,没有黑客......
取自这里:
// 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- 这就是使这段代码有效的原因.它不是适用于任意模型的通用解决方案.
| 归档时间: |
|
| 查看次数: |
15669 次 |
| 最近记录: |