Reputation: 227
I've got a QPlainTextEdit object which I'm using as a mini-python editor in one of my tools. The problem is that when you insert a tab in QPlainTextEdit, it inserts a great big tab rather than four spaces like I'd prefer.
Is there a way to override this functionality, like you can in programs like Notepad++?
Upvotes: 2
Views: 1487
Reputation: 21
I know the question is about three years old but. I just had a similar problem. If you want to replace the tabs with spaces you could overwrite the keyPressEvent function and create a new event which contains spaces instead of the tab.
def keyPressEvent (self, oEvent):
if oEvent.key () == Qt.Key_Tab:
oEvent = QKeyEvent (QEvent.KeyPress
, Qt.Key_Space
, Qt.KeyboardModifiers(oEvent.nativeModifiers())
, " ")
super().keyPressEvent (oEvent)
Upvotes: 2
Reputation: 2540
Use the setTabStopWidth(width)
method to change how much space one tab takes. It takes width in pixels. The default is 80.
If you need to replace all the tabs with four spaces, you can get the string from qtextedit and then replace them
s= text_edit.toPlainText()
s= s.replace('\t', ' ')
Changing tab width in QTextEdit
:
from PyQt5.QtWidgets import *
import sys
class Wind(QWidget):
def __init__(self):
super().__init__()
self.setupUI()
def setupUI(self):
self.setGeometry(300,300, 300,500)
self.show()
vb_layout= QVBoxLayout(self)
text_edit= QTextEdit(self)
# This method sets tab width in pixels
text_edit.setTabStopWidth(8)
vb_layout.addWidget(text_edit)
self.setLayout(vb_layout)
def main():
app= QApplication(sys.argv)
w = Wind()
exit(app.exec_())
if __name__ == '__main__':
main()
Upvotes: 2