Qt QLineEdit 输入内容后字数在右侧动态展示

前言

QLineEdit 设置可输入最大长度可以使用

cpp 复制代码
lineEdit->setMaxLength(10);

怎么实时的把当前输入字数显示出来呢,像饿了么的 input 组件那样

javascript 复制代码
<el-input
  type="text"
  placeholder="请输入内容"
  v-model="text"
  maxlength="10"
  show-word-limit
>
</el-input>

Qt 中 QLineEdit 配合 QLabel 也可以很方便的实现这个效果。

效果图

代码实现

cpp 复制代码
#pragma once

#include <QtWidgets/QMainWindow>
#include "ui_QLineEditDemo.h"
#include <QLineEdit>
#include <QLabel>

class QLineEditDemo : public QMainWindow
{
	Q_OBJECT

public:
	QLineEditDemo(QWidget *parent = Q_NULLPTR);

private:
	Ui::QLineEditDemoClass ui;
	QLineEdit	*lineEdit;
	QLabel		*labelMax;

private slots:
	void onEdit(const QString& text);
};
cpp 复制代码
#include "QLineEditDemo.h"

QLineEditDemo::QLineEditDemo(QWidget *parent)
	: QMainWindow(parent)
{
	ui.setupUi(this);

	// 创建输入框
	lineEdit = new QLineEdit(this);
	lineEdit->setPlaceholderText(QString::fromLocal8Bit("请输入文本"));
	lineEdit->setFixedSize(326,32);
	connect(lineEdit, &QLineEdit::textEdited, this, &QLineEditDemo::onEdit);
	
	//lineEdit 增加字数label
	lineEdit->setStyleSheet(QString::fromLocal8Bit("QLineEdit{\
		padding:6px 55px 6px 12px;\
		border-radius: 2px;\
		border: 1px solid #408cff;\
		background: #FFF;\
		font: 10pt \"微软雅黑\";\
		}"));
	labelMax = new QLabel("0/10", lineEdit);
	labelMax->setObjectName("labelMax"); // 设置子控件的对象名
	labelMax->setAlignment(Qt::AlignRight | Qt::AlignVCenter);
	labelMax->setFixedSize(45, 26); // 设置固定高,lineEditReason 32
	labelMax->setStyleSheet(QString::fromLocal8Bit("border:none;color: #cccccc;font: 10pt \"微软雅黑\";"));
	labelMax->move(326 - 45 - 10, (32 - 26) / 2); // 将label移动到lineEdit右侧 

	ui.verticalLayout->addWidget(lineEdit);

}

void QLineEditDemo::onEdit(const QString& text)
{
	int len = text.length();
	labelMax->setText(QString("%1/10").arg(len));
	if (len <= 10)
	{
		labelMax->setStyleSheet(QString::fromLocal8Bit("color: #cccccc;font: 10pt \"微软雅黑\";"));
	}
	else
	{
		labelMax->setStyleSheet(QString::fromLocal8Bit("color: #FF5050;font: 10pt \"微软雅黑\";"));
	}
}

需要注意的是,QLabel 的尺寸和移动到 QLineEdit 的位置是相关的。

如变更QLabel的尺寸,相关位置也要做调整。

另外我这里没有限制最大可输入长度,而是当超过最大长度后,将字数红色展示。

实际应用中可以和提交按钮做个联动,超过就让其不可用就好。

相关推荐
用户805533698035 天前
不止三件套:QObject 属性系统全关键字与运行时反射!
c++·qt
xcyxiner5 天前
DicomViewer (vcpkg Windows和ubuntu编译)7
qt
Quz10 天前
QML Hello World 入门示例
qt
xcyxiner13 天前
DicomViewer (dcmtk读取dcm文件)5
qt
xcyxiner13 天前
DicomViewer (后台线程处理文件)4
qt
xcyxiner14 天前
DicomViewer (添加模型类)3
qt
xcyxiner14 天前
DicomViewer (目录调整) 2
qt
xcyxiner14 天前
dcmtk vtk vtk-dicom(gdcm) 编译(debug) v2
qt
桥田智能16 天前
桥田智能 QT-650S:面向白车身焊装的 800kg 重载快换解决方案
开发语言·qt·系统架构
森G16 天前
75、服务器源码解析---------云视频服务项目
linux·服务器·网络·c++·qt