想实现组合框点下拉按钮就显示一个日期时间控件,下面是代码
头文件:ComboBoxDelegate.h
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#ifndef Inc_ComboBoxDelegate_H
#define Inc_ComboBoxDelegate_H
#include <QItemDelegate>
#include <QModelIndex>
#include <QObject>
#include <QSize>
#include <QComboBox>
class ComboBoxDelegate : public QItemDelegate
{
Q_OBJECT
public:
ComboBoxDelegate(QObject *parent = 0);
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 //Inc_ComboBoxDelegate_H
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
实现文件ComboBoxDelegate.cpp
#include <QtGui>
#include "ComboBoxDelegate.h"
ComboBoxDelegate::ComboBoxDelegate(QObject *parent):QItemDelegate(parent)
{
}
QWidget *ComboBoxDelegate::createEditor(QWidget *parent,
const QStyleOptionViewItem &/* option */,
const QModelIndex &/* index */) const
{
QDateTimeEdit *editor = new QDateTimeEdit(parent);
editor->setDisplayFormat("dd/M/yyyy");
editor->setCalendarPopup(true);
return editor;
}
void ComboBoxDelegate::setEditorData(QWidget *editor,const QModelIndex &index) const
{
QDateTimeEdit *dateEditor = qobject_cast<QDateTimeEdit *>(editor);
if (dateEditor)
{
dateEditor->setDate(QDate::fromString(index.model()->data(index, Qt::EditRole).toString(), "d/M/yyyy"));
}
}
void ComboBoxDelegate::setModelData(QWidget *editor, QAbstractItemModel *model,
const QModelIndex &index) const
{
QDateTimeEdit *dateEditor = qobject_cast<QDateTimeEdit *>(editor);
if (dateEditor)
{
model->setData(index, dateEditor->date().toString("dd/M/yyyy"));
}
}
void ComboBoxDelegate::updateEditorGeometry(QWidget *editor,
const QStyleOptionViewItem &option, const QModelIndex &/* index */) const
{
editor->setGeometry(option.rect);
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////
在使用的地方:
QComboBox* pCmb = new QComboBox(this);
pCmb ->setItemDelegate(new ComboBoxDelegate(this));
点击组合框的下拉按钮没有任何反应在,如果把组合框换为QTableWidget就没有问题。
QTableWidget * plst = new QTableWidget(1,1,this);
plst->setItemDelegate(new ComboBoxDelegate(this));
请问问题在那里?
另外,我想把组合框换成QLineEdit控件,感觉这样设置时间更合理一些,点一下QLineEdit就弹出QDateTimeEdit 设时间,但QLineEdit并没有setItemDelegate接口,不能这样做,另外也想过把QListWidget设置显示为一行来替换QComboBox,但显示并不理想,并且点击相关item也没有弹出QDateTimeEdit,请问有什么办法实现这样的效果么?