81 lines
1.9 KiB
C++
81 lines
1.9 KiB
C++
#include "CTableView.h"
|
|
#include <QHeaderView>
|
|
#include <QtMath>
|
|
|
|
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::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).toString();
|
|
int width = fm.width(text) + 10; // 加上一些额外空间
|
|
maxWidth = qMax(maxWidth, width);
|
|
}
|
|
|
|
int heightBase=30;
|
|
int heightCount=1;
|
|
for (int i = 0; i < sections; ++i) {
|
|
QString text = model()->headerData(i, Qt::Horizontal).toString();
|
|
int width = fm.width(text) + 20; // 加上一些额外空间
|
|
// 如果宽度超过阈值,则换行
|
|
if (width > maxWidthThreshold) {
|
|
header->resizeSection(i, maxWidthThreshold);
|
|
qreal tmpHeightCount=qreal(width)/qreal(maxWidthThreshold);
|
|
if(tmpHeightCount>heightCount){
|
|
heightCount=qCeil(tmpHeightCount);
|
|
}
|
|
} else {
|
|
if(i==0)
|
|
{
|
|
maxWidth=210;
|
|
}
|
|
header->resizeSection(i, maxWidth);
|
|
heightCount=2;
|
|
}
|
|
}
|
|
header->setFixedHeight(heightCount*heightBase);
|
|
}
|
|
|
|
|
|
|
|
void CTableView::showEvent(QShowEvent *event){
|
|
QTableView::showEvent(event);
|
|
adjustHeaderWidth();
|
|
}
|
|
|