通常,当我重新实现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()传递了一个空字符串,它将启动一个菜单。该菜单不会知道是哪一列调用了它,混乱将进一步接踵而至。
我知道点击( const QModelIndex& )只会告诉我正确的索引和文本。但是,我需要区分按钮。
发布于 2012-10-23 10:21:46
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,但在您的示例中,它可能是不同的值)。
https://stackoverflow.com/questions/13022211
复制相似问题