PyQt5 文本输入框自动补全QLineEdit的实现示例


Posted in Python onMay 13, 2020

一、QCompleter类

自动补全会用到的一个类

PyQt5 文本输入框自动补全QLineEdit的实现示例

主要代码

def init_lineedit(self):
    # 增加自动补全
    self.completer = QCompleter(items_list)
    # 设置匹配模式 有三种: Qt.MatchStartsWith 开头匹配(默认) Qt.MatchContains 内容匹配 Qt.MatchEndsWith 结尾匹配
    self.completer.setFilterMode(Qt.MatchContains)
    # 设置补全模式 有三种: QCompleter.PopupCompletion(默认) QCompleter.InlineCompletion  QCompleter.UnfilteredPopupCompletion
    self.completer.setCompletionMode(QCompleter.PopupCompletion) 
    # 给lineedit设置补全器
    self.lineedit.setCompleter(self.completer)


  def init_combobox(self):
    # 增加选项元素
    for i in range(len(items_list)):
      self.combobox.addItem(items_list[i])
    self.combobox.setCurrentIndex(-1)

    # 增加自动补全
    self.completer = QCompleter(items_list)
    self.completer.setFilterMode(Qt.MatchContains)
    self.completer.setCompletionMode(QCompleter.PopupCompletion)
    self.combobox.setCompleter(self.completer)

完整代码:

import sys
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *
################################################

items_list=["C","C++","Java","Python","JavaScript","C#","Swift","go","Ruby","Lua","PHP"]

################################################
class Widget(QWidget):
  def __init__(self, *args, **kwargs):
    super(Widget, self).__init__(*args, **kwargs)
    layout = QHBoxLayout(self)
    self.lineedit = QLineEdit(self, minimumWidth=200)
    self.combobox = QComboBox(self, minimumWidth=200)
    self.combobox.setEditable(True)

    layout.addWidget(QLabel("QLineEdit", self))
    layout.addWidget(self.lineedit)
    layout.addItem(QSpacerItem(20, 20, QSizePolicy.Expanding, QSizePolicy.Minimum))

    layout.addWidget(QLabel("QComboBox", self))
    layout.addWidget(self.combobox)

    #初始化combobox
    self.init_lineedit()
    self.init_combobox()

    #增加选中事件
    self.combobox.activated.connect(self.on_combobox_Activate)

  def init_lineedit(self):
    # 增加自动补全
    self.completer = QCompleter(items_list)
    # 设置匹配模式 有三种: Qt.MatchStartsWith 开头匹配(默认) Qt.MatchContains 内容匹配 Qt.MatchEndsWith 结尾匹配
    self.completer.setFilterMode(Qt.MatchContains)
    # 设置补全模式 有三种: QCompleter.PopupCompletion(默认) QCompleter.InlineCompletion  QCompleter.UnfilteredPopupCompletion
    self.completer.setCompletionMode(QCompleter.PopupCompletion)
    # 给lineedit设置补全器
    self.lineedit.setCompleter(self.completer)

  def init_combobox(self):
    # 增加选项元素
    for i in range(len(items_list)):
      self.combobox.addItem(items_list[i])
    self.combobox.setCurrentIndex(-1)

    # 增加自动补全
    self.completer = QCompleter(items_list)
    self.completer.setFilterMode(Qt.MatchContains)
    self.completer.setCompletionMode(QCompleter.PopupCompletion)
    self.combobox.setCompleter(self.completer)

  def on_combobox_Activate(self, index):
    print(self.combobox.count())
    print(self.combobox.currentIndex())
    print(self.combobox.currentText())
    print(self.combobox.currentData())
    print(self.combobox.itemData(self.combobox.currentIndex()))
    print(self.combobox.itemText(self.combobox.currentIndex()))
    print(self.combobox.itemText(index))

if __name__ == "__main__":
  app = QApplication(sys.argv)
  w = Widget()
  w.show()
  sys.exit(app.exec_())

二、QStandardItemModel类

最终效果

PyQt5 文本输入框自动补全QLineEdit的实现示例

PyQt5 文本输入框自动补全QLineEdit的实现示例

import sys

