【问题标题】:Center the Text of QTextEdit horizontally and vertically将 QTextEdit 的文本水平和垂直居中
【发布时间】:2013-07-27 07:12:46
【问题描述】:

我想将我的 QTextEdit 的文本水平和垂直居中。

我试过了,但是没用。

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);

是否有机会使用样式表将其设置为居中?

【问题讨论】:

  • 你需要多行文字吗?
  • 嗯,有点,但不是真的。通常,TextEdit中有1-3个单词,每次都会更新。

标签: c++ qt qtextedit qtstylesheets


【解决方案1】:

如果你只需要一行,你可以使用QLineEdit 代替:

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

如果您只想显示文本,不允许用户编辑它,您可以使用QLabel 代替。这也适用于换行:

QLabel* label = new QLabel("centered text");
lineEdit->setWordWrap(true);
lineEdit->setAlignment(Qt::AlignCenter);

【讨论】:

    【解决方案2】:

    这里是我使用的来自 PySide 的代码,适用于那些需要使用 QTextEdit 而不是 QLineEdit 的人。它基于我在这里的回答: https://stackoverflow.com/a/34569735/1886357

    这里是代码,但解释在链接:

    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()
    

    【讨论】: