开发者

Changing QAbstractTableModel headerData using the role

开发者 https://www.devze.com 2023-04-13 07:50 出处:网络
I have a subclass class TableModel : public QAbstractTableModel I override the headerData method as follow:

I have a subclass

class TableModel : public QAbstractTableModel

I override the headerData method as follow:

QVariant TableModel::headerData(int section, Qt::Orientation orientation, int role) const
{
   if (role == Qt::DisplayRole && orientation == Qt::Horizontal) {...}
   if (role == TableModel::CurrencyRole && orientation == Qt::Horizontal) {...}
   return QVariant();
}

I have a method that set a QTableView as follow using TableModel* table

void A::SetDisplay(QTableView* table_view, QString filter, int role, int sort_role)
{
  proxyModel = new QSortFilterProxyModel(this);
  proxyModel->setSourceModel(table);
  proxyModel->setDynamicSortFilter(true);
  proxyModel->setSortRole(sort_role);
  table_view->setModel(proxyModel);
  table_view->setSortingEnabled(true);
  table_view->setSelectionBehavior(QAbstractItemView::SelectRows);
  table_view->horizontalHeader()->setStretchLastSection(true);
  table_view->verticalHeader()->hide();
  table_view->setEditTriggers(QAbstractItemView::NoEditTriggers);
  table_view->setSelectionMode(QAbstractItemView::SingleSelection);
  proxyModel->setFilterRegExp(QRegExp(filter, Qt::CaseInsensitive));
  proxyModel->setFilterKeyColumn(1);
  proxyModel->sort(0, Qt::AscendingOrder);
  connect( table_view->selectionModel(),
    SIGNAL(selectionChanged(QItemSelection,QItemSelection)),
    this, SIGNAL(selectionChanged(QItemSelection)));
}

I have two QTableView objects ViewA and viewB. I need ViewA to have a header with role == Qt::Displ开发者_如何学编程ayRole and viewB to have a header with role == TableModel::CurrencyRole. How can I get the headerData to change for each view using the role.

Thanks, and please let me know if I left any detail out or or something is unclear in my question.


First of all, it looks like to do exactly what you're trying to to is going to be a bit tricky.

After a quick perusal of the Qt source code it looks like there's no way to change what role is passed to your model's headerData() function just using the API.

You do, however, have the ability to subclass QHeaderView and override the virtual paintSection() function and then do whatever you want. You'll probably need to look over Qt's implementation of this function for reference of how to implement it properly.

At this point you can set the header view on your views to your new custom one, and then set some internal flag from your view that tells it how to properly call headerData() with the role you want.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号