23

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?

Stefan van den Akker
  • 6,661
  • 7
  • 48
  • 63
jsalvador
  • 733
  • 2
  • 7
  • 18

3 Answers3

27

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.

UmNyobe
  • 22,539
  • 9
  • 61
  • 90
10

I don't think there is an existing method for this, but here's two approaches that work:


1.) Subclass QTableWidgetItem

MyTableWidgetItem::MyTableWidgetItem() :
    QTableWidgetItem()
{
    setTextAlignment( Qt::AlignLeft );
}

However, this is probably a bit overkill for just a single setting + you might want to overload all four constructors of QTableWidgetItem.


2.) Another approach is using a factory instead of calling new:
Note: The linked article talks about unit testing, but there are many more advantages by doing that.

QTableWidgetItem* MyTableWidgetFactory::createTableWidgetItem( const QString& text ) const
{
    QTableWidgetItem* item = new QTableWidgetItem( text );
    item->setTextAlignment( Qt::AlignLeft );
    return item;
}

Then instead of

QTableWidgetItem* myItem = new QTableWidgetItem( "foo" );
item->setTextAlignment( Qt::AlignLeft );

you can do

QTableWidgetItem* myItem = myFactory->createTableWidgetItem( "foo" );

where myFactory is an object of MyTableWidgetFactory.

Tim Meyer
  • 12,210
  • 8
  • 64
  • 97
0

If you're using delegates for cells, rows or columns, you'd be subclassing QStyledItemDelegate; it has a method initStyleOption which can be used to set style options for all cells using your delegate.

void MyItemDelegate::initStyleOption(QStyleOptionViewItem *option,
                                     const QModelIndex &index) const override {
  // call base class implementation to set things up as default
  QStyledItemDelegate::initStyleOption(option, index);

  // override just the style options you want later
  option->displayAlignment = Qt::AlignCenter;
}

It's more elegant and less cumbersome unlike when working with QTableWidgetItems.

legends2k
  • 31,634
  • 25
  • 118
  • 222