c++ - 将 QLabel 对齐设置为右侧并在右侧剪切文本
问题描述
我正在用 C++ 编写一个 Qt 4.8(我们不能为这个项目使用更新的 Qt 版本)应用程序,我有各种 QLabels,它们必须右对齐,并且其文本在代码中动态设置。但是如果文本超过 QLabel 的大小,它会在左侧被剪裁。然而,所需的行为是剪辑右侧的文本。
例如,包含客户名称“Abraham Lincoln”的 QLabel 会将文本剪辑为“aham Lincoln”而不是“Abraham Li”。有没有内置的方法可以做到这一点,还是我必须根据文本长度动态移动和调整 QLabel 的大小?
解决方案
QLabel
不幸的是,我认为您无法完全实现您想要的。但是您可以尝试以一种方式管理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
。
推荐阅读
- flutter - 如何检查密钥是否存在共享首选项值然后打开一个新屏幕
- javascript - 重写 javascript 函数以避免 JQuery.json 文件不被服务器读取
- java - 在java中具有相同值的另一个节点之前插入一个节点
- c# - 在避免stackoverflow异常的同时使用stackalloc的任何方式
- reactjs - React Router + Animation 库问题:组件在使用 react-router-dom 卸载之前不会动画
- java - 为什么部署在heroku中的tomcat中的PUT方法的请求参数始终为NULL
- npm - “找不到命令:create-nuxt-app”有什么问题
- python - Python 中 PillowWriter 导出到 .gif 时出错
- flutter - 颤动中的不可滚动网格
- python - 如何将 keras 顺序 API 转换为功能 API