我有一个QTableWidget
,目前拥有其自己的自定义上下文菜单。这是用于设置它的代码:
MyClass::MyClass()
{
m_table->horizontalHeader()->setContextMenuPolicy(Qt::CustomContextMenu);
connect(m_table->horizontalHeader(), SIGNAL(customContextMenuRequested(QPoint)), SLOT(customHeaderMenuRequested(QPoint)));
}
void MyClass::customHeaderMenuRequested(QPoint pos)
{
int columnClicked = m_table->horizontalHeader()->logicalIndexAt(pos);
QMenu * menu = new QMenu(this);
actNone = new QAction("-", this);
menu->addAction(actNone);
.
.
.
menu->popup(m_table->horizontalHeader()->viewport()->mapToGlobal(pos));
}
此上下文菜单在用户右键单击 QTableWidget
的列标题时发生。
我想复制此行为,但我希望它是左键单击而不是右键单击。
我尝试添加EventFilter
和其他内容,但没有任何效果。
谢谢
您必须使用sectionClicked
的QHeaderView
信号,因此必须将customHeaderMenuRequested
参数从QPoint
更改为int
,此参数将指示所按的列,以获得几何位置QCursor::pos()
用于:
MyClass::MyClass()
{
...
connect(m_table->horizontalHeader(), &QHeaderView::sectionClicked, this, &MainWindow::customHeaderMenuRequested);
}
void MyClass::customHeaderMenuRequested(int section)
{
qDebug()<<section;
QMenu * menu = new QMenu(this);
QAction *actNone = new QAction("-", this);
menu->addAction(actNone);
menu->popup(QCursor::pos());
}
更新:
更好的解决方案是实施自定义的QHeaderView
:
headerview.h
#ifndef HEADERVIEW_H
#define HEADERVIEW_H
#include <QHeaderView>
#include <QMouseEvent>
class HeaderView : public QHeaderView
{
Q_OBJECT
public:
using QHeaderView::QHeaderView;
protected:
void mousePressEvent(QMouseEvent *event){
if(event->buttons() == Qt::LeftButton)
emit customSignal(logicalIndexAt(event->pos()));
QHeaderView::mousePressEvent(event);
}
signals:
void customSignal(int section);
};
#endif // HEADERVIEW_H
MyClass::MyClass()
{
...
HeaderView *horizontal_header = new HeaderView(Qt::Horizontal);
m_table->setHorizontalHeader(horizontal_header);
connect(horizontal_header, &HeaderView::customSignal, this, &MainWindow::customHeaderMenuRequested);
}
void MyClass::customHeaderMenuRequested(int section)
{
qDebug()<<section;
QMenu * menu = new QMenu(this);
QAction *actNone = new QAction("-", this);
menu->addAction(actNone);
menu->popup(QCursor::pos());
}