• 8818阅读
  • 1回复

QTableWidget如何自适应宽度? [复制链接]

上一主题 下一主题
离线wukexin
 
只看楼主 倒序阅读 楼主  发表于: 2008-05-30
— 本帖被 XChinux 执行加亮操作(2008-05-31) —
请问:QTableWidget如何自适应宽度?
离线steinlee

只看该作者 1楼 发表于: 2008-05-31
Write your own table to inherit QTableWidget and add this function in it.

void YourTable::fitColumns( void )
{
    QFont font = QApplication::font( 0 );
    for ( int col = 0; col < numCols(); col++)
    {
        // See if the column contains a QComboTableItem
        QTableItem * theItem = item ( 0,col);
        if ( theItem && (theItem->rtti() == 1 || theItem->rtti() == 1452))
        {
            // rtti ==1: QComboTableItem; 1452 == PComboTableItem
            int maxWidth = 0;
            QComboTableItem * it = (QComboTableItem *) theItem;

            for ( int i = 0; i < it->count(); i++ )
            {
                QString text = it->text ( i );
                QFontMetrics fm ( font );
                int width = fm.width ( text ) + 45;
                if ( width > maxWidth) maxWidth = width;
            }
            if ( maxWidth > columnWidth ( col ))
                setColumnWidth ( col, maxWidth );
        }
        else
        {
            adjustColumn( col );
        }

        // See if the header fits
        QString headerString =  horizontalHeader()->label ( col );
        QFontMetrics fm ( font );
        int i = headerString.find( QRegExp("\\n"), 0 );
        int width;
        if ( i > 0 )
        {
            headerString.truncate( i);
        }
        width = fm.width ( headerString ) + 10;
        if ( width > columnWidth ( col ))
        {
            setColumnWidth ( col, width );
        }
    }
}
Looking for remote C/C++ and Qt 兼职
快速回复
限100 字节
 
上一个 下一个