PDA

View Full Version : delegate isn't work with QSqlTableModel?



TomASS
2nd August 2009, 23:30
Hi,

I have:

QSqlTableModel *model = new QSqlTableModel();
model->setTable( "table" );
model->select();
model->setHeaderData( 0, Qt::Horizontal, QObject::tr("Annual Pay") );
model->setHeaderData( 1, Qt::Horizontal, QObject::tr("First Name") );
model->setHeaderData( 2, Qt::Horizontal, QObject::tr("Last Name") );
model->removeColumn( 0 );
TableResult->setModel( model );
BarDelegate delegate;
TableResult->setItemDelegateForColumn(1, &delegate);
TableResult->show();


and in Delegate class i've:


class BarDelegate : public QAbstractItemDelegate
{
public:
BarDelegate( QObject *parent = 0 );

void paint( QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index ) const;
QSize sizeHint( const QStyleOptionViewItem &option, const QModelIndex &index ) const;

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;
};

In createEditor:

QWidget *BarDelegate::createEditor( QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index ) const
{
QMessageBox::information( 0, "window1", "test" );
QLineEdit *lineEdit = new QLineEdit( parent );
lineEdit->setAutoFillBackground( true );
lineEdit->installEventFilter( const_cast<BarDelegate*>(this) );
return lineEdit;
}

When I press on a cell TableResult, there is no QMessageBox :/

Similar with:

void BarDelegate::setEditorData( QWidget *editor, const QModelIndex &index ) const
{
QMessageBox::information( 0, "window1", "test2" );
QString value = index.model()->data( index, Qt::DisplayRole ).toString();
static_cast<QLineEdit*>( editor )->setText( value );
}
and :/

void BarDelegate::setModelData( QWidget *editor, QAbstractItemModel *model, const QModelIndex &index ) const
{
QMessageBox::information( 0, "window1", "test3" );
model->setData( index, static_cast<QLineEdit*>( editor )->text() );
}

victor.fernandez
3rd August 2009, 13:14
You cannot instantiate the delegate on the stack. You must instantiate it on the heap instead:


BarDelegate *delegate = new BarDelegate(this);
TableResult->setItemDelegateForColumn(1, delegate);

TomASS
3rd August 2009, 13:23
Thanks! Work!