PyQt4 文字框

PyQt4 文字框示例

在本文中,你將學習如何使用PyQt4與文字框進行互動。

如果要在文字框 QLineEdit 中顯示文字,可以使用 setText() 方法。

PyQt4 QLineEdit

如果按下按鈕,下面的文字框示例將更改文字。

import sys
from PyQt4.QtCore import pyqtSlot
from PyQt4.QtGui import *
 
# create our window
app = QApplication(sys.argv)
w = QWidget()
w.setWindowTitle('Textbox example @pythonspot.com')
 
# Create textbox
textbox = QLineEdit(w)
textbox.move(20, 20)
textbox.resize(280,40)
 
# Set window size.
w.resize(320, 150)
 
# Create a button in the window
button = QPushButton('Click me', w)
button.move(20,80)
 
# Create the actions
@pyqtSlot()
def on_click():
    textbox.setText("Button clicked.")
 
# connect the signals to the slots
button.clicked.connect(on_click)
 
# Show the window and run the app
w.show()
app.exec_()

使用以下行建立文字欄位:

textbox = QLineEdit(w)
textbox.move(20, 20)
textbox.resize(280,40)

按鈕(來自螢幕截圖)使用:

button = QPushButton('Click me', w)

我們通過以下方式將按鈕連線到 on_click 功能:

# connect the signals to the slots
button.clicked.connect(on_click)

此函式使用 setText() 設定文字框。