QHeaderView::mousePressEvent (need to figure out the column/index)

2.6k Views Asked by At

Generally I can get this to work no problem when I reimplement QTableView::mousePressEvent( QMouseEvent* ). However, doing it on QHeaderView is not working for me. Code is simple.

void my_header_t::mousePressEvent( QMouseEvent* event )
{
    if ( !event ) {
    return;
}

if ( event->button() == Qt::RightButton ) {

    QPoint point( event->x(), event->y() );
    QModelIndex index   = indexAt( point );

    printf( "%s data %s %d,%d %s (point: %d,%d )\n",
        ts().c_str(), index.data().toString().toStdString().c_str(),
        index.row(), index.column(), index.isValid() ? "True" : "False",
        event->x(), event->y() );

    handle_right_click( index.data().toString() );

} else {
    QHeaderView::mousePressEvent( event );
}

x() and y() from the QMouseEvent are fine. However, it creates an invalid index, with row() of -1, and column() of -1. Obviously, I'm passing an empty string to handle_right_click() which kicks off a menu. That menu is not going to know which column called it, and the mayhem will further ensue.

I know that clicked( const QModelIndex& ) will just tell me the right index, with the text. However, I need to differentiate between buttons.

1

There are 1 best solutions below

1
On

QHeaderView provides an alternative function, logicalIndexAt, for determining the index of the header item that you're interested in. Using your code from above:

void my_header_t::mousePressEvent( QMouseEvent* event )
{
   if ( !event ) {
      return;
   }

   if ( event->button() == Qt::RightButton ) {
      int index = logicalIndexAt( event->pos() );

      handle_right_click(model()->headerData(index, Qt::Horizontal).toString());

   } else {
      QHeaderView::mousePressEvent( event );
   }
}

Note that the orientation of the header must be passed to the headerData method (in this case, I've just assumed that it's Qt::Horizontal, but in your case it might be something different).