Reputation: 584
Suppose I type a paragraph with new lines such as,
Hey mr Nikhil
Howdy you
Funny$ life isn't it.
Now consider the dollar symbol as my cursor. If I can print my text by this code,
print(self.toPlainText())
Then how can I get the text before the cursor so that my output will be,
Hey mr Nikhil
Howdy you
Funny
Help please.
Upvotes: 1
Views: 324
Reputation: 243897
You have to use the cursor position:
import sys
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
class Widget(QWidget):
def __init__(self, parent=None):
QWidget.__init__(self, parent)
lay = QVBoxLayout(self)
self.te = QTextEdit()
self.te.setPlainText('''Hey mr Nikhil\nHowdy you\nFunny life isn't it.''')
lay.addWidget(self.te)
button = QPushButton("Click Me")
lay.addWidget(button)
button.clicked.connect(self.on_clicked)
def on_clicked(self):
p = self.te.textCursor().position()
result = self.te.toPlainText()[:p]
print("result:\n{}".format(result))
if __name__ == '__main__':
app = QApplication(sys.argv)
w = Widget()
w.show()
sys.exit(app.exec_())
Upvotes: 1