Я не думаю, что вы можете достичь именно того, чего хотите, только с QLabel
, к сожалению.Но вы можете попробовать управлять a QLabel
таким образом, чтобы он выровнялся / обрезался так, как вам нужно.Кажется, что работает следующее:
#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;
};
Конечно, вам, возможно, придется добавить дополнительные функции-члены в зависимости от того, как именно вы сейчас используете QLabel
.