Set default alignment for cells in QTableWidget

前端 未结 2 1408
无人及你
无人及你 2020-12-09 09:44

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

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

However I would like t

2条回答
  •  隐瞒了意图╮
    2020-12-09 10:07

    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.

提交回复
热议问题