diff --git a/mainwindow.cpp b/mainwindow.cpp index ed19eac..de3fc38 100644 --- a/mainwindow.cpp +++ b/mainwindow.cpp @@ -49,11 +49,9 @@ MainWindow::MainWindow(QWidget *parent) textToSqliteAction->setIcon(convertIcon); sqliteToTextAction->setIcon(convertIcon); - ui->tableWidget->installEventFilter(this); - contextMenu = new QMenu(this); - QAction* addRowAboveAction = contextMenu->addAction(tr("在上方添加行")); - QAction* addRowBelowAction = contextMenu->addAction(tr("在下方添加行")); + QAction* addRowAboveAction = contextMenu->addAction(tr("向上添加一行")); + QAction* addRowBelowAction = contextMenu->addAction(tr("向下添加一行")); connect(addRowAboveAction, &QAction::triggered, this, &MainWindow::onAddRowAboveActionTriggered); connect(addRowBelowAction, &QAction::triggered, this, &MainWindow::onAddRowBelowActionTriggered); } @@ -64,28 +62,20 @@ MainWindow::~MainWindow() delete ui; } -bool MainWindow::eventFilter(QObject* obj, QEvent* event) -{ - if (obj == ui->tableWidget && event->type() == QEvent::ContextMenu) - { - QContextMenuEvent* contextMenuEvent = static_cast(event); - contextMenuEvent->accept(); - contextMenu->exec(contextMenuEvent->globalPos()); - return true; // 事件已处理 - } - return QMainWindow::eventFilter(obj, event); -} - - void MainWindow::contextMenuEvent(QContextMenuEvent* event) { - QPoint cellPos = ui->tableWidget->mapFromGlobal(event->globalPos()); - int currentRow = ui->tableWidget->rowAt(cellPos.y()); - int currentColumn = ui->tableWidget->columnAt(cellPos.x()); + QPoint cellPos = ui->tableWidget->viewport()->mapFromGlobal(event->globalPos()); + int currentColumn = ui->tableWidget->horizontalHeader()->logicalIndexAt(cellPos.x()); - if (currentRow >= 0 && currentColumn == 0) + if (currentColumn == -1) { - contextMenu->exec(event->globalPos()); + int currentRow = ui->tableWidget->rowAt(cellPos.y()); + + if (currentRow >= 0) + { + ui->tableWidget->selectRow(currentRow); // Select the clicked row + contextMenu->popup(event->globalPos()); + } } } diff --git a/mainwindow.h b/mainwindow.h index 7d30049..23873a2 100644 --- a/mainwindow.h +++ b/mainwindow.h @@ -25,7 +25,6 @@ public: void convertTextToSqlite(); void convertSqliteToText(); void showProgressDialog(const QString& labelText, int minimum, int maximum); - bool eventFilter(QObject* obj, QEvent* event); void contextMenuEvent(QContextMenuEvent* event); private slots: