QLineEdit自动补全:模拟QQ登录补全账号

2022-07-25,,,,

效果图如下:

首先介绍Qt的QCompleter类,官方文档介绍如下:
You can use QCompleter to provide auto completions in any Qt widget, such as QLineEdit and QComboBox. When the user starts typing a word, QCompleter suggests possible ways of completing the word, based on a word list. The word list is provided as a QAbstractItemModel. (For simple applications, where the word list is static, you can pass a QStringList to QCompleter’s constructor.)
您可以使用QCompleter在任何Qt部件(如QLineEdit和QComboBox)中提供自动完成。当用户开始键入一个单词时,QCompleter根据一个单词列表提出了完成该单词的可能方法。单词列表是作为一个QacuactItemModel提供的。(对于简单的应用程序,单词列表是静态的,可以将QStringList传递给QCompleter的构造函数。)
关于QCompleter介绍

QLineEdit使用QCompleter构建补全器

m_LineEdit = new QLineEdit();
m_LineEdit->setCompleterByList(m_userIdList);
ui.comboBox_userName->setLineEdit(m_vvLineEdit);

关于QCompleter补全下拉框的样式优化

	m_Completer->popup()->setStyleSheet(
		"QListView{"
		//"font-family: 微软雅黑;"
		"font-size: 16px;"
		"outline:0px;"
		"border: 1px solid rgba(0,0,0,10%);"
		"text-align: left;"
		//"padding-left:23px;"
		"}");

	//显示个数
	m_Completer->setMaxVisibleItems(4);

以上只是构建了输入账号时类似QComboBox提示,还不能做到自动在QLineEdit上补全后续内容。
模拟qq登录的效果,需要重载QLineEdit输入响应信号textEdited。
在记录输入内容的时候,需要记录上一次输入的内容
m_oldLineEditText:上一次记录的值
setUserPassWord():补全密码方法(省略)

connect(ui.comboBox_userName->lineEdit(), &QLineEdit::textEdited, this, [=](QString txt) {
		if (txt.isEmpty()) {
			m_oldLineEditText = txt;
			return;
		}
		if (m_oldLineEditText.size() >= txt.size()) {
			m_oldLineEditText = txt;
			return;
		}
		m_oldLineEditText = txt;
		QStringList result = m_userIdList.filter(txt);
		if (!result.isEmpty()) {
			QString firstUserId = result[0];
			int index = firstUserId.indexOf(txt);
			if (0 == index) {
				ui.comboBox_userName->lineEdit()->setText(firstUserId);
				setUserPassWord(firstUserId);
				ui.comboBox_userName->lineEdit()->setSelection(txt.size(), firstUserId.size());
			}
		}
	});

代码比较粗糙,各位若有所改进,望相告,多谢~

本文地址:https://blog.csdn.net/qq_36651243/article/details/111885139

《QLineEdit自动补全:模拟QQ登录补全账号.doc》

下载本文的Word格式文档,以方便收藏与打印。