PyQt5 - QLineEdit 控制元件



QLineEdit 物件是最常用的輸入欄位。它提供了一個可以輸入單行文字的框。要輸入多行文字,需要使用QTextEdit 物件。

下表列出了 QLineEdit 類的一些重要方法:

序號 方法及描述
1

setAlignment()

根據對齊常量對齊文字

Qt.AlignLeft

Qt.AlignRight

Qt.AlignCenter

Qt.AlignJustify

2

clear()

清除內容

3

setEchoMode()

控制框內文字的外觀。回顯模式值如下:

QLineEdit.Normal

QLineEdit.NoEcho

QLineEdit.Password

QLineEdit.PasswordEchoOnEdit

4

setMaxLength()

設定輸入字元的最大數量

5

setReadOnly()

使文字框不可編輯

6

setText()

以程式設計方式設定文字

7

text()

檢索欄位中的文字

8

setValidator()

設定驗證規則。可用的驗證器有:

QIntValidator - 將輸入限制為整數

QDoubleValidator - 小數部分限制為指定的小數位數

QRegexpValidator - 根據正則表示式檢查輸入

9

setInputMask()

應用字元組合的掩碼進行輸入

10

setFont()

顯示 QFont 物件的內容

QLineEdit 物件發出以下訊號:

以下是訊號最常用的方法。

序號 方法及描述
1

cursorPositionChanged()

游標移動時

2

editingFinished()

按下“Enter”鍵或欄位失去焦點時

3

returnPressed()

按下“Enter”鍵時

4

selectionChanged()

選中文字發生變化時

5

textChanged()

框中的文字透過輸入或以程式設計方式發生變化時

6

textEdited()

文字被編輯時

示例

此示例中的 QLineEdit 物件演示了其中一些方法的使用。

第一個欄位e1使用自定義字型顯示文字,右對齊,並允許整數輸入。第二個欄位將輸入限制為小數點後兩位的數字。第三個欄位應用了用於輸入電話號碼的輸入掩碼。欄位e4上的 textChanged() 訊號連線到 textchanged() 槽方法。

e5欄位的內容以密碼形式回顯,因為其 EchoMode 屬性設定為 Password。它的 editingFinished() 訊號連線到 presenter() 方法。因此,一旦使用者按下 Enter 鍵,該函式就會執行。欄位e6顯示預設文字,該文字不可編輯,因為它被設定為只讀。

import sys
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
def window():
   app = QApplication(sys.argv)
   win = QWidget()
	
   e1 = QLineEdit()
   e1.setValidator(QIntValidator())
   e1.setMaxLength(4)
   e1.setAlignment(Qt.AlignRight)
   e1.setFont(QFont("Arial",20))
	
   e2 = QLineEdit()
   e2.setValidator(QDoubleValidator(0.99,99.99,2))
	
   flo = QFormLayout()
   flo.addRow("integer validator", e1)
   flo.addRow("Double validator",e2)
	
   e3 = QLineEdit()
   e3.setInputMask('+99_9999_999999')
   flo.addRow("Input Mask",e3)
	
   e4 = QLineEdit()
   e4.textChanged.connect(textchanged)
   flo.addRow("Text changed",e4)
	
   e5 = QLineEdit()
   e5.setEchoMode(QLineEdit.Password)
   flo.addRow("Password",e5)
	
   e6 = QLineEdit("Hello Python")
   e6.setReadOnly(True)
   flo.addRow("Read Only",e6)
	
   e5.editingFinished.connect(enterPress)
   win.setLayout(flo)
   win.setWindowTitle("PyQt")
   win.show()
	
   sys.exit(app.exec_())

def textchanged(text):
   print "contents of text box: "+text
	
def enterPress():
   print "edited"

if __name__ == '__main__':
   window()

輸出

以上程式碼產生以下輸出:

QLineEdit Widget Output
contents of text box: h
contents of text box: he
contents of text box: hel
contents of text box: hell
contents of text box: hello
editing finished
pyqt_basic_widgets.htm
廣告

© . All rights reserved.