从QCompletion弹出窗口中检索QComboBox索引

时间:2016-07-19 13:39:01

标签: c++ qt

我有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()是不是指组合框的原始项目数据?

1 个答案:

答案 0 :(得分:0)

正如我所看到的,您的问题是您从未设置comboIndex的模型中检索UserData。您为内部UserData模型的项目设置了QComboBox(请参阅QComboBox),但是当您尝试检索此数据时,可以使用您设置的MyItemDelegate代码执行此操作对于QTreeView QCompleter。这就是为什么index委托方法中的paintQCompleter内部模型的索引,而不是QComboBox内部模型的索引。这就是为什么comboIndex总是0

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