PyQt5 QLineEdit自动补全

自动补全的应用

QLineEdit自动补全的功能经常应用于输入邮箱等场合,会自动提供补全项。
QLineEdit自动补全的功能需要用到QCompleter类。
可以使用QCompleter在任何Qt小部件中提供自动完成功能,例如QLineEdit和QComboBox

自动补全的举例1

  • 新建QCompleter对象,并设置其匹配模式,补全模式等。
  • 设置对象的setCompleter()
import sys
from PyQt5 import QtWidgets
from PyQt5.Qt import *

# 选项列表
items_list = ["Python", "C sharp", "AMD", "Anlogic", "ROS2", "STM32"]


class Widget(QtWidgets.QWidget):
    def __init__(self):
        super().__init__()

        # 设置水平布局管理, 如果不加self, 最后要使用setLayout指定,如果有,则不需要。
        layout = QtWidgets.QHBoxLayout(self)

        # 创建文本框和组合框
        self.line_edit = QtWidgets.QLineEdit(self)
        self.combo_box = QtWidgets.QComboBox(self)
        self.combo_box.setEditable(True)        # 可以输入

        # 添加label和QlineEdit
        layout.addWidget(QtWidgets.QLabel("QLineEdit", self))
        layout.addWidget(self.line_edit)

        # 设置空白区
        layout.addItem(QtWidgets.QSpacerItem(20, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum))

        # 添加标题和组合框
        layout.addWidget(QtWidgets.QLabel("QComboBox", self))
        layout.addWidget(self.combo_box)

        # 增加组合框选项元素及设置初始选中值
        for i in range(len(items_list)):
            self.combo_box.addItem(items_list[i])
        self.combo_box.setCurrentIndex(-1)

        # 配置自动补全
        self.auto_complete()

    def auto_complete(self):
        """
        配置自动补全函数
        """
        # 设置匹配模式  有三种: Qt.MatchStartsWith 开头匹配(默认)
        #                      Qt.MatchContains 内容匹配
        #                      Qt.MatchEndsWith 结尾匹配
        self.completer = QtWidgets.QCompleter(items_list)
        self.completer.setFilterMode(Qt.MatchContains)
        # 设置补全模式  有三种: QCompleter.PopupCompletion 弹出选项补全(默认)
        #                      QCompleter.InlineCompletion 行内显示补全
        #                      QCompleter.UnfilteredPopupCompletion 全显选项补全
        self.completer.setCompletionMode(QtWidgets.QCompleter.PopupCompletion)

        # 设置 line_edit 和 combo_box 的补全器
        self.line_edit.setCompleter(self.completer)
        self.combo_box.setCompleter(self.completer)


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

自动补全的举例2

  • 新建QStandardItemModel对象。
    • QStandardItemModel是QAbstractItemModel的派生类,用于在Model/View架构中存储自定义数据的通用模型,可以用于在任何支持QAbstractItemModel接口的view(例如QListView、QTableView和QTreeView,以及自定义视图)中作为数据存储。

    • QStandardItemModel可以用作标准Qt数据类型的数据存储Model。QStandardItemModel提供了一种经典的基于项的方法来处理模型中的数据。QStandardItemModel模型中的项对应类型必须为QStandardItem。

  • 设置对象的setCompleter(), 利用QStandardItemModel的setData方法,改变其存储的值。
  • 在使用装饰器pyqtSlot时,需要指定QMetaObject.connectSlotsByName(self),并且name要通过self.line1.setObjectName(‘line1’)指定。
import sys
from PyQt5.Qt import *


class Widget(QWidget):
    def __init__(self):
        super().__init__()
        self.line1 = QLineEdit(self)
        self.m_model = QStandardItemModel(0, 1, self)
        m_completer = QCompleter(self.m_model, self)
        self.line1.setCompleter(m_completer)
        self.email = self.line1.text()
        m_completer.activated[str].connect(self.onEmailChoosed)

        self.line1.setObjectName('line1')
        QMetaObject.connectSlotsByName(self)

    def onEmailChoosed(self):
        self.line1.setText(self.email)

    @pyqtSlot(str)
    def on_line1_textChanged(self, text):
        if '@' in self.line1.text():
            return
        email_list = ["@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(email_list)):
            self.m_model.insertRow(0)
            self.m_model.setData(self.m_model.index(0, 0), text + email_list[i])


if __name__ == "__main__":
    app = QApplication(sys.argv)
    widget = Widget()
    widget.setGeometry(100, 100, 400, 200)
    widget.show()
    sys.exit(app.exec_())

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值