65 lines
1.6 KiB
C++
65 lines
1.6 KiB
C++
#include "CTableView.h"
|
|
#include <QHeaderView>
|
|
|
|
CTableView::CTableView(QWidget *parent)
|
|
: QTableView(parent)
|
|
{
|
|
|
|
}
|
|
|
|
int CTableView::tableColumnWidth()
|
|
{
|
|
return m_nTableColWidth;
|
|
}
|
|
|
|
void CTableView::setTableColumnWidth(const int &nWidth)
|
|
{
|
|
m_nTableColWidth = nWidth;
|
|
|
|
horizontalHeader()->setDefaultSectionSize(m_nTableColWidth);
|
|
}
|
|
|
|
int CTableView::tableRowHeight()
|
|
{
|
|
return m_nTableRowHeight;
|
|
}
|
|
|
|
void CTableView::setTableRowHeight(const int &nHeight)
|
|
{
|
|
m_nTableRowHeight = nHeight;
|
|
|
|
verticalHeader()->setDefaultSectionSize(m_nTableRowHeight);
|
|
}
|
|
|
|
void CTableView::showEvent(QShowEvent *event){
|
|
QTableView::showEvent(event);
|
|
adjustHeaderWidth();
|
|
}
|
|
|
|
|
|
// 自动调整表头宽度以适应文本
|
|
void CTableView::adjustHeaderWidth() {
|
|
QHeaderView *header = horizontalHeader();
|
|
int sections = header->count();
|
|
int maxWidth = 0;
|
|
QFontMetrics fm(header->font());
|
|
int maxWidthThreshold = 200; // 设置换行的阈值
|
|
|
|
for (int i = 0; i < sections; ++i) {
|
|
QString text = model()->headerData(i, Qt::Horizontal, Qt::DisplayRole).toString();
|
|
int width = fm.width(text) + 10; // 加上一些额外空间
|
|
maxWidth = qMax(maxWidth, width);
|
|
}
|
|
|
|
for (int i = 0; i < sections; ++i) {
|
|
QString text = model()->headerData(i, Qt::Horizontal, Qt::DisplayRole).toString();
|
|
int width = fm.width(text) + 10; // 加上一些额外空间
|
|
// 如果宽度超过阈值,则换行
|
|
if (width > maxWidthThreshold) {
|
|
header->resizeSection(i, maxWidthThreshold);
|
|
} else {
|
|
header->resizeSection(i, maxWidth);
|
|
}
|
|
}
|
|
}
|