c++ - QT FontMetrics::BoundingRect 大小错误

标签 c++ qt qtableview

我正在使用 Qt 5.2,我目前正在尝试从 QTableView 打印一个表格,但是我在根据内容计算行高时遇到了这个问题。我现在得到的是下面的循环,它循环遍历 QTableView 行并使用 boundingRect 函数获取每一行的高度。

for(int r=0; r<rows; ++r) {
    //tempTable.resizeRowToContents(r);
    QString str = tempTable.model()->data(tempTable.model()->index(r,0)).toString();
    QFontMetrics fm(tempTable.font());
    QRect rect = fm.boundingRect(0,0,tempTable.columnWidth(0),0,(Qt::TextWordWrap),str);
    tempTable.setRowHeight(r,rect.size().height());
    totalHeight += tempTable.rowHeight(r);
}

不幸的是,这个函数返回了一些奇怪的结果,为字符串做了很大的填充: enter image description here

有什么办法可以解决这个问题吗?

最佳答案

所以,最后,我找到了导致问题的代码部分。这个字符串,

tempTable.horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);

我为了将列拉伸(stretch)到页面宽度而放置的,以某种意想不到的方式影响了 boundingRect 的行为。在我删除它并使用 setColumnWidth 函数设置每个列的宽度后,一切看起来都很好。

关于c++ - QT FontMetrics::BoundingRect 大小错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23519070/

相关文章:

c++ - C++中 vector 的Malloc错误

c++ - 头文件中的 constexpr const char*

c++ - Qt音乐播放器: mini player mode

linux - 各种Qt平台插件有什么用?

QTableView - 未获得选择更改信号

c++ - Qt - QTableView - 表格行中的可点击按钮

c++ - 如何在 C++ 中使用 PI 常量

c++ - 为什么必须动态分配扩展数组才能使该函数正常工作 C++

c++ - 如何卸载高度依赖于正确异常处理的计算繁重的任务?

python - 内部 C++ 对象 (PySide2.QtGui.QContextMenuEvent) 已在 Qtableview 上删除