1

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.

kiss-o-matic
  • 1,111
  • 16
  • 32

1 Answers1

3

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).

RA.
  • 7,542
  • 1
  • 34
  • 35
  • Awesome -- that got it. I knew about logicalIndexAt... not sure why I didn't try it. Only caveat for someone else referencing this: QHeaderView does not have access to any model() by default. As I'm inheriting, I set and store the model (actually QSortFilterProxyModel in this case) from the parent QTableView. Thanks again. – kiss-o-matic Oct 23 '12 at 03:20