#include <QApplication>
#include <QTableWidget>
#include <QString>
#include <QHeaderView>
#include <QFontMetrics>
// 判断字符是否是英文字符
bool char_is_eng(const char ch)
{
if(ch >= 0 && ch <= 127)
return true;
else
return false;
}
// 计算给定字符串在限制字符数或宽度前的字节长度
int get_text_len(const char* strUtf8, int maxWidth, const QFontMetrics& fm)
{
int wmLen = 0; // 当前宽度
int nstrLen = strlen(strUtf8); // 输入字符串的字节长度
int i = 0; // 字节位置
while (i < nstrLen)
{
int charWidth;
if (char_is_eng(strUtf8[i]))
{
charWidth = fm.horizontalAdvance(QChar(strUtf8[i]));
wmLen += charWidth;
i++;
}
else
{
charWidth = fm.horizontalAdvance(QString::fromUtf8(strUtf8 + i, 3));
wmLen += charWidth;
i += 3;
}
if (wmLen > maxWidth)
{
return i;
}
}
return nstrLen;
}
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QTableWidget tableWidget(5, 3);
// 设置表头
tableWidget.setHorizontalHeaderLabels(QStringList() << "Column 1" << "Column 2" << "Column 3");
tableWidget.horizontalHeader()->setStretchLastSection(true);
const char* message = "Hello, 世界! How are you?";
// 设置表格内容
for(int row = 0; row < tableWidget.rowCount(); ++row)
{
for(int col = 0; col < tableWidget.columnCount(); ++col)
{
QTableWidgetItem *item = new QTableWidgetItem();
QFontMetrics fm = tableWidget.fontMetrics();
int maxWidth = tableWidget.columnWidth(col) - 10; // 减去一些内边距
int displayLen = get_text_len(message, maxWidth, fm);
item->setText(QString::fromUtf8(message, displayLen));
tableWidget.setItem(row, col, item);
}
}
tableWidget.show();
return a.exec();
}
实现根据QTableWidgetItem项的宽度动态调整显示字符
最新推荐文章于 2024-07-25 21:48:01 发布