PyQT 窗口:我想记住它关闭的位置 [英] PyQT Window: I want to remember the location it was closed at

查看:56
本文介绍了PyQT 窗口:我想记住它关闭的位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 QDialog,当用户关闭 QDialog 并稍后重新打开时,我想记住位置并在完全相同的位置打开窗口.我怎么会记得那个位置?

I have a QDialog, and when the user closes the QDialog, and reopens it later, I want to remember the location and open the window at the exact same spot. How would I exactly remember that location?

推荐答案

为此,您可以使用 saveState(), saveGeometry() resize()move() 方法,与 closeEvent()QSettings 其他答案提到的.下面是一些示例,以了解这个想法:

For that, you can use the saveState(), saveGeometry() resize() and move() methods, in conjunction with the closeEvent() and QSettings mentioned by the other answers. Here is some example, to get the idea:

class MyWindow(QMainWindow):
    def __init__(self, parent):
        QMainWindow.__init__(self, parent)
        self.settings = QSettings("MyCompany", "MyApp")
        self.restoreGeometry(self.settings.value("geometry", ""))
        self.restoreState(self.settings.value("windowState", ""))

    def closeEvent(self, event):
        self.settings.setValue("geometry", self.saveGeometry())
        self.settings.setValue("windowState", self.saveState())
        QMainWindow.closeEvent(self, event)

更新答案以使用 PyQt API v2.如果使用 API v1,则必须手动将 settings.value() 的结果转换为 ByteArray 之类的

Updated answer to use PyQt API v2. If using API v1, you have to manually cast the result of settings.value() to a ByteArray like

self.restoreState(self.settings.value("windowState").toByteArray())

我还使用了窗口自己的 size()pos(),因为我已经从 .ui 加载了窗口文件.如果从头开始编写窗口,您可以在这些行之前将其设置为默认值.对于状态,我默认为一个空字符串,该函数很乐意将其作为空 ByteArray 接受,并且在第一次运行时不执行任何操作.

I also used the window's own size() and pos(), since I'm already loading the windows from a .ui file. You may set it to defaults before those lines if coding the window from scratch. For the state, I'm defaulting to an empty string, which the function happily accepts as an empty ByteArray and does nothing on the first run.

这篇关于PyQT 窗口:我想记住它关闭的位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