# from PyQt5.Qt import QCompleter
from PyQt5.Qt import QStandardItemModel
from PyQt5.QtCore import Qt
from PyQt5.QtCore import pyqtSlot
from PyQt5.QtCore import pyqtSignal
from PyQt5.QtWidgets import QFrame
from PyQt5.QtWidgets import QLabel
from PyQt5.QtWidgets import QWidget
from PyQt5.QtWidgets import QLineEdit
from PyQt5.QtWidgets import QTextEdit
from PyQt5.QtWidgets import QCompleter
from PyQt5.QtWidgets import QSizePolicy
from PyQt5.QtWidgets import QMainWindow
from PyQt5.QtWidgets import QPushButton
from PyQt5.QtWidgets import QGridLayout
from PyQt5.QtWidgets import QApplication

from View import interface

class MainWindow(QMainWindow):

  def __init__(self):
    super(MainWindow,self).__init__(None)
    self.setWindowTitle("对金属腐蚀性试验仪")
    self.initUI()

  def initUI(self):
    layout = QGridLayout()
    layout.setSpacing(10)
    self.loginLabel = QLabel("邮箱:")
    self.loginLabel.setAlignment(Qt.AlignRight)
    self.loginLabel.setStyleSheet("color:rgb(20,20,20,255);font-size:16px;font-weight:bold:text")

    self.loginTxt = QLineEdit()
    self.loginTxt.setText("admin")
    self.loginTxt.setPlaceholderText("User Name")
    self.loginTxt.setClearButtonEnabled(True)
    self.loginTxt.textChanged.connect(self.on_loginTxt_textChanged) #绑定槽函数
    self.m_model = QStandardItemModel(0, 1, self)
    m_completer = QCompleter(self.m_model, self)
    self.loginTxt.setCompleter(m_completer)
    m_completer.activated[str].connect(self.onTxtChoosed)


    self.pwdLabel = QLabel("密码:")
    self.pwdLabel.setAlignment(Qt.AlignRight)
    self.pwdTxt = QLineEdit()
    self.pwdTxt.setContextMenuPolicy(Qt.NoContextMenu) #禁止复制粘贴
    self.pwdTxt.setPlaceholderText("Password")
    self.pwdTxt.setText("admin")
    self.pwdTxt.setEchoMode(QLineEdit.Password)
    self.pwdTxt.setClearButtonEnabled(True)
    self.registeredBtn = QPushButton("注册")
    self.loginBtn = QPushButton("登陆")

    self.headLabel = QLabel("用户登陆")
    self.headLabel.resize(300,30)
    self.headLabel.setAlignment(Qt.AlignCenter)
    self.headLabel.setStyleSheet("color:rgb(10,10,10,255);font-size:25px;font-weight:bold;font-family:Roman times;")

    self.headLabel.setSizePolicy(QSizePolicy.Expanding,QSizePolicy.Expanding)
    layout.addWidget(self.headLabel,0,0,1,2)
    policy = self.headLabel.sizePolicy()
    print(policy.verticalPolicy())
    policy.setVerticalPolicy(1)
    print(policy.verticalPolicy())
    # policy.setVerticalPolicy(1)
    layout.addWidget(self.loginLabel,1,0)
    layout.addWidget(self.loginTxt,1,1)
    layout.addWidget(self.pwdLabel,2,0)
    layout.addWidget(self.pwdTxt,2,1)
    layout.addWidget(self.registeredBtn,3,0)
    layout.addWidget(self.loginBtn,3,1)

    frame = QFrame(self)
    frame.setLayout(layout)
    self.setCentralWidget(frame)
    self.resize(300,150)

  def onTxtChoosed(self, txt):
    self.loginTxt.setText(txt)

  @pyqtSlot(str)
  def on_loginTxt_textChanged(self, text):
    if '@' in self.loginTxt.text():
      return

    emaillist = ["@163.com", "@qq.com", "@gmail.com", "@live.com", "@126.com", "@139.com"]
    self.m_model.removeRows(0, self.m_model.rowCount())
    for i in range(0, len(emaillist)):
      self.m_model.insertRow(0)
      self.m_model.setData(self.m_model.index(0, 0), text + emaillist[i])

