You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PyQt6:QInputDialog无法定位到鼠标光标位置的问题求助

QInputDialog无法在鼠标光标位置显示的解决方法

尝试使用QInputDialog获取输入,希望它能显示在鼠标光标位置,但执行代码后无效,对话框每次都出现在同一位置。其他对象使用move方法可正常移动,但QInputDialog的move和setGeometry方法似乎毫无作用。

原代码:

def createNewNote(self):
    cursor_pos = QCursor.pos()
    input_dialog = QInputDialog(self)
    input_dialog.setWindowTitle("New Note")
    input_dialog.setLabelText("Enter Note Name:")
    input_dialog.setGeometry(cursor_pos.x(), cursor_pos.y(), input_dialog.width(), input_dialog.height())
    ok = input_dialog.exec()
    if ok:
        title = input_dialog.textValue()
        note_node = NoteNode(self)
        note_node.move(cursor_pos)
        note_node.setTitle(title)
        self.note_nodes.append(note_node)
        note_node.show()

问题原因

QInputDialog作为模态对话框,内部包含标签、输入框、按钮等控件,它会在调用exec()时自动计算布局并调整自身尺寸。你提前调用setGeometry时使用的width()和height()是Qt的初始默认值,并非对话框实际渲染后的真实尺寸,后续的布局调整会直接覆盖你设置的位置参数,导致对话框回到默认位置。

解决方案:提前计算真实尺寸再设置位置

先调用adjustSize()强制Qt完成布局计算,获取对话框的真实尺寸后,再用move()设置光标位置:

def createNewNote(self):
    cursor_pos = QCursor.pos()
    input_dialog = QInputDialog(self)
    input_dialog.setWindowTitle("New Note")
    input_dialog.setLabelText("Enter Note Name:")
    
    # 强制对话框计算内部布局后的真实尺寸
    input_dialog.adjustSize()
    # 将对话框左上角对齐光标位置(如需中心对齐,可改为cursor_pos.x()-input_dialog.width()//2, cursor_pos.y()-input_dialog.height()//2)
    input_dialog.move(cursor_pos.x(), cursor_pos.y())
    
    ok = input_dialog.exec()
    if ok:
        title = input_dialog.textValue()
        note_node = NoteNode(self)
        note_node.move(cursor_pos)
        note_node.setTitle(title)
        self.note_nodes.append(note_node)
        note_node.show()

备选方案:临时显示对话框获取真实尺寸

如果adjustSize()在某些环境下仍不生效,可以临时显示再隐藏对话框,让Qt完成渲染后获取真实尺寸:

def createNewNote(self):
    cursor_pos = QCursor.pos()
    input_dialog = QInputDialog(self)
    input_dialog.setWindowTitle("New Note")
    input_dialog.setLabelText("Enter Note Name:")
    
    # 临时显示并隐藏,触发布局计算
    input_dialog.show()
    input_dialog.hide()
    # 此时获取的尺寸为真实渲染后的大小
    input_dialog.move(cursor_pos.x(), cursor_pos.y())
    
    ok = input_dialog.exec()
    if ok:
        title = input_dialog.textValue()
        note_node = NoteNode(self)
        note_node.move(cursor_pos)
        note_node.setTitle(title)
        self.note_nodes.append(note_node)
        note_node.show()

内容的提问来源于stack exchange,提问作者koren69

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.26 08:55:16