PyQt5 QSpinBox - How to get the X and Y co-ordinates respectively

PyQt5 QSpinBox - How to get the X and Y co-ordinates respectively

If you want to get the X and Y coordinates of a QSpinBox (or any other QWidget for that matter) relative to its parent, you can use the x() and y() methods. These methods return the X and Y coordinates of the widget's top-left corner relative to its parent.

Here's a simple example to demonstrate how to get the X and Y coordinates of a QSpinBox:

import sys from PyQt5.QtWidgets import QApplication, QMainWindow, QSpinBox, QVBoxLayout, QPushButton, QWidget, QLabel class MainWindow(QMainWindow): def __init__(self): super().__init__() self.central_widget = QWidget(self) self.layout = QVBoxLayout(self.central_widget) self.spin_box = QSpinBox(self.central_widget) self.layout.addWidget(self.spin_box) self.label = QLabel(self.central_widget) self.layout.addWidget(self.label) self.button = QPushButton("Get Coordinates", self.central_widget) self.button.clicked.connect(self.display_coordinates) self.layout.addWidget(self.button) self.setCentralWidget(self.central_widget) def display_coordinates(self): x_coord = self.spin_box.x() y_coord = self.spin_box.y() self.label.setText(f"X: {x_coord}, Y: {y_coord}") app = QApplication(sys.argv) mainWin = MainWindow() mainWin.show() sys.exit(app.exec_()) 

In this example, there's a QSpinBox, a QPushButton, and a QLabel within a QMainWindow. Clicking on the button will retrieve the X and Y coordinates of the QSpinBox and display them in the QLabel.

Note: The coordinates are relative to the parent widget. If you want the global screen coordinates, you can use the mapToGlobal() function:

global_point = self.spin_box.mapToGlobal(self.spin_box.pos()) x_global = global_point.x() y_global = global_point.y() 

More Tags

playsound ipc functional-dependencies shapefile vertical-alignment becomefirstresponder apache-commons-csv apache-camel pausing-execution angular-pipe

More Programming Guides

Other Guides

More Programming Examples