if __name__ == '__main__':
  app = QApplication(sys.argv)
  mainWindow = MainWindow()
  mainWindow.show()
  mainWindow.activateWindow()
  mainWindow.raise_()
  app.exec_()
  del mainWindow
  del app

QStandardItemModel类为存储自定义数据提供了一个通用模型。

QStandardItemModel可以用作标准Qt数据类型的存储库。它是模型/视图类之一,是Qt的模型/视图框架的一部分。

QStandardItemModel提供了一个经典的基于项目的方法来处理模型。 QStandardItemModel中的项目由QStandardItem提供。

QStandardItemModel实现了QAbstractItemModel接口,这意味着该模型可用于在支持该接口的任何视图(如QListView,QTableView和QTreeView以及您自己的自定义视图)中提供数据。为了提高性能和灵活性,您可能希望子类QAbstractItemModel为不同类型的数据存储库提供支持。例如,QDirModel为底层文件系统提供了一个模型接口。

当你想要一个列表或树时,你通常会创建一个空的QStandardItemModel并使用appendRow()向模型添加项目,使用item()来访问项目。如果您的模型表示一个表格,您通常会将表格的维度传递给QStandardItemModel构造函数,并使用setItem()将项目放入表格中。您还可以使用setRowCount()和setColumnCount()来更改模型的尺寸。要插入项目,请使用insertRow()或insertColumn(),并删除项目,请使用removeRow()或removeColumn()。

您可以使用setHorizontalHeaderLabels()和setVerticalHeaderLabels()来设置模型的标题标签。

您可以使用findItems()在模型中搜索项目,并通过调用sort()对模型进行排序。

调用clear()从模型中移除所有项目。

2.2 代码理解

self.loginTxt = QLineEdit()
    self.loginTxt.setText("admin")
    self.loginTxt.setPlaceholderText("User Name")
    self.loginTxt.setClearButtonEnabled(True)
0    self.loginTxt.textChanged.connect(self.on_loginTxt_textChanged) #绑定槽函数
1    self.m_model = QStandardItemModel(0, 1, self)
2    m_completer = QCompleter(self.m_model, self)
3    self.loginTxt.setCompleter(m_completer)
4    m_completer.activated[str].connect(self.onTxtChoosed)


  def onTxtChoosed(self, txt):
    self.loginTxt.setText(txt)

  @pyqtSlot(str)
  def on_loginTxt_textChanged(self, text):
    if '@' in self.loginTxt.text():
      return

    emaillist = ["@163.com", "@qq.com", "@gmail.com", "@live.com", "@126.com", "@139.com"]
    self.m_model.removeRows(0, self.m_model.rowCount())
    for i in range(0, len(emaillist)):
      self.m_model.insertRow(0)
      self.m_model.setData(self.m_model.index(0, 0), text + emaillist[i])

0-将文本改变信号连接到on_loginTxt_textChanged 函数处理

  • 构建一个0行一列的新项目模型。self.m_model = QStandardItemModel(0, 1, self)
  • 用给定的父对象,构造一个补全(完成)对象,该对象提供来自指定模型的完成对象,这里就是self.m_model. m_completer = QCompleter(self.m_model, self)
  • 将我们想要自动补全、完成的文本输入框对象设置关联上面创建的 补全(完成对象)
  • QCompleter.activated;如果文本框的当前项目发生更改,则会发出两个信号currentIndexChanged()和activated()。无论以编程方式或通过用户交互完成更改,currentIndexChanged()总是被发射,而只有当更改是由用户交互引起时才activated() 。highlighted()信号在用户突出显示组合框弹出列表中的项目时发出。所有三个信号都有两个版本,一个带有str参数,另一个带有int参数。如果用户选择或突出显示一个图像,则只会发出int信号。每当可编辑组合框的文本发生改变时,editTextChanged()信号就会发出。所以讲activated信号连接到用户选择文本处理函数上

参考连接

到此这篇关于PyQt5 文本输入框自动补全QLineEdit的实现示例的文章就介绍到这了,更多相关PyQt5 文本输入框自动补全内容请搜索三水点靠木以前的文章或继续浏览下面的相关文章希望大家以后多多支持三水点靠木!

