PyQt多行文本输入框

7

我正在使用PyQt,并试图为用户构建一个多行文本输入框。然而,当我运行下面的代码时,我只能输入一行文本。我该如何修复它以使用户可以输入尽可能多的文本?

   import sys
   from PyQt4.QtGui import *
   from PyQt4.QtCore import *

   def window():
       app = QApplication(sys.argv)
       w = QWidget()

       w.resize(640, 480)

       textBox = QLineEdit(w)
       textBox.move(250, 120)

       button = QPushButton("click me")
       button.move(20, 80)

       w.show()

       sys.exit(app.exec_())


   if __name__ == '__main__':
       window()
2个回答

12

QLineEdit 是一个提供单行而非多行文本输入的控件。如果需要多行文本输入,可以使用 QPlainTextEdit

import sys
from PyQt4.QtGui import *
from PyQt4.QtCore import *

def window():
    app = QApplication(sys.argv)
    w = QWidget()

    w.resize(640, 480)

    textBox = QPlainTextEdit(w)
    textBox.move(250, 120)

    button = QPushButton("click me", w)
    button.move(20, 80)

    w.show()

    sys.exit(app.exec_())


if __name__ == '__main__':
    window()

0
发布更新的答案,针对PyQt5,以防其他人也在寻找类似的内容:

widget

import sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QWidget, QPlainTextEdit, QPushButton
from PyQt5.QtCore import QSize

class ExampleWindow(QMainWindow):
    def __init__(self):
        super().__init__()

        self.setMinimumSize(QSize(440, 280))    
        self.setWindowTitle("PyQt5 Textarea example") 

        # Add text field
        self.text_edit = QPlainTextEdit(self)
        self.text_edit.move(10, 10)
        self.text_edit.resize(400, 200)

        # Add button
        self.button = QPushButton('Print Text', self)
        self.button.move(10, 220)
        self.button.resize(400, 40)
        self.button.clicked.connect(self.print_text_to_console)

    def print_text_to_console(self):
        text = self.text_edit.toPlainText()
        # Clear the box and focus on it again
        self.text_edit.setPlainText("")
        self.text_edit.setFocus()
        print(text)

if __name__ == "__main__":
    app = QApplication(sys.argv)
    mainWin = ExampleWindow()
    mainWin.show()
    sys.exit(app.exec_())

QPlainTextEdit

QPushButton


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接