Sections

How do I create a default size for the rows in a table view?


Answer:


In order to change the default size for the rows in a table view, you need to reimplement sizeHintForRow() and make sure resizeRowToContents() is called. See the documentation:


http://doc.trolltech.com/4.3/qtableview.html#sizeHintForRow

The example below demonstrates how this can be achieved

#include <QtGui>

class Model : public QAbstractTableModel
{
public:
Model(QObject *parent)
{
QStringList firstRow;
QStringList secondRow;

for (int i = 0; i < 5; i++ ) {
firstRow.insert(i,"Row 1 " + QString::number(i+1));
secondRow.insert(i,"Row 2 " + QString::number(i+1));
}

stringList << firstRow << secondRow;
}

// Returns the number of rows
int rowCount ( const QModelIndex & parent = QModelIndex() ) const
{
return stringList.count();
}

// Returns the number of columns
int columnCount ( const QModelIndex & parent = QModelIndex() ) const
{
return stringList[0].count();

}


// Returns an appropriate value for the requested data.
// If the view requests an invalid index or if the role is not
// Qt::DisplayRole, an invalid variant is returned.
// Any valid index that corresponds to a string for the index's column and row in
// the stringlist is returned
QVariant data ( const QModelIndex & index, int role = Qt::DisplayRole ) const
{
if (!index.isValid())
return QVariant();
if (role != Qt::DisplayRole)
return QVariant();
QStringList list = (QStringList)stringList.at(index.row());
return list.at(index.column());
}
private:
QList<QStringList>stringList;

};

class TableView : public QTableView
{
public:
TableView(QWidget *parent) {}

//Returns the needed size for the rows
int sizeHintForRow ( int row ) const
{
return 200;
}
};


int main(int argc, char **argv)
{
QApplication app(argc, argv);
QWidget widget;

QHBoxLayout *layout = new QHBoxLayout(&widget);

TableView *tableView = new TableView(&widget);
Model *model = new Model(tableView);
tableView->setModel(model);

for (int i = 0; i < model->rowCount(); i++) {
tableView->resizeRowToContents(i);
}

layout->addWidget(tableView);

widget.show();
return app.exec();
}

back

Patron of KDECustomers

Customers