Center the Text of QTextEdit horizontally and vertically

前端 未结 2 421
孤城傲影
孤城傲影 2020-12-11 08:13

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\",         


        
相关标签:
2条回答
  • 2020-12-11 08:35

    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);
    
    0 讨论(0)
  • 2020-12-11 08:56

    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: https://stackoverflow.com/a/34569735/1886357

    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()
    
    0 讨论(0)
提交回复
热议问题