PDA

View Full Version : set the width of the columns of QTableView



zhanglr
28th July 2008, 22:46
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

jacek
28th July 2008, 23:12
How about using the SizeHint role in the model?

zhanglr
29th July 2008, 14:26
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?


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)
{
QSize size(100, 50);
if (section == 0)
{
size.setWidth(200);
}

return QVariant(size);
}
}
}

return QVariant();
}


Regards,
Michael zhang

fifth
29th July 2008, 19:44
I generally do this by extending the table view and modifying the resizeEvent method;



# Python code ...
class MyTable(QTableView):

def __init__(self, model, parent = None):
super(MyTable, self).__init__(parent)

rowHeight = self.fontMetrics().height()
self.verticalHeader().setDefaultSectionSize(rowHei ght)
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

zhanglr
29th July 2008, 22:15
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

jacek
30th July 2008, 22:14
If you change header's resize mode to QHeaderView::ResizeToContents, it should work.


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 (http://doc.trolltech.com/4.4/designer-using-custom-widgets.html#promoting-widgets) mechanism.


And is it sure that when resizeEvent called, the column has been created?
You can always check how many columns exist in resizeEvent().

zhanglr
31st July 2008, 15:29
Hi jacek,

Thanks a lot. :D

Best Regards
Michael zhang