优化右键菜单增加行功能

This commit is contained in:
阿甘 2023-08-13 22:22:09 +08:00
parent 5744d80e69
commit dd9f9408c1
2 changed files with 12 additions and 23 deletions

View File

@ -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<QContextMenuEvent*>(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());
}
}
}

View File

@ -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: