pythonuser-interfacepyqtscreen-resolutionpyqt6

How to do content scaling in PyQt6?


So I build a desktop application using PyQt6 and I want the desktop application content to resize with our screen size. For example I have this layout which has 770 x 550 ratio and I want this user interface ratio to work on any given monitor size. Does anyone know how to do it? For example, in VScode app, when you resize the content then VScode UI placement will remain the same. How do I achieve such effect in PyQt6?

I already tried to use resize event but the widgets did not resize with the UI nor the placement do. I also have watched in Youtube by using matrices, but was it really necessary to build application that could resize?


Solution

  • Can you post the code of your main window and add picture of what you have now and what you want the window to do?

    Without knowing too much about your window you can use one of the layout managers included with PyQt such as QHBoxLayout and QVBoxLayout. Then you can use stretch factors to keep the same "aspect ratio"

    For example:

    # Resizing window
    
    from PyQt6.QtWidgets import QWidget, QPushButton, QMainWindow, QApplication, QHBoxLayout, QVBoxLayout, QLabel
    from PyQt6.QtGui import QColor, QPalette
    
    
    class Color(QWidget):
        def __init__(self, color):
              super().__init__()
              self.setAutoFillBackground(True)
    
              
              palette = self.palette()
              palette.setColor(QPalette.ColorRole.Window, QColor(color))
              self.setPalette(palette)
              
    
    class MainWindow(QMainWindow):
        def __init__(self):
            super().__init__()
         
           
            # Left Frame
            
            left_frame = Color('blue')
            left_frame_layout = QVBoxLayout()
    
            left_frame_layout.addWidget(QPushButton(text =  'click me'))
            left_frame_layout.addWidget(QLabel('this is the left frame'))
    
            left_frame.setLayout(left_frame_layout)
    
    
            # Right Frame
            
            right_frame = Color('green')
            right_frame_layout = QHBoxLayout()
    
            right_frame_layout.addWidget(QPushButton(text =  'click me'))
            right_frame_layout.addWidget(QLabel('this is the right frame'))
    
            right_frame.setLayout(right_frame_layout)
            
    
            # Main Frame
            main_layout = QHBoxLayout()
    
            main_layout.addWidget(left_frame,0)  # with a stretch factor of 0, this frame won't take any new avaible space when resizing horizontally
            main_layout.addWidget(right_frame,1) # stretch factor of 1.
        
            
            main_frame = QWidget()
            main_frame.setLayout(main_layout)
            self.setCentralWidget(main_frame)
    
         
    app = QApplication([])
    window = MainWindow()
    window.show()
    app.exec()