set the width of the columns of QTableView
Hi,
I am a new bee of QT.
I try to use QTableView and QAbstractTableModel. I created my own TableModel and called ui.tableView->setModel. Everything looks fine.
But I find that I cannot set the width of column from my TableModel.
I found the function, QTableView::setColumnWidth. But I don't know when I am able to call it. Because I only return the string from Model, I don't know when the framework will create the columns. But I need set width of the column after it is created.
Anybody knows what I must do? Thanks a lot.
Best Regards,
Michael zhang
Re: set the width of the columns of QTableView
How about using the SizeHint role in the model?
Re: set the width of the columns of QTableView
Hi Jacek,
First of all, thanks for you quick reply.
I added it Qt::SizeHintRole into the code. But looks like it only be able to change the height of header but not width.
following is my code, Do I do anything not correct? or any other suggestion?
Code:
QVariant TableModel
::headerData(int section, Qt
::Orientation orientation,
int role
) const {
if (orientation == Qt::Horizontal)
{
if (section < _columnInfos.size())
{
if (role == Qt::DisplayRole)
{
return QVariant(_columnInfos
[section
]->GetName
());
}
else if(role == Qt::SizeHintRole)
{
if (section == 0)
{
size.setWidth(200);
}
}
}
}
}
Regards,
Michael zhang
Re: set the width of the columns of QTableView
I generally do this by extending the table view and modifying the resizeEvent method;
Code:
# Python code ...
def __init__(self, model, parent = None):
super(MyTable, self).__init__(parent)
rowHeight = self.fontMetrics().height()
self.verticalHeader().setDefaultSectionSize(rowHeight)
self.setModel(model)
def resizeEvent(self, event):
width = event.size().width()
self.setColumnWidth(1, width * 0.25) # 25% Width Column
self.setColumnWidth(2, width * 0.75) # 75% Width Column
Re: set the width of the columns of QTableView
Hi,
Thanks for your reply.
I am not really know Python. But looks like you means I must create my own view class. And override the funciton resizeEvent.
But if I do so, how can I let Visual Studio to know this view need use my view class but not the QTableView?
And is it sure that when resizeEvent called, the column has been created?
Best Regards,
Michael zhang
Re: set the width of the columns of QTableView
If you change header's resize mode to QHeaderView::ResizeToContents, it should work.
Quote:
Originally Posted by
zhanglr
But if I do so, how can I let Visual Studio to know this view need use my view class but not the QTableView?
In Qt Designer you can use promotion mechanism.
Quote:
Originally Posted by
zhanglr
And is it sure that when resizeEvent called, the column has been created?
You can always check how many columns exist in resizeEvent().
Re: set the width of the columns of QTableView
Hi jacek,
Thanks a lot. :D
Best Regards
Michael zhang