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

Posted

技术标签:

【中文标题】将 QTextEdit 的文本水平和垂直居中【英文标题】:Center the Text of QTextEdit horizontally and vertically 【发布时间】: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个单词,每次都会更新。 【参考方案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://***.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()

【讨论】:

以上是关于将 QTextEdit 的文本水平和垂直居中的主要内容,如果未能解决你的问题,请参考以下文章

文本DIV水平居中和垂直居中

如何在堆栈中垂直或水平居中小部件?

绝对定位情况下水平垂直居中小技巧

css html 如何将图片img标签 水平居中 垂直居中 和水平垂直居中

没有固定大小的容器中的垂直和水平居中文本在 Firefox 中表现得很奇怪

如何在媒体查询设置的流体布局中垂直和水平居中子元素?