📜  PyQt5 QSpinBox – 获取像素比例比例(1)

📅  最后修改于: 2023-12-03 15:03:58.926000             🧑  作者: Mango

PyQt5 QSpinBox – 获取像素比例比例

PyQt5中的QSpinBox小部件用于选择整数值。在某些情况下可能需要获取像素比例比例。本文介绍如何使用QSpinBox小部件来获取像素比例比例。

代码示例
from PyQt5.QtWidgets import QApplication, QMainWindow, QSpinBox
from PyQt5.QtGui import QGuiApplication, QWindow

import sys


class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()

        self.setWindowTitle("QSpinBox")
        self.setGeometry(100, 100, 300, 100)

        self.spin_box = QSpinBox(self)
        self.spin_box.setGeometry(100, 50, 100, 30)

        self.show()

        screen = QGuiApplication.primaryScreen()
        dpi = screen.physicalDotsPerInch()

        window = self.windowHandle()
        device_pixel_ratio = window.devicePixelRatio()

        print("DPI: ", dpi)
        print("Device Pixel Ratio: ", device_pixel_ratio)

        pixel_ratio = dpi / 96 * device_pixel_ratio

        print("Pixel Ratio: ", pixel_ratio)


if __name__ == '__main__':
    app = QApplication(sys.argv)
    window = MainWindow()
    sys.exit(app.exec_())
解释说明

代码中首先导入了必要的类库和模块,而后创建了MainWindow类,并初始化了QSpinBox小部件。接着使用QGuiApplication和QWindow类获取了屏幕的DPI和窗口的设备像素比。最后,计算出像素比例比例并打印到控制台。

screen = QGuiApplication.primaryScreen()
dpi = screen.physicalDotsPerInch()

window = self.windowHandle()
device_pixel_ratio = window.devicePixelRatio()

pixel_ratio = dpi / 96 * device_pixel_ratio

运行结果

运行程序后,DPI、Device Pixel Ratio和Pixel Ratio值将打印在控制台上。例如:

DPI:  96.0
Device Pixel Ratio:  1.0
Pixel Ratio:  1.0
代码下载