I don't think you can achieve exactly what you want with just a QLabel
unfortunately. But you could try managing a QLabel
in such a way that it aligns/trims in the way you require. The following seems to work...
#include <QFontMetrics>
#include <QLabel>
class label: public QWidget {
using super = QWidget;
public:
explicit label (const QString &text, QWidget *parent = nullptr)
: super(parent)
, m_label(text, this)
{
}
virtual void setText (const QString &text)
{
m_label.setText(text);
fixup();
}
virtual QString text () const
{
return(m_label.text());
}
protected:
virtual void resizeEvent (QResizeEvent *event) override
{
super::resizeEvent(event);
m_label.resize(size());
fixup();
}
private:
void fixup ()
{
/*
* If the text associated with m_label has a width greater than the
* width of this widget then align the text to the left so that it is
* trimmed on the right. Otherwise it should be right aligned.
*/
if (QFontMetrics(font()).boundingRect(m_label.text()).width() > width())
m_label.setAlignment(Qt::AlignLeft | Qt::AlignVCenter);
else
m_label.setAlignment(Qt::AlignRight | Qt::AlignVCenter);
}
QLabel m_label;
};
Of course you may have to add extra member functions depending on exactly how you are currently using QLabel
.