Center the Text of QTextEdit horizontally and vertically
Asked Answered
O

2

6

I want to center the text of my QTextEdit horizontally and vertically.

I tried this, but it didn't work.

m_myTextEdit = new QTextEdit("text edit", m_ui->centralWidget);
m_myTextEdit->setGeometry(5, 50, 400, 250);
m_myTextEdit->setReadOnly(true);
m_myTextEdit->setAlignment(Qt::AlignCenter);

Is there a opportunity to set it centered with a StyleSheet?

Oconnor answered 26/7, 2013 at 21:13 Comment(2)
Do you need multiple lines of text?Neaten
Hmm kind of, but not really. Normally, there are 1-3 Words in the TextEdit, which gets updated every time.Oconnor
N
8

If you only need one line, you can use a QLineEdit instead:

QLineEdit* lineEdit = new QLineEdit("centered text");
lineEdit->setAlignment(Qt::AlignCenter);

If you only want to display the text, not allow the user to edit it, you can use a QLabel instead. This works with line wrapping, too:

QLabel* label = new QLabel("centered text");
lineEdit->setWordWrap(true);
lineEdit->setAlignment(Qt::AlignCenter);
Neaten answered 26/7, 2013 at 21:51 Comment(0)
L
0

Here is code from PySide that I use for this, for those that need to use QTextEdit rather than QLineEdit. It is based on my answer here:

Here is the code, but the explanation is at the link:

import sys
from PySide import QtGui, QtCore

class TextLineEdit(QtGui.QTextEdit):
    topMarginCorrection = -4 #not sure why needed
    returnPressed = QtCore.Signal()
    def __init__(self, fontSize = 10, verticalMargin = 2, parent = None):
        QtGui.QTextEdit.__init__(self, parent)
        self.setAttribute(QtCore.Qt.WA_DeleteOnClose)
        self.setLineWrapMode(QtGui.QTextEdit.NoWrap)
        self.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
        self.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
        self.setFontPointSize(fontSize)
        self.setViewportMargins(0, self.topMarginCorrection , 0, 0)  #left, top, right, bottom
        #Set up document with appropriate margins and font
        document = QtGui.QTextDocument()
        currentFont = self.currentFont()
        currentFont.setPointSize(fontSize)
        document.setDefaultFont(currentFont)
        document.setDocumentMargin(verticalMargin)
        self.setFixedHeight(document.size().height())
        self.setDocument(document)

    def keyPressEvent(self, event):
        '''stops retun from returning newline'''
        if event.key() in (QtCore.Qt.Key_Enter, QtCore.Qt.Key_Return):
            self.returnPressed.emit()
            event.accept()
        else:
            QtGui.QTextEdit.keyPressEvent(self, event)

def main():
    app = QtGui.QApplication(sys.argv)
    myLine = TextLineEdit(fontSize = 15, verticalMargin = 8)
    myLine.show()
    sys.exit(app.exec_())

if __name__ == "__main__":
    main()
Lodger answered 2/1, 2016 at 19:31 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.