2012-10-23 36 views
0

當我重新實現QTableView :: mousePressEvent(QMouseEvent *)時,通常我可以得到這個工作沒問題。但是,在QHeaderView上執行它並不適合我。代碼很簡單。QHeaderView :: mousePressEvent(需要找出列/索引)

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(),它將啓動菜單。該菜單不會知道哪一欄叫它,並且混亂將進一步發生。

我知道點擊(const QModelIndex &)會告訴我正確的索引和文本。不過,我需要區分按鈕。

回答

3

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,但在你的情況下它可能會有所不同)。

+0

太棒了 - 知道了。我知道logicalIndexAt ...不知道爲什麼我沒有嘗試它。 只需注意別人的引用: 默認情況下,QHeaderView無法訪問任何模型()。正如我繼承,我從父QTableView中設置和存儲模型(在這種情況下實際上是QSortFilterProxyModel)。 再次感謝。 –

相關問題