【问题标题】:QHeaderView::mousePressEvent (need to figure out the column/index)QHeaderView::mousePressEvent (需要弄清楚列/索引)
【发布时间】:2012-10-23 01:07:01
【问题描述】:

通常,当我重新实现 QTableView::mousePressEvent( QMouseEvent* ) 时,我可以让它正常工作。但是,在 QHeaderView 上执行此操作对我不起作用。代码很简单。

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 );
}
QMouseEvent 中的

x() 和 y() 很好。但是,它会创建一个无效索引,其中 row() 为 -1,column() 为 -1。显然,我将一个空字符串传递给 handle_right_click() 以启动菜单。该菜单不知道是哪一列调用了它,混乱将进一步接踵而至。

我知道 clicked( const QModelIndex& ) 只会告诉我正确的索引和文本。但是,我需要区分按钮。

【问题讨论】:

    标签: qt qheaderview


    【解决方案1】:

    QHeaderView 提供了一个替代函数logicalIndexAt,用于确定您感兴趣的标题项的索引。使用上面的代码:

    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 );
       }
    }
    

    请注意,标头的方向必须传递给 headerData 方法(在这种情况下,我只是假设它是 Qt::Horizontal,但在您的情况下它可能会有所不同)。

    【讨论】:

    • 太棒了——明白了。我知道logicalIndexAt ...不知道为什么我不尝试它。仅对引用此内容的其他人提出警告:默认情况下,QHeaderView 无权访问任何模型()。在继承时,我从父 QTableView 设置并存储模型(在这种情况下实际上是 QSortFilterProxyModel)。再次感谢。
    猜你喜欢
    • 2019-05-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多