PyQt 多行文本输入框

问题描述 投票:0回答:2

我正在使用 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()
python pyqt pyqt4 pyqt5
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 的更新答案,以防其他人正在寻找类似的内容:

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_())

Q纯文本编辑

Q按钮

© www.soinside.com 2019 - 2024. All rights reserved.