本文主要是介绍QStyledItemDelegate派生类小例,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
QStyledItemDelegate派生类小例
///spinboxdelegate.h/
#ifndef SPINBOXDELEGATE_H
#define SPINBOXDELEGATE_H
#include <QWidget>
#include <QStyledItemDelegate>
#include <QModelIndex>
#include <QObject>
#include <QSize>
#include <QSpinBox>
class SpinBoxDelegate : public QStyledItemDelegate
{
Q_OBJECT
public:
SpinBoxDelegate(QObject *parent = 0);
~SpinBoxDelegate();
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;
};
#endif // SPINBOXDELEGATE_H
/spinboxdelegate.cpp///
#include "spinboxdelegate.h"
SpinBoxDelegate::SpinBoxDelegate(QObject *parent)
: QStyledItemDelegate(parent)
{
}
SpinBoxDelegate::~SpinBoxDelegate()
{
}
QWidget *SpinBoxDelegate::createEditor(QWidget *parent, const QStyleOptionViewItem &option,
const QModelIndex &index) const{
QSpinBox *editor = new QSpinBox(parent);
editor->setMinimum(0);
editor->setMaximum(100);
return editor;
}
void SpinBoxDelegate::setEditorData(QWidget *editor,
const QModelIndex &index) const{
int value = index.model()->data(index,Qt::EditRole).toInt();
QSpinBox *spinBox = static_cast<QSpinBox*>(editor);
spinBox->setValue(value);
}
void SpinBoxDelegate::setModelData(QWidget *editor, QAbstractItemModel *model,
const QModelIndex &index) const{
QSpinBox *spinBox = static_cast<QSpinBox*>(editor);
spinBox->interpretText();
int value = spinBox->value();
model->setData(index, value, Qt::EditRole);
}
void SpinBoxDelegate::updateEditorGeometry(QWidget *editor, const QStyleOptionViewItem *option,
const QModelIndex &index) const{
editor->setGeometry(option->rect);
}
/main.cpp///
#include "spinboxdelegate.h"
#include <QApplication>
#include <QStandardItemModel>
#include <QTableView>
#include <QModelIndex>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QStandardItemModel model(4,2);
QTableView tableView;
tableView.setModel(&model); //为视图设置模型
SpinBoxDelegate spinBox_dg;
tableView.setItemDelegate(&spinBox_dg); //为视图设置项委托
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)) );
}
}
tableView.setWindowTitle(QObject::tr("Spin Box Delegate"));
tableView.show();
return a.exec();
}
运行结果:
这篇关于QStyledItemDelegate派生类小例的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!