可以在样式表中设置QTableWidget的单元格对齐方式来实现内容居中显示。具体步骤如下:
- 设置QTableWidget的单元格对齐方式为居中。
tableWidget->horizontalHeader()->setDefaultAlignment(Qt::AlignHCenter | Qt::AlignVCenter);
- 在样式表中设置QTableWidget的单元格对齐方式。
QTableWidget::item {
text-align: center;
}
完整代码示例:
#include <QApplication>
#include <QWidget>
#include <QTableWidget>
#include <QHBoxLayout>
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
QWidget *window = new QWidget();
QTableWidget *tableWidget = new QTableWidget();
tableWidget->setRowCount(3);
tableWidget->setColumnCount(3);
QStringList header;
header << "ID" << "Name" << "Age";
tableWidget->setHorizontalHeaderLabels(header);
QStringList data;
data << "001" << "Tom" << "20"
<< "002" << "Jerry" << "18"
<< "003" << "Mickey" << "22";
for (int row = 0; row < tableWidget->rowCount(); ++row) {
for (int col = 0; col < tableWidget->columnCount(); ++col) {
QTableWidgetItem *item = new QTableWidgetItem(data.at(row*tableWidget->columnCount() + col));
tableWidget->setItem(row, col, item);
}
}
// 设置单元格内容居中显示
// tableWidget->horizontalHeader()->setDefaultAlignment(Qt::AlignHCenter | Qt::AlignVCenter);
// 在样式表中设置单元格内容居中显示
tableWidget->setStyleSheet("QTableWidget::item {text-align: center;}");
QHBoxLayout *layout = new QHBoxLayout();
layout->addWidget(tableWidget);
window->setLayout(layout);
window->show();
return app.exec();
}
运行结果如下图所示: