我正在使用qt框架开发应用程序,现在我想将表格数据保存为pdf。我正在使用QTextTable和QTextDocument类。但是我无法将文本居中在单元格中。我该怎么办?
感谢您的帮助。
答案 0 :(得分:5)
如果要在插入文本时进行对齐,可以使用alignment = Qt:AlignHCenter调用此函数。您可以修改该功能以指定字符格式。
// Insert text with specified alignment in specified cell
void insertAlignedText(QTextTable *table, int row, int col, Qt::Alignment alignment, QString text)
{
// Obtain cursor and current block format
QTextCursor textCursor = table->cellAt(row,col).firstCursorPosition();
QTextBlockFormat blockFormat = textCursor.blockFormat();
// Read vertical part of current alignment flags
Qt::Alignment vertAlign = blockFormat.alignment() & Qt::AlignVertical_Mask;
// Mask out vertical part of specified alignment flags
Qt::Alignment horzAlign = alignment & Qt::AlignHorizontal_Mask;
// Combine current vertical and specified horizontal alignment
Qt::Alignment combAlign = horzAlign | vertAlign;
// Apply and write
blockFormat.setAlignment(combAlign);
textCursor.setBlockFormat(blockFormat);
textCursor.insertText(text);
}
答案 1 :(得分:1)
QTextBlockFormat centerAlignment;
centerAlignment.setAlignment(Qt::AlignHCenter);
cursor = table->cellAt(row, column).firstCursorPosition();
cursor.setBlockFormat(centerAlignment);
cursor.insertText("Hello, this is my first post here!");
但请注意,设置一次的对齐有效,直到下一次更改。这意味着,例如,如果您有一个表中的两列,一个具有左对齐,一个具有右对齐,并且您要逐行添加到表中,则必须为每个单元调用QTextCursor::setBlockFormat()来交替左右对齐。
答案 2 :(得分:0)
如果要在写入文本后修改对齐,可以使用以下函数with alignment = Qt:AlignHCenter。
// Modify horizontal alignment of text in specified cell
void modifyTextAlignment(QTextTable *table, int row, int col, Qt::Alignment alignment)
{
// Obtain cursor and current block format
QTextCursor textCursor = table->cellAt(row,col).firstCursorPosition();
textCursor.select(QTextCursor::BlockUnderCursor);
QTextBlockFormat blockFormat = textCursor.blockFormat();
// Read vertical part of current alignment flags
Qt::Alignment vertAlign = blockFormat.alignment() & Qt::AlignVertical_Mask;
// Mask out vertical part of specified alignment flags
Qt::Alignment horzAlign = alignment & Qt::AlignHorizontal_Mask;
// Combine current vertical and specified horizontal alignment
Qt::Alignment combAlign = horzAlign | vertAlign;
// Apply
blockFormat.setAlignment(combAlign);
textCursor.setBlockFormat(blockFormat);
}
答案 3 :(得分:0)
此问题的PyQt5等效解决方案(如何在QTextTable中居中放置文本)。这也适用于合并的单元格。
centerAlignment = PyQt5.QtGui.QTextBlockFormat()
centerAlignment.setAlignment(PyQt5.QtCore.Qt.AlignHCenter)
cursor = table.cellAt(row, column).firstCursorPosition()
cursor.setBlockFormat(centerAlignment)
cursor.insertText("Hello, this is the PyQt5 code equivalent to this question!")
答案 4 :(得分:-1)