[Qt-interest] setTextAlignment API in QT-3.3.6 ???

Vladimir Barbarosh vladimir.barbarosh at gmail.com
Thu Oct 14 10:40:39 CEST 2010


Sadly, but I solve not the problem requested.  I figure out this after
reading Andre Somers response.  Nevertheless, this solution somehow
relates to the problem, so I think it is worth to post it.

The problem that I solved is:

	There is a model, and you need to align somehow items when
	drawing it.

Take a look at

QVariant QAbstractItemModel::data(..., role = Qt::DisplayRole)
http://doc.qt.nokia.com/4.7/qabstractitemmodel.html#data

enum Qt::ItemDataRole
http://doc.qt.nokia.com/4.7/qt.html#ItemDataRole-enum

enum Qt::AlignmentFlag
http://doc.qt.nokia.com/4.7/qt.html#AlignmentFlag-enum

If you can modify the code of your model, then the easy way is just
return Qt::Align*** for Qt::TextAlignmentRole from your data() method.
This is all that you need.

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
/* virtual */ QVariant data(const QModelIndex &index, int role) const
{
	if (role == Qt::TextAlignmentRole) {
		return Qt::AlignRight;
	}
	...
}
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

If you can't modify the code of your model, then take a look at
QSortFilterProxyModel.

QSortFilterProxyModel
http://doc.qt.nokia.com/4.7/qsortfilterproxymodel.html

The idea is the same -- just intercept data() call and return whatever
you want for Qt::TextAlignmentRole.

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
#include <QtGui/QApplication>
#include <QtGui/QFileSystemModel>
#include <QtGui/QSortFilterProxyModel>
#include <QtGui/QTreeView>

class TextAlignmentReplacement : public QSortFilterProxyModel
{
	Q_OBJECT
public:
	typedef QSortFilterProxyModel Ancestor;

	TextAlignmentReplacement(QObject *parent = 0)
		: Ancestor(parent)
	{}

	/* virtual */ QVariant data(const QModelIndex &index, int role) const
	{
		if (role == Qt::TextAlignmentRole) {
			return Qt::AlignRight;
		}
		return Ancestor::data(index, role);
	}
};

#include "main.moc"

int main(int argc, char *argv[])
{
	QApplication app(argc, argv);

	QFileSystemModel model;
	model.setRootPath("");

	TextAlignmentReplacement proxy;
	proxy.setSourceModel(&model);

	QTreeView view;
	view.setModel(&proxy);
	view.show();

	return app.exec();
}
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -



More information about the Qt-interest-old mailing list