Part 08 自定义委托(Qt)[2012.02.18]

Part 08 自定义委托(Qt)

——2012.02.18

0. 本次学习Qt时主要方法:分析代码实例,理清原代码思路,摘录(修改)代码,编写读书笔记。
1. 编写学习笔记主要形式:展示程序功能,介绍类特点,程序代码简要讲述,展示程序代码。
2. 主要参考学习资料: Qt Assistant与Qt学习之路(49)(豆子空间)。
3. 本Part内容:了解自定义委托的含义,体会编写委托类的方法。

 


附:本次主要学习的类的类继承关系图


 


016 Program –mvc

 

01. 展示程序功能


 
    该程序含一个简单的表格,其中,表格内容共有两栏,第一栏是歌曲名称,第二栏是歌曲的时长,歌曲时长可以通过鼠标的双击,然后点击上下箭头输入调整或通过键盘输入进行调整。

 

 

02. 介绍类的特点

1. 引自Qt Assistant(V4.8):#include <QItemDelegate>
        The QItemDelegate class provides display and editing facilitiesfor data items from a model.
        QItemDelegate can be used to provide custom display features and editor widgetsfor item views based on QAbstractItemView subclasses. Using a delegate for this purpose allows the display and editing mechanisms to be customized and developed independently from the model and view.
        The QItemDelegate class is one of the Model/View Classes and is part of Qt's model/view framework. Note that QStyledItemDelegate has taken over the job of drawing Qt's item views. We recommend the use of QStyledItemDelegate when creating new delegates.
        When displaying items from a custom model in a standard view, it is often sufficient to simply ensure that the model returns appropriate data for each of the roles that determine the appearance of items in views. The default delegate used by Qt's standard views uses this role information to display items in most of the common forms expected by users. However, it is sometimes necessary to have even more control over the appearance of items than the default delegate can provide.
        This class provides default implementations of the functions for painting item data in a view and editing data from item models. Default implementations of the paint() and sizeHint() virtual functions, defined in QAbstractItemDelegate, are provided to ensure that the delegate implements the correct basic behavior expected by views.

        You can reimplement these functions in subclasses to customize the appearance of items.
        When editing data in an item view, QItemDelegate provides an editor widget, which is a widget that is placed on top of the view while editing takes place. Editors are created with a QItemEditorFactory; a default static instance provided by QItemEditorFactory is installed on all item delegates. You can set a custom factory using setItemEditorFactory() or set a new default factory with QItemEditorFactory::setDefaultFactory(). It is the data stored in the item model with the Qt::EditRole that is edited.

 

Only the standard editing functions for widget-based delegates are reimplemented here:
        • createEditor() returns the widget used to change data from the model and can be reimplemented to customize editing behavior.
        • setEditorData() provides the widget with data to manipulate.
        • updateEditorGeometry() ensures that the editor is displayed correctly with respect to the item view.
        • setModelData() returns updated data to the model.
The closeEditor() signal indicates that the user has completed editing the data, and that the editor widget can be destroyed.

 

 

03. 程序代码简要讲述


 

        0.这个程序中,共包含了三个类,一个主函数:
         1. track.h
         2. trackdelegate.h
         3. trackeditor.h


        1. track.h
           这个类相当于结点类,类中只定义了两个私有成员(歌曲名和歌曲的持续时间),一个构造函数,用于提供一种类型给另外两个类使用。
       

        2. trackdelegate.h
          这个类就是这个程序中的委托类,具有响应用户操作,修改基类中的数据,显示改动后画面的功能。


 

        3. trackeditor.h
          这个类的功能比较简单,具有两个私有成员,第一个是QList成员,用于接收在main函数中需要初始化的数据,第二个是QTableWidget对象,用于保存列表中的信息。这个类只有一个构造函数外就不包含其它有特殊功能的函数了,主要用于初始化窗口,建立需要委托的对象(QTableWidget),并建立委托关系。

 


04. 程序代码

// main.cpp
#include "trackeditor.h"
#include <QtGui/QApplication>
#include <qlist.h>
int main(int argc, char *argv[])
{
	QApplication a(argc, argv);
	QList<Track> tracks;		// 建立用于初始化的数据
	Track t1("Song 1", 100);
	Track t2("Song 2", 200);
	Track t3("Song 3", 300);
	Track t4("Song 4", 400);
	Track t5("Song 5", 500);
	tracks << t1 << t2 << t3 << t4 << t5;
	TrackEditor te(&tracks, NULL);	// 初始化对话框对象
	te.show();						// 展示对话框
	return a.exec();
}


// track.h
#ifndef TRACK_H
#define TRACK_H
#include <qstring.h>
class Track
{
public:
	Track(const QString &, int duration = 0);
	QString title;	// 歌曲名
	int duration;	// 歌曲持续时间
};
#endif	// TRACK_H


// trackdelegate.h
#ifndef TRACKDELEGATE_H
#define TRACKDELEGATE_H
#include <QtGui\qstyleditemdelegate.h>
#include <qstyleoption.h>
#include <qwidget.h>
#include <qtextoption.h>
#include <qpainter.h>
#include <QTimeEdit>
#include <qlist.h>
class TrackDelegate: public QStyledItemDelegate
{
	Q_OBJECT
public:
	TrackDelegate(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;
};
#endif	// TRACKDELEGATE_H


// trackeditor.h
#ifndef TRACKEDITOR_H
#define TRACKEDITOR_H
#include "track.h"
#include <QtGui/QDialog>
#include <qlist.h>
#include <qtablewidget.h>
class TrackEditor : public QDialog
{
	Q_OBJECT
public:
	TrackEditor(QList<Track> * tracks, QWidget *parent);
	~TrackEditor();
private:
	QList<Track> * tracks;
	QTableWidget * tableWidget;
};
#endif // TRACKEDITOR_H


// track.cpp
#include "track.h"
Track::Track(const QString & t, int d): title(t), duration(d)
{
}


// trackdelegate.cpp
#include "trackdelegate.h"
TrackDelegate::TrackDelegate(int durationColumn, QObject * parent):QStyledItemDelegate(parent)
{
	this -> durationColumn = durationColumn;	// 初始化需要渲染的列,即需要代理的列,需要执行操作的列
}
void TrackDelegate::paint(QPainter * painter, const QStyleOptionViewItem & option, const QModelIndex & index)const
{
	if (index.column() == durationColumn)
	{
		int secs = index.model() -> data(index, Qt::DisplayRole).toInt();
		QString text = QString("%1:%2").arg(secs / 60, 2, 10, QChar('0')).arg(secs % 60, 2, 10, QChar('0'));
		QTextOption o(Qt::AlignRight | Qt::AlignVCenter);
		painter -> drawText(option.rect, text, o);	// 在画面中修改text
	}
	else
	{
		QStyledItemDelegate::paint(painter, option, index);
	}
	return;
}
QWidget * TrackDelegate::createEditor(QWidget * parent, const QStyleOptionViewItem & option, const QModelIndex & index) const
{
	if(index.column() == durationColumn)
	{
		QTimeEdit * timeEdit = new QTimeEdit(parent);
		timeEdit -> setDisplayFormat("mm:ss");
		connect(timeEdit, SIGNAL(editingFinished()), this, SLOT(commitAndCloseEditor()));
		return timeEdit;
	}
	else
	{
		return QStyledItemDelegate::createEditor(parent, option, index);
	}
}
void TrackDelegate::commitAndCloseEditor()
{
	QTimeEdit * editor = qobject_cast<QTimeEdit *>(sender());
	emit commitData(editor);
	emit closeEditor(editor);
	return;
}
void  TrackDelegate::setEditorData(QWidget * editor, const QModelIndex & index)const
{
	if(index.column() == durationColumn)
	{
		int secs = index.model() -> data(index, Qt::DisplayRole).toInt();
		QTimeEdit * timeEdit = qobject_cast<QTimeEdit *>(editor);
		timeEdit -> setTime(QTime(0, secs / 60, secs % 60));
	}
	else
	{
		QStyledItemDelegate::setEditorData(editor, index);
	}
	return;
}
void TrackDelegate::setModelData(QWidget * editor, QAbstractItemModel * model, const QModelIndex & index) const
{
	if(index.column() == durationColumn)
	{
		QTimeEdit * timeEdit = qobject_cast<QTimeEdit *> (editor);
		QTime time = timeEdit -> time();
		int secs = (time.minute() * 60) + time.second();
		model -> setData(index, secs);
	}
	else
	{
		QStyledItemDelegate::setModelData(editor, model, index);
	}
	return;
}


// trackeditor.cpp

#include "trackeditor.h"
#include "trackdelegate.h"
#include "track.h"

#include <qlist.h>
#include <qtablewidget.h>
#include <QVBoxlayout>

TrackEditor::TrackEditor(QList<Track> * tracks, QWidget * parent)	: QDialog(parent)
{
	// 获取数据
	this -> tracks = tracks;

	// 初始化Widget
	tableWidget = new QTableWidget(tracks -> count(), 2);	// 初始化多少行多少列的table
	tableWidget -> setItemDelegate(new TrackDelegate(1));	// 为Widget设置代理
	tableWidget -> setHorizontalHeaderLabels(QStringList() << tr("Track") << tr("Duration"));// 设置table的表头
	
	for ( int row = 0; row < tracks -> count(); ++row)
	{
		Track track = tracks -> at(row);		// 单行提取
		QTableWidgetItem * item0 = new QTableWidgetItem(track.title);	// 提取该行的tittle
		QTableWidgetItem * item1 = new QTableWidgetItem(QString::number(track.duration));	// 提取该行的duration
		item1 -> setTextAlignment(Qt::AlignRight);	// 设置对齐方式
		
		tableWidget -> setItem(row, 0, item0);		// 数据逐项入表
		tableWidget -> setItem(row, 1, item1);
	}

	// 设置布局
	QVBoxLayout * mainLayout = new QVBoxLayout;
	mainLayout -> addWidget(tableWidget);
	this -> setLayout(mainLayout);
}

TrackEditor::~TrackEditor()
{

}



 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值