1. 程式人生 > 程式設計 >PyQt5 文字輸入框自動補全QLineEdit的實現示例

PyQt5 文字輸入框自動補全QLineEdit的實現示例

一、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,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,255);font-size:25px;font-weight:bold;font-family:Roman times;")

    self.headLabel.setSizePolicy(QSizePolicy.Expanding,QSizePolicy.Expanding)
    layout.addWidget(self.headLabel,2)
    policy = self.headLabel.sizePolicy()
    print(policy.verticalPolicy())
    policy.setVerticalPolicy(1)
    print(policy.verticalPolicy())
    # policy.setVerticalPolicy(1)
    layout.addWidget(self.loginLabel,0)
    layout.addWidget(self.loginTxt,1)
    layout.addWidget(self.pwdLabel,2,0)
    layout.addWidget(self.pwdTxt,1)
    layout.addWidget(self.registeredBtn,3,0)
    layout.addWidget(self.loginBtn,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,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,text + emaillist[i])

0-將文字改變訊號連線到on_loginTxt_textChanged 函式處理

  • 構建一個0行一列的新專案模型。self.m_model = QStandardItemModel(0,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 文字輸入框自動補全內容請搜尋我們以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援我們!