【发布时间】:2016-07-19 13:39:00
【问题描述】:
我有一个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()不是指combobox的原始item数据吗?
【问题讨论】: