#define MAXNUM_LETTER_W 9
在编辑框输入时做文本长度控制:
void MainWindowTable::on_textChange(QStandardItem* item)
{ if (isInputing) { return; } m_hasModify = true; if (item->text().length()>MAXQSTRINGLENGTH_NORMAL) { item->setText(item->text().left(MAXQSTRINGLENGTH_NORMAL)); } else if(item->text().length() >= MAXNUM_LETTER_W) { int nCountChineseStr = 0; for (int i = 0 ;i<item->text().length();i++) { if (item->text().at(i)>(char)127) { nCountChineseStr++; } } if (item->text().count(QString("W"))/*+ item->text().count(QString("M"))*/ + nCountChineseStr> MAXNUM_LETTER_W) { item->setText(item->text().left(MAXNUM_LETTER_W)); } } .......}
绘制表格时提取固定长度:
for (int row = 0; row < rows+1; row++)//将view表的内容画到表格中去
{ for(int column = 0; column < colnum_num; column++) { QModelIndex idx = printTable->model()->index(row,column); option.rect = printTable->visualRect(idx); if (printTable->item(row,column)) { QRectF rt(option.rect.left(),option.rect.top(),option.rect.width(),option.rect.height()); rt = rt.translated(offPt); if (row != 0 && column == 0)//行头 { painter.drawText(rt,Qt::AlignCenter,printTable->item(row,column)->text()); } else if (row == 0 &&printTable->item(row,column)->text() != "" )//列头 { painter.drawText(rt,Qt::AlignCenter,printTable->item(row,column)->text()); } else if(printTable->item(row,column)->text() != "") { QString str = printTable->item(row,column)->text(); /*if(row == 10 || row == 11 || row == 12) str = str.left(14); else str = str.left(8);*/ str = str.left(MAXQSTRINGLENGTH_NORMAL); //每页显示5组数据,腾出的宽度分配给每列,这样子绘制图像时的QRect能存放14位长的字符串,才不会想之前那样报错。原始数据长度不变,不存在数据截断情况。 painter.drawText(rt,Qt::AlignCenter,str); } } }这样子就没有了之间的报错问题