[Python] PyQt6 issue in fetching geometry of the window

Discussão em 'Python' iniciado por Stack, Fevereiro 1, 2025.

  1. Stack

    Stack Membro Participativo

    I am currently learning the PyQt6 library and I want to get the geometry of the window. The issue is that the x and y positions are always 0 even after I changed the position of the window on the screen.

    • OS: Ubuntu
    • Python version: 3.9

    import sys
    from PyQt6.QtWidgets import QApplication, QVBoxLayout, QPushButton, QWidget
    from PyQt6.QtCore import QTimer

    class MainWindow(QWidget):
    def __init__(self):
    super().__init__()
    self.resize(200, 300)
    self.setWindowTitle("Main Window")
    layout = QVBoxLayout()
    btn = QPushButton("Click", self)
    btn.clicked.connect(self.print_geometry)
    layout.addWidget(btn)
    self.setLayout(layout)

    self.show()

    def print_geometry(self):
    print(self.geometry()) # This will now print the correct geometry

    if __name__ == '__main__':
    app = QApplication(sys.argv)
    win = MainWindow()
    sys.exit(app.exec())



    Output:

    PyQt6.QtCore.QRect(0, 0, 200, 300)
    PyQt6.QtCore.QRect(0, 0, 200, 300)
    PyQt6.QtCore.QRect(0, 0, 200, 300)
    PyQt6.QtCore.QRect(0, 0, 200, 300)


    I don't know why it is returning 0 for x and y positions. It should have returned the exact position.

    Continue reading...

Compartilhe esta Página