【问题标题】:Retrieve QComboBox index from QCompletion popup从 QCompletion 弹出窗口中检索 QComboBox 索引
【发布时间】:2016-07-19 13:39:00
【问题描述】:

我有一个QComboBox 和一个QCompleterQCompleter 在弹出列表中显示建议,我正在以自定义方式绘制元素。

问题是:即使我确实将它存储到项目的UserData 中,我也无法获取原始组合框中的索引。

完整代码如下:

class MyItemDelegate: public QItemDelegate {
public:
    MyItemDelegate(QWidget *parent) :
      QItemDelegate(parent) {}

    void paint(QPainter *painter, const QStyleOptionViewItem &option,
               const QModelIndex &index ) const Q_DECL_OVERRIDE
    {
        if (index.row() == 0) { // If this is the first item in the POPUP VIEW

          auto comboIndex = index.data(Qt::UserRole).toInt();
          qDebug() << "Combobox index is " << comboIndex; // WRONG!!
        }
       ... custom styling code omitted since off-topic ...
    }
};

MyWindow::MyWindow(QStringList words, QMainWindow *parent) :
  QDialog((QWidget*)parent),
  ui(new Ui::MyWindow) {

  ui->setupUi(this);

  int comboBoxIndex = 0;
  for(auto& word : words) {
    ui->myComboBox->addItem(word, comboBoxIndex); // This is stored in UserData
    ++comboBoxIndex;
  }

  completer = new QCompleter(words, this);

  // Use a TreeView for the popup of the completer
  QTreeView *treeView = new QTreeView(this);
  completer->setPopup(treeView);

  treeView->setItemDelegate(new MyItemDelegate(this));
}

无论QCompletion 弹出列表中的第一个元素是什么,qDebug() 行总是返回0 作为索引。

index.data()不是指combobox的原始item数据吗?

【问题讨论】:

    标签: c++ qt


    【解决方案1】:

    如我所见,您的问题是您从未设置UserData 的模型中检索comboIndex。您为内部QComboBox 模型的项目设置UserData(请参阅QComboBox),但是当您尝试检索此数据时,您在MyItemDelegate 的代码中执行此操作,您为QTreeView 设置QCompleter .这就是为什么在paint 委托方法中的indexQCompleter 内部模型的索引,而不是QComboBox 内部模型的索引。这就是为什么comboIndex 总是0

    要解决您的问题,您可以在QCompleter 内部模型中添加UserData。例如,您可以创建自己的模型并使用方法setModelQCompleter 设置此模型。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多