int main(int argc, char *argv[]) { QApplication app(argc, argv); QStandardItemModel model(4, 4); QTableView tableView; tableView.setSizeAdjustPolicy(QTableView::AdjustToContents); tableView.setModel(&model); for (int row = 0; row < model.rowCount(); ++row) { for (int column = 0; column < model.columnCount(); ++column) { QModelIndex index = model.index(row, column, QModelIndex()); model.setData(index, QVariant(QString("%1,%2").arg(row).arg(column))); } } tableView.setSpan(1, 1, 2, 2); tableView.show(); return app.exec(); }
/* we create a table that has a fixed height, but can stretch to fit certain width */ QTableView *PrintLayout::createProfileTable(ProfilePrintModel *model, const int tableW) { // setup a new table QTableView *table = new QTableView(); QHeaderView *vHeader = table->verticalHeader(); QHeaderView *hHeader = table->horizontalHeader(); table->setAttribute(Qt::WA_DontShowOnScreen); table->setSelectionMode(QAbstractItemView::NoSelection); table->setFocusPolicy(Qt::NoFocus); table->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); table->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff); hHeader->setVisible(false); vHeader->setVisible(false); #if QT_VERSION < QT_VERSION_CHECK(5, 0, 0) hHeader->setResizeMode(QHeaderView::Fixed); vHeader->setResizeMode(QHeaderView::Fixed); #else hHeader->setSectionResizeMode(QHeaderView::Fixed); vHeader->setSectionResizeMode(QHeaderView::Fixed); #endif // set the model table->setModel(model); /* setup cell span for the table using QTableView::setSpan(). * changes made here reflect on ProfilePrintModel::data(). */ const int cols = model->columnCount(); const int rows = model->rowCount(); // info on top table->setSpan(0, 0, 1, 4); table->setSpan(1, 0, 1, 4); // gas used table->setSpan(2, 0, 1, 2); table->setSpan(3, 0, 1, 2); // notes table->setSpan(6, 0, 1, 5); table->setSpan(7, 0, 5, 5); /* resize row heights to the 'profilePrintRowHeights' indexes. * profilePrintTableMaxH will then hold the table height. */ int i; profilePrintTableMaxH = 0; for (i = 0; i < rows; i++) { int h = profilePrintRowHeights.at(i); profilePrintTableMaxH += h; vHeader->resizeSection(i, h); } // resize columns. columns widths are percentages from the table width. int accW = 0; for (i = 0; i < cols; i++) { int pw = qCeil((qreal)(profilePrintColumnWidths.at(i) * tableW) / 100.0); accW += pw; if (i == cols - 1 && accW > tableW) /* adjust last column */ pw -= accW - tableW; hHeader->resizeSection(i, pw); } // resize table->resize(tableW, profilePrintTableMaxH); // hide the grid and set a stylesheet table->setItemDelegate(new ProfilePrintDelegate(this)); table->setShowGrid(false); table->setStyleSheet( "QTableView { border: none }" "QTableView::item { border: 0px; padding-left: 2px; padding-right: 2px; }"); // return return table; }