我对 QComboBox 作为 QTableWidget 的项目委托编辑器有疑问。QTableWidget 使用 SqlTypeDelegate 作为项目委托。
当我在 QGraphicsScene(通过 QGraphicsProxyWidget)中绘制 QTableWidget 时,不会显示可用项目的 QComboBox 弹出列表。但是,如果我将 QTableWidget 用作普通小部件(不是通过 QGraphicsScene\View 绘制的),那么 QComboBox 的行为是正常的 - 它显示项目列表。
我应该怎么做才能强制 QComboBox 显示其项目列表?
下面的示例代码:
主.cpp:
#include <QtGui/QApplication>
#include <QGraphicsScene>
#include <QGraphicsView>
#include <QTableWidget>
#include "sqltypedelegate.h"
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
QGraphicsScene scene;
QTableWidget *table = new QTableWidget(4,2);
table->setItemDelegate(new SqlTypeDelegate(table));
QGraphicsProxyWidget *proxy = scene.addWidget(table);
QGraphicsView view(&scene);
view.show();
return app.exec();
}
sqltypedelegate.h:
#include <QItemDelegate>
#include <QStyledItemDelegate>
#include <QModelIndex>
#include <QObject>
#include <QSize>
#include <QComboBox>
class SqlTypeDelegate : public QItemDelegate
{
Q_OBJECT
public:
SqlTypeDelegate(QObject *parent = 0);
QWidget *createEditor(QWidget *parent, const QStyleOptionViewItem &option,
const QModelIndex &index) const;
void setEditorData(QWidget *editor, const QModelIndex &index) const;
void setModelData(QWidget *editor, QAbstractItemModel *model,
const QModelIndex &index) const;
void updateEditorGeometry(QWidget *editor,
const QStyleOptionViewItem &option, const QModelIndex &index) const;
};
sqltypedelegate.cpp:
#include <QtGui>
#include "sqltypedelegate.h"
SqlTypeDelegate::SqlTypeDelegate(QObject *parent)
: QItemDelegate(parent)
{}
QWidget *SqlTypeDelegate::createEditor(QWidget *parent,
const QStyleOptionViewItem &/* option */,
const QModelIndex &/* index */) const
{
QComboBox *editor = new QComboBox(parent);
editor->addItem(QString("decimal(50)"));
editor->addItem(QString("integer"));
editor->addItem(QString("varchar(50)"));
editor->addItem(QString("char"));
editor->setEditable(true);
return editor;
}
void SqlTypeDelegate::setEditorData(QWidget *editor,
const QModelIndex &index) const
{
QString value = index.model()->data(index, Qt::EditRole).toString();
QComboBox *comboBox = static_cast<QComboBox*>(editor);
comboBox->setEditText(value);
}
void SqlTypeDelegate::setModelData(QWidget *editor, QAbstractItemModel *model,
const QModelIndex &index) const
{
QComboBox *comboBox = static_cast<QComboBox*>(editor);
model->setData(index, comboBox->currentText(), Qt::EditRole);
}
void SqlTypeDelegate::updateEditorGeometry(QWidget *editor,
const QStyleOptionViewItem &option, const QModelIndex &/* index */) const
{
QComboBox *comboBox = static_cast<QComboBox*>(editor);
comboBox->setGeometry(option.rect);
}