qt - 禁用 QComboBox 中的特定项目

标签 qt

在我的应用程序中,我想在满足某些条件时禁用 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();
}

最佳答案

我上面评论中链接的答案似乎是在谈论旧版本的 Qt。我已经在 Qt5.4 和 Qt5.6 上测试过了,这里不需要自己设置颜色,你只需要设置和/或清除 Qt::ItemIsEnabled标志,这是一个例子:

#include <QtWidgets>

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());
  Q_ASSERT(model != nullptr);
  bool disabled = true;
  QStandardItem *item = model->item(2);
  item->setFlags(disabled ? item->flags() & ~Qt::ItemIsEnabled
                          : item->flags() | Qt::ItemIsEnabled);
  comboBox.show();
  return a.exec();
}

关于qt - 禁用 QComboBox 中的特定项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38915001/

相关文章:

qt - 如何将 QT 翻译添加到 CMake

c++ - QT自定义鼠标事件和拖动模式

c++ - 将它们传递给 cpp 后如何与 qml 项目值进行交互?

Qt 5.11 : Touch input inverted in my application

c++ - qt在qgridlayout中设置相同大小的小部件

c++ - 为什么我的嵌套 QEventLoop 不能为我的 QThread 传递所有事件?

c++ - 将 setText 和 setNum 合并到 Qt 中的标签中?

c++ - Qt套接字写段错误

RStudio 不显示任何 Pane

c++ - 为什么 windows 任务栏自定义任务列表在 windows 10 上没有 pin 时不起作用?