我想在Qtableview中的某一列加入一个QComboBox来编辑,就是下图中的,我创建了一个自定义的delegate,继承自QStyledItemDelegate类,但是不知道为什么双击相应列后,QComboBox弹出来了,没有嵌在表格里面。
代码如下:
QWidget* ClientDelegate::createEditor(
QWidget *parent, const QStyleOptionViewItem &option,
const QModelIndex &index) const
{
if(index.column() != client_state){
return QStyledItemDelegate::createEditor(parent,option,index);
}
QComboBox *stateBox = new QComboBox;
stateBox->setFixedHeight(option.rect.height());
stateBox->addItem("设计中",ClientInfo::ShejiZhong);
stateBox->addItem("等待回复",ClientInfo::DengdaiHuifu);
stateBox->addItem("处理中",ClientInfo::ChuliZhong);
stateBox->addItem("已确认",ClientInfo::YiQueren);
stateBox->addItem("已发片",ClientInfo::YiFapian);
return stateBox;
}
void ClientDelegate::setEditorData(QWidget * editor, const QModelIndex & index) const
{
if(index.column() != client_state){
QStyledItemDelegate::setEditorData(editor,index);
return;
}
int state = index.data().toInt();
QComboBox *stateBox = static_cast<QComboBox *>(editor);
stateBox->setCurrentIndex(state);
}
void ClientDelegate::setModelData(QWidget *editor, QAbstractItemModel *model,
const QModelIndex &index) const
{
if(index.column() != client_state){
QStyledItemDelegate::setModelData(editor,model,index);
return;
}
QComboBox *stateBox = static_cast<QComboBox *>(editor);
int state = stateBox->currentData().toInt();
model->setData(index,state);
}
------解决方案--------------------
没有指定父窗口的问题:
QWidget* ClientDelegate::createEditor(
QWidget *parent, const QStyleOptionViewItem &option,
const QModelIndex &index) const
{
if(index.column() != client_state){
return QStyledItemDelegate::createEditor(parent,option,index);
}
QComboBox *stateBox = new QComboBox(parent);
stateBox->setFixedHeight(option.rect.height());
stateBox->addItem("设计中",ClientInfo::ShejiZhong);
stateBox->addItem("等待回复",ClientInfo::DengdaiHuifu);
stateBox->addItem("处理中",ClientInfo::ChuliZhong);
stateBox->addItem("已确认",ClientInfo::YiQueren);
stateBox->addItem("已发片",ClientInfo::YiFapian);
return stateBox;
}