PDA

View Full Version : QTableWidget + QDateEdit + Delegates



Cykus
6th June 2008, 14:40
Hi
i try to set QDateEdit in cell QTableWidget but doesn't work

//mainwindow
ui.tabela->setItemDelegate(new DateDelegate(5));
QTableWidgetItem *nazwa5 = new QTableWidgetItem(obiekt[idx].item[5]);
ui.tabela->setItem(idx, 5, nazwa5);
"obiekt[idx].item[5]" it's QString

class DateDelegate

// *.h
#include <QItemDelegate>
#include <QModelIndex>
#include <QObject>
#include <QSize>
#include <QDateEdit>

class DateDelegate : public QItemDelegate
{
Q_OBJECT
public:
DateDelegate(int durationColumn, QObject *parent = 0);
// void paint(QPainter *painter, 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;
private slots:
void commitAndCloseEditor();
private:
int durationColumn;
};




// *.cpp
#include "datedelegate.h"
#include <QtGui>



DateDelegate::DateDelegate(int durationColumn, QObject *parent)
: QItemDelegate(parent)
{
this->durationColumn = durationColumn;
}

QWidget *DateDelegate::createEditor(QWidget *parent,
const QStyleOptionViewItem &option,
const QModelIndex &index) const
{
if(index.column() == 5 ){
QDateTimeEdit *editor = new QDateTimeEdit(parent);
editor->setDisplayFormat("dd.MM.yyyy");
editor->setCalendarPopup(true);
connect(editor, SIGNAL(editingFinished()), this, SLOT(commitAndCloseEditor()));
return editor;

}
if(index.column() == 6 ){
QDateTimeEdit *editor = new QDateTimeEdit(parent);
editor->setDisplayFormat("dd.MM.yyyy");
editor->setCalendarPopup(true);
connect(editor, SIGNAL(editingFinished()), this, SLOT(commitAndCloseEditor()));
return editor;

}
if(index.column() == 7 ){
QDateTimeEdit *editor = new QDateTimeEdit(parent);
editor->setDisplayFormat("dd.MM.yyyy");
editor->setCalendarPopup(true);
connect(editor, SIGNAL(editingFinished()), this, SLOT(commitAndCloseEditor()));
return editor;

}

}

void DateDelegate::commitAndCloseEditor()
{
QDateEdit *editor = qobject_cast<QDateEdit *>(sender());
emit commitData(editor);
emit closeEditor(editor);
}

void DateDelegate::setEditorData(QWidget *editor,
const QModelIndex &index) const
{
QDateTimeEdit *dateEditor = qobject_cast<QDateTimeEdit *>(editor);
QString value = index.model()->data(index, Qt::EditRole).toString();

dateEditor->setDate(QDate::fromString(value , "dd.MM.yyyy"));

}

void DateDelegate::setModelData(QWidget *editor,
QAbstractItemModel *model,
const QModelIndex &index) const
{
QDateTimeEdit *dateEditor = qobject_cast<QDateTimeEdit *>(editor);
QString value = dateEditor->date().toString("dd.MM.yyyy");
model->setData(index, value, Qt::EditRole);
}


sorry for my english
thx for help

jacek
8th June 2008, 00:43
What does "doesn't work" mean exactly in your case?