我有QComboBox
QCompleter
。 QCompleter
在弹出列表中显示建议,我以自定义方式绘制元素。
问题是:即使我将其存储到项目的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()
是不是指组合框的原始项目数据?
答案 0 :(得分:0)
正如我所看到的,您的问题是您从未设置comboIndex
的模型中检索UserData
。您为内部UserData
模型的项目设置了QComboBox
(请参阅QComboBox),但是当您尝试检索此数据时,可以使用您设置的MyItemDelegate
代码执行此操作对于QTreeView
QCompleter
。这就是为什么index
委托方法中的paint
是QCompleter
内部模型的索引,而不是QComboBox
内部模型的索引。这就是为什么comboIndex
总是0
。
要解决您的问题,您可以在UserData
内部模型中添加QCompleter
。例如,您可以创建自己的模型,并使用方法setModel为QCompleter
设置此模型。