Issue
I am desperately trying to get the answer for a seems to be a very simple question. So, I have my main code which is a UI that has QTextEdit
and I want to limit characters amount to 140. The best way, in my opinion, would be reimplementing keyPressEvent
and KeyReleaseEvent
functions.
To do that I am creating a class with my custom Text Edit widget:
class CustomTextEdit(QtWidgets.QTextEdit):
def keyPressEvent(self, event, text):
if len(text) > 140:
return
else:
self.setText(text)
I don't need an event here. I only need to pass an argument that will hold the text that is already written in the text editor. However, when I try to create a QEditText
and pass the current text by saying in my main UI:
self.text_edit = QtWidgets.CustomTextEdit()
self.text_edit.keyPressEvent(self.text_edit.toPlainText())
the program understands it as if I am passing an event which is a QKeyEvent
and of course says that it doesn't have length.
What am I doing wrong? How to pass an event and an argument? Is it even possible?
I have been reading tones of answers to a similar question but still, don't get the answer. Please, help!
Solution
keyPressEvent
can take only two arguments: self
and event
(named as you wish). To access the text already written in the editor you can use self.toPlainText()
before accepting event with event.accept()
. So, for your case to limit characters amount to 140 I would propose this workaround:
class CustomTextEdit(QWidgets.QTextEdit):
def keyPressEvent(self, event):
current_text = self.toPlainText()
super().keyPressEvent(event) # event.accept() is not working for me for some reasons
if len(self.toPlainText()) > 140:
self.setText(current_text)
Answered By - sanyassh
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.