gpt4 book ai didi

c++ - QTableWidget 右键单击​​事件的问题

转载 作者:行者123 更新时间:2023-11-28 02:47:21 29 4
gpt4 key购买 nike

我能够通过子类化 QTableWidget 来模拟右键单击事件:

头文件:

#ifndef QRIGHCLICKTABLE_H
#define QRIGHCLICKTABLE_H

#include <QTableWidget>
#include <QMouseEvent>

class QRightClickTable : public QTableWidget
{
Q_OBJECT

public:
explicit QRightClickTable(QWidget *parent = 0);

private slots:
void mousePressEvent(QMouseEvent *e);

signals:
void rightClicked();

public slots:

};

#endif // QRIGHCLICKTABLE_H

cpp文件

QRightClickTable::QRightClickTable(QWidget *parent) :
QPushButton(parent)
{
}

void QRightClickTable::mousePressEvent(QMouseEvent *e)
{
if(e->button()==Qt::RightButton)
emit rightClicked();
}

QRightClickTable *button = new QRightClickTable(this);
ui->gridLayout->addWidget(button);
connect(button, SIGNAL(rightClicked()), this, SLOT(onRightClicked()));


void MainWindow::onRightClicked()
{
qDebug() << "User right clicked me";
}

现在,右键单击可以正常工作,但 QTableWidget 还存在其他问题:所有其他鼠标事件,例如左键单击以选择单元格,不再起作用。你能帮帮我吗?

最佳答案

    softwareTableWidget = new QTableWidget();
softwareTableWidget->setContextMenuPolicy(Qt::CustomContextMenu);
QObject::connect(softwareTableWidget, &QTableWidget::customContextMenuRequested, this, [this](){
QMenu *menu = new QMenu;
auto a = menu->addAction("Test");
QObject::connect(a, &QAction::triggered, this, [this, menu, a](){
qDebug() << "Test";
a->deleteLater();
menu->deleteLater();
});
menu->exec(QCursor::pos());
menu->clear();
});

如果你只想在项目点击时显示上下文菜单,那么添加这个:

if (softwareTableWidget->itemAt(softwareTableWidget->mapFromGlobal(QCursor::pos())))
{
QMenu *menu = new QMenu;
auto a = menu->addAction("Test");
QObject::connect(a, &QAction::triggered, this, [this, menu, a](){
qDebug() << "Test";
a->deleteLater();
menu->deleteLater();
});
menu->exec(QCursor::pos());
menu->clear();
}

当然你可以做任何你想做的而不是显示上下文菜单

关于c++ - QTableWidget 右键单击​​事件的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23974919/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com