如何使用widget PlainTextEdit或TextEdit输出和输入文本?

时间:2009-09-08 21:08:19

标签: python user-interface qt

如何使用widget PlainTextEdit或TextEdit输出和输入文本?我对PyQt4感兴趣。

2 个答案:

答案 0 :(得分:3)

答案 1 :(得分:0)

您需要更具体,但无论如何,以下代码将创建一个带有TextEdit的对话框,该对话框将显示输入文件: from PyQt4 import QtCore, QtGui

def read_file(file):
    """
    Returns all contents of file
    """
    result = ""
    with open(file) as f:
        for line in f:
           result+= line
    return result

class ExampleDialog(QtGui.QDialog):

    def __init__(Self, parent, file):
        QtGui.QDialog.__init__(self, parent)
        # create main layout of the dialog
        layout = QtGui.QVBoxLayout()
        layout.addWidget(QLabel(self.tr("Contents of file:"))
        edit = QtGui.QPlainTextEdit(self)
        # read the file and get the content
        edit.appendPlainText(read_file(file))
        layout.addWidget(edit)
        self.setLayout(layout)

file = "hello.txt"
dialog = ExampleDialog(None, file)
dialog.exec_()

def read_file(file): """ Returns all contents of file """ result = "" with open(file) as f: for line in f: result+= line return result class ExampleDialog(QtGui.QDialog): def __init__(Self, parent, file): QtGui.QDialog.__init__(self, parent) # create main layout of the dialog layout = QtGui.QVBoxLayout() layout.addWidget(QLabel(self.tr("Contents of file:")) edit = QtGui.QPlainTextEdit(self) # read the file and get the content edit.appendPlainText(read_file(file)) layout.addWidget(edit) self.setLayout(layout) file = "hello.txt" dialog = ExampleDialog(None, file) dialog.exec_() 以上只是QDialog的一个例子,但应该足以让你开始。

希望它有所帮助!