#include "iconedlabel.h"
#include "qad_types.h"
#include <QHBoxLayout>
#include <QEvent>


IconedLabel::IconedLabel(QWidget * parent): QFrame(parent) {
	label_.setAlignment(Qt::AlignCenter);
	icon_.setAlignment(Qt::AlignCenter);
	icon_.setScaledContents(true);
	setIconSize(QSize());
	setDirection(RightToLeft);
}


QIcon IconedLabel::icon() const {
	return icon_.pixmap() == 0 ? QIcon() : QIcon(*icon_.pixmap());
}


bool IconedLabel::event(QEvent * e) {
	if (e->type() == QEvent::FontChange || e->type() == QEvent::Polish)
		setIconSize(iconSize());
	return QFrame::event(e);
}


QSize IconedLabel::realIconSize() const {
	return size_.isValid() ? size_ : preferredIconSize(1.f, this);
}


void IconedLabel::setIcon(const QIcon & i) {
	sicon_ = i;
	setIconSize(iconSize());
}


void IconedLabel::setIconSize(const QSize & s) {
	size_ = s;
	QSize sz = realIconSize();
	icon_.setPixmap(sicon_.pixmap(sz));
	icon_.setFixedSize(sz);
}


void IconedLabel::setDirection(IconedLabel::Direction d) {
	dir_ = d;
	if (layout() != 0)
		delete layout();
	QLayout * lay = new QBoxLayout((QBoxLayout::Direction)dir_);
	lay->addItem(new QSpacerItem(1, 1, QSizePolicy::Expanding, QSizePolicy::Expanding));
	lay->addWidget(&label_);
	lay->addWidget(&icon_);
	lay->addItem(new QSpacerItem(1, 1, QSizePolicy::Expanding, QSizePolicy::Expanding));
	lay->setContentsMargins(0, 0, 0, 0);
	setLayout(lay);
	update();
}