Python 相关文章推荐
Linux下Python获取IP地址的代码
Nov 30 Python
Python的Tornado框架实现异步非阻塞访问数据库的示例
Jun 30 Python
win10环境下python3.5安装步骤图文教程
Feb 03 Python
python3之微信文章爬虫实例讲解
Jul 12 Python
python tensorflow基于cnn实现手写数字识别
Jan 01 Python
浅谈Python中的全局锁(GIL)问题
Jan 11 Python
Pycharm新手教程(只需要看这篇就够了)
Jun 18 Python
PyQt 图解Qt Designer工具的使用方法
Aug 06 Python
Python循环实现n的全排列功能
Sep 16 Python
Python 3.6打包成EXE可执行程序的实现
Oct 18 Python
python图的深度优先和广度优先算法实例分析
Oct 26 Python
仅用几行Python代码就能复制她的U盘文件?
Jun 26 Python
django自带的权限管理Permission用法说明
May 13 #Python
Python基于jieba, wordcloud库生成中文词云
May 13 #Python
django admin 根据choice字段选择的不同来显示不同的页面方式
May 13 #Python
Jupyter notebook如何实现指定浏览器打开
May 13 #Python
基于FME使用Python过程图解
May 13 #Python
django rest framework serializers序列化实例
May 13 #Python
Python+Django+MySQL实现基于Web版的增删改查的示例代码
May 13 #Python
You might like
用PHP连mysql和oracle数据库性能比较
2006/10/09 PHP
php学习笔记 数组的常用函数
2011/06/13 PHP
php和mysql中uft-8中文编码乱码的几种解决办法
2012/04/19 PHP
PHP中的use关键字概述
2014/07/23 PHP
php生成RSS订阅的方法
2015/02/13 PHP
PHP加密解密类实例分析
2015/04/20 PHP
基于PHP实现用户在线状态检测
2020/11/10 PHP
javascript函数库-集合框架
2007/04/27 Javascript
网站导致浏览器崩溃的原因总结(多款浏览器) 推荐
2010/04/15 Javascript
三级下拉菜单的js实现代码
2011/05/23 Javascript
JavaScript模块规范之AMD规范和CMD规范
2015/10/27 Javascript
JS实现兼容性较好的随屏滚动效果
2015/11/09 Javascript
jQuery中cookie插件用法实例分析
2015/12/04 Javascript
JavaScript基础重点(必看)
2016/07/09 Javascript
JS添加或修改控件的样式(Class)实现方法
2016/10/15 Javascript
jQuery Validate格式验证功能实例代码(包括重名验证)
2017/07/18 jQuery
Angular.js初始化之ng-app的自动绑定与手动绑定详解
2017/07/31 Javascript
element-ui 上传图片后清空图片显示的实例
2018/09/04 Javascript
VUE2.0+ElementUI2.0表格el-table循环动态列渲染的写法详解
2018/11/30 Javascript
vue filter 完美时间日期格式的代码
2019/08/14 Javascript
浅谈Vue3.0新版API之composition-api入坑指南
2020/04/30 Javascript
[11:42]2018DOTA2国际邀请赛寻真——OG卷土重来
2018/08/17 DOTA
[01:06:25]Secret vs Liquid 2018国际邀请赛淘汰赛BO3 第一场 8.25
2018/08/29 DOTA
Python对切片命名的实现方法
2018/10/16 Python
浅谈pymysql查询语句中带有in时传递参数的问题
2020/06/05 Python
Python更改pip镜像源的方法示例
2020/12/01 Python
洛杉矶生活休闲而精致的基础品牌:Mika Jaymes
2018/01/07 全球购物
局域网定义和特性
2016/01/23 面试题
5个HTML5的常用本地存储方式详解与介绍
2021/03/27 HTML / CSS
日语专业推荐信
2013/11/12 职场文书
歌唱比赛获奖感言
2014/01/21 职场文书
2014政府领导班子对照检查材料思想汇报(3篇)
2014/09/26 职场文书
助学金感谢信
2015/01/20 职场文书
tensorflow+k-means聚类简单实现猫狗图像分类的方法
2021/04/28 Python
python随机打印成绩排名表
2021/06/23 Python
html5+实现plus.io进行拍照和图片等获取
2022/06/01 HTML / CSS