textedit的Pyside按键事件

时间:2013-01-31 11:58:54

标签: python pyside

我有2个QTextEdit个小工具,我需要按下回车键(Return)将第一个输入到第二个的所有内容....我无法实现请帮忙吗?

我知道我需要使用KeyPressEvent,但我不明白如何仅将其用于QTextEdit ??

self.textEdit = QtGui.QTextEdit(self.widget)
self.textEdit.setMinimumSize(QtCore.QSize(201, 291))
self.textEdit.setMaximumSize(QtCore.QSize(201, 291))
self.textEdit.setObjectName("textEdit")
self.textEdit.setReadOnly(True)
self.verticalLayout.addWidget(self.textEdit)

self.textEdit_2 = QtGui.QTextEdit(self.widget)
self.textEdit_2.setMinimumSize(QtCore.QSize(201, 41))
self.textEdit_2.setMaximumSize(QtCore.QSize(201, 41))
self.textEdit_2.setObjectName("textEdit_2")
self.textEdit_2.setFocusPolicy(Qt.StrongFocus)
self.verticalLayout.addWidget(self.textEdit_2)

任何帮助都表示感谢我被困......

2 个答案:

答案 0 :(得分:1)

使用viewportEvent(继承自QAbstractScrollArea

    self.textEdit.viewportEvent.connect(self.copy_the_text)

    def copy_the_text(self, event):
        if isinstance(event, QtGui.QKeyEvent):  # as viewportEvent gets *all* events
            if event.key() == Qt.Key_Return or event.key() == Qt.Key_Enter:
                # copy the text from textEdit to textEdit_2

您可以使用Qt.Key_Enter,但我认为您可能需要Qt.Key_Return

修改

如果您使用的旧版PySide没有新的样式信号和插槽,则需要使用

self.connect(self.textEdit, SIGNAL("viewportEvent(event)"), self.copy_the_text)

答案 1 :(得分:1)

以下是一个显示QLineEdit及其returnPressed信号的小示例。按返回后,QLineEdit中的文字将附加到QTextEdit

import sys
from PySide import QtGui

class Window(QtGui.QWidget):
    def __init__(self, parent=None):
        super(Window, self).__init__(parent)

        self.output = QtGui.QTextEdit()
        self.output.setReadOnly(True)

        self.input = QtGui.QLineEdit()
        self.input.returnPressed.connect(self.addInput)
        self.input.setPlaceholderText('input here')

        layout = QtGui.QVBoxLayout(self)
        layout.addWidget(self.output)
        layout.addWidget(self.input)

    def addInput(self):
        # skip empty text
        if self.input.text():
            self.output.append(self.input.text())
        # clear the QLineEdit for new input
        self.input.clear()

if __name__ == '__main__':
    app = QtGui.QApplication(sys.argv)

    w = Window()
    w.show()

    sys.exit(app.exec_())