c++qtablewidget不显示行号
时间: 2024-06-13 21:07:29 浏览: 127
您可以通过以下两种方法在C++的QTableWidget中显示行号:
1.使用QTableWidget的setVerticalHeaderLabels()方法设置垂直表头标签,标签内容为行号。示例代码如下:
```c++
// 设置行数和列数
int rowCount = 5;
int columnCount = 3;
ui->tableWidget->setRowCount(rowCount);
ui->tableWidget->setColumnCount(columnCount);
// 设置垂直表头标签
QStringList headerLabels;
for(int i=1; i<=rowCount; i++){
headerLabels << QString::number(i);
}
ui->tableWidget->setVerticalHeaderLabels(headerLabels);
```
2.自定义QTableWidget的QHeaderView,将其设置为显示行号。示例代码如下:
```c++
// 自定义QHeaderView
class LineNumberHeaderView : public QHeaderView
{
public:
LineNumberHeaderView(Qt::Orientation orientation, QWidget *parent = nullptr)
: QHeaderView(orientation, parent)
{
setDefaultAlignment(Qt::AlignRight | Qt::AlignVCenter);
}
protected:
void paintSection(QPainter *painter, const QRect &rect, int logicalIndex) const override
{
painter->save();
QStyleOptionHeader opt;
initStyleOption(&opt);
opt.rect = rect;
opt.section = logicalIndex;
style()->drawControl(QStyle::CE_Header, &opt, painter, this);
painter->setPen(QColor(0, 0, 0));
painter->drawText(rect.adjusted(0, 0, -3, 0), Qt::AlignRight | Qt::AlignVCenter,
QString::number(logicalIndex + 1));
painter->restore();
}
};
// 设置行数和列数
int rowCount = 5;
int columnCount = 3;
ui->tableWidget->setRowCount(rowCount);
ui->tableWidget->setColumnCount(columnCount);
// 设置自定义QHeaderView
ui->tableWidget->setVerticalHeader(new LineNumberHeaderView(Qt::Vertical, ui->tableWidget));
```
阅读全文