C ++ QTableWidget左键单击CustomContextMenu

时间:2018-04-11 21:13:53

标签: c++ qt contextmenu qtablewidget

我有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和其他内容,但没有任何效果。

谢谢

1 个答案:

答案 0 :(得分:1)

您必须使用sectionClicked的{​​{1}}信号,因此您必须将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()); }

<强> headerview.h

QHeaderView
#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