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 相关文章推荐
python调用短信猫控件实现发短信功能实例
Jul 04 Python
python中使用mysql数据库详细介绍
Mar 27 Python
Python远程桌面协议RDPY安装使用介绍
Apr 15 Python
python实现贪吃蛇小游戏
Mar 21 Python
python re库的正则表达式入门学习教程
Mar 08 Python
详解python selenium 爬取网易云音乐歌单名
Mar 28 Python
python3调用windows dos命令的例子
Aug 14 Python
windows下Python安装、使用教程和Notepad++的使用教程
Oct 06 Python
python读取tif图片时保留其16bit的编码格式实例
Jan 13 Python
利用PyTorch实现VGG16教程
Jun 24 Python
Python 必须了解的5种高级特征
Sep 10 Python
在pycharm创建scrapy项目的实现步骤
Dec 01 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
40个迹象表明你还是PHP菜鸟
2008/09/29 PHP
php编程实现获取excel文档内容的代码实例
2011/06/28 PHP
php取整函数ceil,floo,round的用法及介绍
2013/08/31 PHP
PHP判断JSON对象是否存在的方法(推荐)
2016/07/06 PHP
Yii2中YiiBase自动加载类、引用文件方法分析(autoload)
2016/07/25 PHP
php使用curl详细解析及问题汇总
2016/08/11 PHP
浅谈PHP定义命令空间的几个注意点(推荐)
2016/10/29 PHP
JS 获取浏览器和屏幕宽高等信息的实现思路及代码
2013/07/31 Javascript
两个数组去重的JS代码
2013/12/04 Javascript
将中国标准时间转换成标准格式的代码
2014/03/20 Javascript
jquery库文件略庞大用纯js替换jquery的方法
2014/08/12 Javascript
深入分析原生JavaScript事件
2014/12/29 Javascript
解析微信JS-SDK配置授权,实现分享接口
2016/12/09 Javascript
JavaScript数组_动力节点Java学院整理
2017/06/26 Javascript
简单实现js鼠标跟随效果
2020/08/02 Javascript
谈谈对vue响应式数据更新的误解
2017/08/01 Javascript
vue-router重定向不刷新问题的解决
2018/06/25 Javascript
JS实现简单tab选项卡切换
2019/10/25 Javascript
vue实现把接口单独存放在一个文件方式
2020/08/13 Javascript
JavaScript实现世界各地时间显示
2020/09/07 Javascript
详解React中共享组件逻辑的三种方式
2021/02/02 Javascript
[56:35]DOTA2上海特级锦标赛主赛事日 - 5 总决赛Liquid VS Secret第一局
2016/03/06 DOTA
Python通过调用有道翻译api实现翻译功能示例
2018/07/19 Python
Python Socket编程之多线程聊天室
2018/07/28 Python
python生成每日报表数据(Excel)并邮件发送的实例
2019/02/03 Python
网站性能延迟加载图像的五种技巧(小结)
2020/08/13 HTML / CSS
将一个数的从第5位开始的7个数取出,其余位置0
2016/05/26 面试题
如何查看在weblogic中已经发布的EJB
2012/06/01 面试题
国际金融专业大学生职业生涯规划书
2013/12/28 职场文书
西式婚礼主持词
2014/03/13 职场文书
党的群众路线对照检查材料
2014/08/27 职场文书
部门2014年度工作总结
2014/11/12 职场文书
质量保证书怎么写
2015/02/27 职场文书
2015年七夕情人节活动方案
2015/05/06 职场文书
行政上诉状范文
2015/05/23 职场文书
新课程改革心得体会
2016/01/22 职场文书