0

我有 2QTextEdit个小部件,我需要将第一个到第二个中输入的任何内容放在按下回车键 ( 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)

任何帮助表示赞赏我被卡住了.....

4

2 回答 2

2

使用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)
于 2013-01-31T14:08:52.560 回答
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_())
于 2013-02-01T04:34:04.443 回答