M
M
Mercury132016-01-25 15:13:59
Qt
Mercury13, 2016-01-25 15:13:59

Qt: autoresize column by sample?

Good old QTableView.
Let's assume that there are a lot of rows in the table and therefore the usual autoresize is not suitable (slows down). I would like to make an autoresize, so to speak, according to the model. More precisely, the larger of the two: the width of the title and the width of some sample.
For example, for numeric columns, I would sample 0000,0000. For dates, 00 Www 0000. For strings, 20 middle letters (20/26 of the width of the English alphabet). Etc.
PS A lot = tens of thousands.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Mercury13, 2016-02-02
@Mercury13

Found a way.

namespace {

    // Пока делегат стандартный, использую шаблон «Паблик Морозов».
    // Если нет — он сам и будет Морозовым.
    class QStyledItemDelegateMorozov : public QStyledItemDelegate {
    public:
        using QStyledItemDelegate::initStyleOption;
    };

}


void SomeReport::autoResize()
{
    QHeaderView* header = table->horizontalHeader();
    QStyledItemDelegateMorozov* delegate =
            reinterpret_cast<QStyledItemDelegateMorozov*>(
            dynamic_cast<QStyledItemDelegate*>(table->itemDelegate()));
    QStyle* style = table->style();
    QStyleOptionViewItem option;
    for (int col = 0; col < model.columnCount(); ++col) {
        QModelIndex index = model.index(0, col);
        delegate->initStyleOption(&option, index);
        option.text = "12345678901234";
        int headerSize = header->sectionSizeHint(col);
        int cellSize = style->sizeFromContents(
                QStyle::CT_ItemViewItem, &option, QSize(), table).width();
        table->setColumnWidth(col, std::max(headerSize, cellSize));
    }
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question