Reputation: 35
I have 2 QTextEdit
widgets and I need to put whatever is entered in the first to the second on a press of the enter key (Return
).... I am not able to implement it please help?
I know I need to use KeyPressEvent
but I don't understand how to use it only for the 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)
Any help is appreciated I am stuck.....
Upvotes: 0
Views: 5169
Reputation: 20353
Use the viewportEvent
(inherited from 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
You can use Qt.Key_Enter
but I think you probably want Qt.Key_Return
If you are using an older version of PySide
without new style signals and slots you'll need to use
self.connect(self.textEdit, SIGNAL("viewportEvent(event)"), self.copy_the_text)
Upvotes: 2
Reputation: 36715
Here is a small example that shows QLineEdit
and its returnPressed
signal. Upon pressing return the text in the QLineEdit
will be appended to the 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_())
Upvotes: 1