QTableView disable sorting for some columns

2019-06-14 03:24发布

问题:

I am using QtableView(qt5.9) with 10 columns and want to disable sorting for 2nd and 3rd (only some) columns when the user clicks on the header of these columns.

  • I use setsortingenabled flag to make my QtableView allow sorting

  • Is there any signal which I should listen to on clicking of header and then call some appropraite method or deny sorting.

回答1:

You can use the header signal sortIndicatorChanged to restore the current sort indicator.

Example:

    connect(m_poTableView->header(), &QHeaderView::sortIndicatorChanged,
            this, &MyClass::HandleIndicatorChanged);


    MyClass::HandleIndicatorChanged(int logicalIndex, Qt::SortOrder eSort)
    {
       if (logicalIndex != 0)
       {
             this->m_poTableView->horizontalHeader()->setSortIndicator(
                0, this->m_poTableView->model()->sortOrder());
       }
    }