我创建了一个 QStyledItemDelegate 类,我想在其中使一些项目可检查,一些带有两个小部件。但它工作不正常。我错过了什么?这是它的样子:
请参见第 1 行,看起来这两个小部件都在那里,但它们并没有真正显示出来。而且我需要一些帮助才能使项目可检查(这与添加复选框不同?)。谢谢你。
这是我的 QStyledItemDelegate 类:
//! [0]
SpinBoxDelegate::SpinBoxDelegate(QObject *parent)
: QStyledItemDelegate(parent)
{
}
//! [0]
//! [1]
QWidget *SpinBoxDelegate::createEditor(QWidget *parent,
const QStyleOptionViewItem &option,
const QModelIndex &index) const
{
if (index.row()==1) {
QLineEdit* lineBox;
QCheckBox* checkBox;
QWidget *panel;
panel = new QWidget(parent);
QHBoxLayout *layout = new QHBoxLayout;
lineBox = new QLineEdit( );
lineBox->setText("abc");
checkBox = new QCheckBox( );
layout->addWidget(checkBox);
layout->addWidget(lineBox);
panel->setLayout(layout);
return panel;
}else if (index.row()==2) {
// need to make this check-able item?
}else{
QLineEdit *editor = new QLineEdit(parent);
return editor;
}
}
//! [1]
//! [2]
void SpinBoxDelegate::setEditorData(QWidget *editor,
const QModelIndex &index) const
{
int value = index.model()->data(index, Qt::EditRole).toInt();
if (index.row()==1) {
// need something here?
}else{
QLineEdit *spinBox = static_cast<QLineEdit*>(editor);
spinBox->setText("value");
}
}
//! [2]
//! [3]
void SpinBoxDelegate::setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const
{
if (index.row()==1) {
// need something here?
}else{
QLineEdit *spinBox = static_cast<QLineEdit*>(editor);
model->setData(index, spinBox->text(), Qt::EditRole);
}
}
//! [3]
//! [4]
void SpinBoxDelegate::updateEditorGeometry(QWidget *editor,
const QStyleOptionViewItem &option, const QModelIndex &/* index */) const
{
editor->setGeometry(option.rect);
}
//! [4]
这是我的 main.cpp:
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
QStandardItemModel model(4, 2);
//QTableView tableView;
QTreeView treeView;
treeView.setModel(&model);
SpinBoxDelegate delegate;
treeView.setItemDelegate(&delegate);
//! [0]
//tableView.horizontalHeader()->setStretchLastSection(true);
treeView.setRootIsDecorated(false);
treeView.setHeaderHidden(true);
treeView.setIndentation(20);
//! [1]
for (int row = 0; row < 4; ++row) {
for (int column = 0; column < 2; ++column) {
QModelIndex index = model.index(row, column, QModelIndex());
model.setData(index, QVariant((row + 1) * (column + 1)));
}
//! [1] //! [2]
}
//! [2]
//! [3]
treeView.setWindowTitle(QObject::tr("Spin Box Delegate"));
treeView.show();
return app.exec();
}
//! [3]
这最终是我想要实现的目标: