我希望水平和垂直居中调整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);
是否有机会将其设置为以StyleSheet为中心?
答案 0 :(得分:5)
如果您只需要一行,则可以改为使用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);
答案 1 :(得分: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()