Qt 鼠标右键菜单显示不超出屏幕底部

#include 

void MainWindow::tableWidget_test_showMenu(const QPoint pos)
{
	tableWidget_test_menu->move(cursor().pos());
    tableWidget_test_menu->show();
    int x = pos.x();
    int y = pos.y();

    QDesktopWidget* desktopWidget =QApplication::desktop();
    QRect desktopRect =desktopWidget->screenGeometry(); // 获取屏幕信息
    qDebug() << "desktopRect: " << desktopRect;

    QPoint global = tableWidget_test_menu->mapToGlobal(QPoint(0, tableWidget_test_menu->height()));  // 得到右键菜单左下角的坐标
    if (global.y() > desktopRect.height()) {   // 超过屏幕底部
    	// 向上移动到刚好和屏幕底部齐平
        global.setY(desktopRect.height() - tableWidget_test_menu->height());
    } else {
    	// 恢复原来位置,不移动
        global.setY(global.y() - tableWidget_test_menu->height());
    }
    tableWidget_test_menu->move(global);
    tableWidget_test_menu->show();
}

当菜单会超出屏幕底部时,会向上移动:
Qt 鼠标右键菜单显示不超出屏幕底部_第1张图片

当菜单不超出屏幕底部时,就正常显示:
Qt 鼠标右键菜单显示不超出屏幕底部_第2张图片

你可能感兴趣的:(Qt,qt)