QLineEditUnit.h
#pragma once
#include <QLineEdit>
#include <QPushButton>
class QLineEditUnit : public QLineEdit
{
Q_OBJECT
public:
QLineEditUnit(QWidget* parent = Q_NULLPTR);
~QLineEditUnit();
//获取编辑框单位
QString UnitText()const;
//设置编辑框单位
void SetUnitText(const QString& unitText);
private:
QPushButton* m_unitButton = nullptr;//单位文本按钮
};
QUnitLineEdit.cpp
#include "QLineEditUnit.h"
#include <QLayout>
#include <QStyle>
QLineEditUnit::QLineEditUnit(QWidget* parent) : QLineEdit(parent)
{
m_unitButton = new QPushButton;
//单位按钮扁平无边框
m_unitButton->setStyleSheet("border-style:solid;color: rgba(77, 155, 213, 1);");
m_unitButton->setFlat(true);
//单位加入布局
QBoxLayout* layout = new QBoxLayout(QBoxLayout::LeftToRight);
layout->addStretch();
layout->setSpacing(0);
//单位按钮的Margins
//右边留了13px,留给单位(按钮)
layout->setContentsMargins(0, 0, 13, 0);
layout->addWidget(m_unitButton);
this->setLayout(layout);
}
QLineEditUnit::~QLineEditUnit()
{
}
QString QLineEditUnit::UnitText() const
{
return this->m_unitButton->text();
}
void QLineEditUnit::SetUnitText(const QString& unitText)
{
if (unitText.isEmpty() || this->m_unitButton->text() == unitText)
{
return;
}
m_unitButton->setFont(this->font());
this->m_unitButton->setText(unitText);
// this->m_unitButton->setVisible(true);
//获得文字的宽度
int width = this->fontMetrics().width(m_unitButton->text());
m_unitButton->setFixedWidth(width);
//到单位开头了就往下显示,防止往后输入的内容有一部分在按钮下面
QBoxLayout* layout = (QBoxLayout*)this->layout();
QMargins margins = layout->contentsMargins();
setTextMargins(margins.left(), margins.top(), width + margins.right(), margins.bottom());
}
然后再界面,先拖拽一个lineEdit,然后右键提升
所有的lineEdit都提升为带单位的
把lineEdit的指针强制类型转换成带单位的指针
其实好像我做的强制类型转换没什么必要,多此一举
可以直接用