要根据header的长度来设置QTableView的列宽,可以使用以下方法:

  1. 获取header的文本内容和长度。
QString headerText = tableView->horizontalHeader()->model()->headerData(section, Qt::Horizontal).toString();
int headerWidth = QFontMetrics(tableView->horizontalHeader()->font()).width(headerText);
  1. 设置列宽。
tableView->setColumnWidth(section, headerWidth);

完整的示例代码如下:

// 获取列数
int columnCount = tableView->horizontalHeader()->count();

// 遍历每一列
for (int section = 0; section < columnCount; ++section) {
    // 获取header的文本内容和长度
    QString headerText = tableView->horizontalHeader()->model()->headerData(section, Qt::Horizontal).toString();
    int headerWidth = QFontMetrics(tableView->horizontalHeader()->font()).width(headerText);
    
    // 设置列宽
    tableView->setColumnWidth(section, headerWidth);
}

请注意,上述代码假设tableView是一个有效的QTableView对象,并且已经设置了水平header的model。如果没有设置model,可以使用setModel()方法设置一个有效的model

Qt QTableView根据header的长度来设置列宽

原文地址: http://www.cveoy.top/t/topic/iXcJ 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录