【问题标题】:How to put the window in the top left corner with PyQt?如何使用 PyQt 将窗口放在左上角?
【发布时间】:2020-12-10 23:10:31
【问题描述】:

我试图通过运行以下代码将我的窗口放在左上角:

import sys
from PyQt5 import QtGui
class MainWindow(QtGui.QWidget):

    def __init__(self):
        super(MainWindow, self).__init__()
        self.initUI()

    def initUI(self):
        self.resize(640, 480)
        self.topLeft()
        self.show()

    def topLeft()(self):
        frameGm = self.frameGeometry()
        topLeftPoint = QApplication.desktop().availableGeometry().topLeft()
        frameGm.moveTopLeft(topLeftPoint)
        self.move(frameGm.topLeft())

def main():
    app = QApplication(sys.argv)
    mainWindow = MainWindow()
    sys.exit(app.exec_())

if __name__ == '__main__':
    main()

但是这样做,我的窗口和屏幕左侧之间会出现这样的间隙:

你知道它来自哪里以及如何预防吗?

【问题讨论】:

  • 对示例要更加小心,并确保它们始终是both minimal and reproducible:QWidget 是 PyQt5 中的 QtWidgets 类(不是 QtGui),并且有一个不必要的 @ 987654324@在topLeft的声明中。

标签: python-3.x qt pyqt qgis


【解决方案1】:

这是因为当一个窗口第一次在屏幕上显示时,在show() 和窗口实际映射到屏幕上的那一刻之间发生了一些事情(实际上是很多)。

为了达到您想要的效果,您需要将移动延迟一些时间(通常,在事件循环的“循环”上就足够了)。使用具有 1 个超时的单次 QTimer 通常没问题。

class MainWindow(QtGui.QWidget):
    def __init__(self):
        super(MainWindow, self).__init__()
        self.initUI()

    def initUI(self):
        self.resize(640, 480)
        QTimer.singleShot(1, self.topLeft)
        self.show()

    def topLeft(self):
        # no need to move the point of the geometry rect if you're going to use
        # the reference top left only
        topLeftPoint = QApplication.desktop().availableGeometry().topLeft()
        self.move(topLeftPoint)

【讨论】:

  • 感谢您的回答,我已尝试这样做,但仍然遇到同样的问题。事实上,这些代码行是当放在屏幕边缘时调整窗口大小的函数的一部分:stackoverflow.com/questions/63518997/… 如果你能在上面放一个 lokk,你会很有帮助的! :)
  • 如果尝试增加超时时间(例如 1000,即 1 秒)会怎样?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-04-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-06-13
相关资源
最近更新 更多