Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

Text alignment on QTableWidgetItem



  • Hello to all,
    I have a QTAbleWidget on which I have inserted a QTableWidgetItem as follows:

    ui-> tableData-> setItem (line ++, 1, new QTableWidgetItem (lang.at (ConfigData.at (32))));
    

    tableData is the QTableWidget.
    I would like the data (lang.at (ConfigData ...) to be centered in the cell.
    I did search on google, but I found only solutions that unfortunately at the moment I cannot understand.
    Some advice?
    Thanks.

    Stephen


  • Lifetime Qt Champion

    Hi
    You can set it on the item
    alt text

    item->setTextAlignment(Qt::AlignCenter);

    so in your case

    auto item = new QTableWidgetItem (lang.at (ConfigData.at (32)));
    item->setTextAlignment(Qt::AlignCenter);
    ui-> tableData-> setItem (line ++, 1,  item);
    


  • Hi mrjj and thanks for your help.
    I've tested your solution and works fine, but, I've code as this:

    ui->tableData->setItem(riga, 0, new QTableWidgetItem("MAP1"));
            ui->tableData->setItem(riga++, 1, new QTableWidgetItem(QString::number(ConfigData.at(3))));
    
            ui->tableData->setItem(riga, 0, new QTableWidgetItem("MAP2"));
            ui->tableData->setItem(riga++, 1, new QTableWidgetItem(QString::number(ConfigData.at(4))));
    
            ui->tableData->setItem(riga, 0, new QTableWidgetItem("SUB1"));
            ui->tableData->setItem(riga++, 1, new QTableWidgetItem(QString::number(ConfigData.at(5))));
    

    the columns and rows number is dinamic.
    I wondered if it was possible to set textalignment directly in this definition:

    ui->tableData->setItem(riga, 0, new QTableWidgetItem("SUB1"));
            ui->tableData->setItem(riga++, 1,  ---->new QTableWidgetItem(QString::number(ConfigData.at(5))));
    

    without create a QTableWidgetItem object for each row how you've suggested me:

    auto item1 = new QTableWidgetItem(QString::number((ConfigData.at(1) << 8)+ConfigData.at(2)));
            item1->setTextAlignment(Qt::AlignCenter);
            ui->tableData->setItem(riga, 0, new QTableWidgetItem("MAP2"));
            ui->tableData->setItem(riga++, 1, item1);
    

    Thanks again for your help.


  • Lifetime Qt Champion

    @Stefanoxjx
    Hi
    You could just use a small helper function to keep it as one liners.
    like:

    (above the other function)
    QTableWidgetItem * MakeItem(QString value) {
    auto item = new QTableWidgetItem(value);
    item->setTextAlignment(Qt::AlignCenter);
    return item;
    }
    ...
    
    
     ui->tableData->setItem(riga++, 1,  MakeItem(QString::number(ConfigData.at(5))));
    


  • Hi mrjj, your solution works very fine.
    Many thanks :)

    Stefano


Log in to reply