Search code examples
c++qtqtablewidgettext-alignment

Set default alignment for cells in QTableWidget


I know you can set the alignment for each item using:

TableWidget->item(0,0)->setTextAlignment(Qt::AlignLeft);

However I would like to set a default alignment for all the cells in order to do not have to set it every time I create a new item. Is it possible?


Solution

  • Yes it is possible. But you need to understand you are not modifying a property of the table widget, but a property of the table widget item. First create your own item, and set it up as you want

     QTableWidgetItem * protoitem = new QTableWidgetItem();
     protoitem->setTextAlignment(Qt::AlignLeft);
     etc...
    

    Then each time you want to create a new item rather than using the constructor you use

     QTableWidgetItem * newitem = protoitem->clone();
     tableWidget->setItem(0,0, newitem);
    

    Another alternative to clone (untested) is to set a prototype on your tablewidget

    QTableWidget::setItemPrototype ( const QTableWidgetItem * item )
    

    This last one can be more appropriate if you are using a Ui or if the item is editable.