5

我想将 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);

有没有机会以样式表为中心设置它?

4

2 回答 2

8

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

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

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

QLabel* label = new QLabel("centered text");
lineEdit->setWordWrap(true);
lineEdit->setAlignment(Qt::AlignCenter);
于 2013-07-26T21:51:28.120 回答
0

这是我用于此的 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()
于 2016-01-02T19:31:13.770 回答