I also needed to layout table views without displaying their scrollbars. sizeHint() and minimumSizeHint() did the work for me. Below is the code of a sub-class of the QTableView:
MyTableView
::MyTableView(QWidget* parent
){
}
QSize MyTableView
::sizeHint() const {
return minimumSizeHint();
}
QSize MyTableView
::minimumSizeHint() const {
int colCount = m->columnCount();
int w = 0;
for(int i=0; i<colCount; ++i) {
w += columnWidth(i);
}
int rowCount = m->rowCount();
int h = 0;
for(int i=0; i<rowCount; ++i) {
h += rowHeight(i);
}
int doubleFrame = 2 * frameWidth();
w += verticalHeader()->width() + doubleFrame;
h += horizontalHeader()->height() + doubleFrame;
}
MyTableView::MyTableView(QWidget* parent)
: QTableView(parent)
{
}
QSize MyTableView::sizeHint() const
{
return minimumSizeHint();
}
QSize MyTableView::minimumSizeHint() const
{
QAbstractItemModel* m = model();
int colCount = m->columnCount();
int w = 0;
for(int i=0; i<colCount; ++i) {
w += columnWidth(i);
}
int rowCount = m->rowCount();
int h = 0;
for(int i=0; i<rowCount; ++i) {
h += rowHeight(i);
}
int doubleFrame = 2 * frameWidth();
w += verticalHeader()->width() + doubleFrame;
h += horizontalHeader()->height() + doubleFrame;
return QSize(w, h);
}
To copy to clipboard, switch view to plain text mode
Here is alternative code for minimumSizeHint() which also does the work:
QSize MyTableView
::minimumSizeHint() const {
int doubleFrame = 2 * frameWidth();
int w = hHeader->length() + vHeader->width() + doubleFrame;
int h = vHeader->length() + hHeader->height() + doubleFrame;
}
QSize MyTableView::minimumSizeHint() const
{
QHeaderView* vHeader = verticalHeader();
QHeaderView* hHeader = horizontalHeader();
int doubleFrame = 2 * frameWidth();
int w = hHeader->length() + vHeader->width() + doubleFrame;
int h = vHeader->length() + hHeader->height() + doubleFrame;
return QSize(w, h);
}
To copy to clipboard, switch view to plain text mode
I like this second implementation better because it is shorter but I'm not sure if it'll work in all cases. I'm actually not sure if the first implementation will also work in all cases, so if someone with more Qt experience could give an advice I would really appreciate it.
Thank you in advance,
Yuri
Bookmarks