PyQt5 – 设置固定的高度或宽度的窗口大小

PyQt5 – 设置固定的高度或宽度的窗口大小

当我们创建一个窗口时,默认情况下窗口的大小是可以调整的,尽管如此,我们可以使用setFixedSize()方法来设置窗口的固定大小,但是如果我们只想设置固定的高度或宽度,我们就不能使用这个方法。我们想设置一个固定的长度,另一个是可变的,为了做到这一点,我们必须使用setFixedWidth()方法来设置固定的宽度长度,setFizedHeight()方法来设置固定的高度长度。

语法:

self.setFixedWidth(width)
self.setFixedHeight(height)

参数: 两者都以整数为参数。

执行的动作: setFixedWidth()设置恒定宽度。 setFixedHeight()设置恒定高度。

固定宽度的代码

# importing the required libraries
 
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
import sys
 
 
class Window(QMainWindow):
    def __init__(self):
        super().__init__()
 
 
        # set the title
        self.setWindowTitle("Python")
 
        width = 500
         
        # setting  the fixed width of window
        self.setFixedWidth(width)
 
 
        # creating a label widget
        self.label_1 = QLabel("Fixed width", self)
 
        # moving position
        self.label_1.move(0, 0)
 
        # setting up the border
        self.label_1.setStyleSheet("border :3px solid black;")
 
        # resizing label
        self.label_1.resize(120, 80)
 
        # show all the widgets
        self.show()
 
 
# create pyqt5 app
App = QApplication(sys.argv)
 
# create the instance of our Window
window = Window()
 
# start the app
sys.exit(App.exec())

输出 :

PyQt5 - 设置固定的高度或宽度的窗口大小

固定高度的代码 –

# importing the required libraries
 
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
import sys
 
 
class Window(QMainWindow):
    def __init__(self):
        super().__init__()
 
 
        # set the title
        self.setWindowTitle("Python")
 
        height = 400
        # setting  the fixed height of window
        self.setFixedHeight(height)
 
 
        # creating a label widget
        self.label_1 = QLabel("Fixed height", self)
 
        # moving position
        self.label_1.move(0, 0)
 
        # setting up the border
        self.label_1.setStyleSheet("border :3px solid black;")
 
        # resizing label
        self.label_1.resize(120, 80)
 
        # show all the widgets
        self.show()
 
 
# create pyqt5 app
App = QApplication(sys.argv)
 
# create the instance of our Window
window = Window()
 
# start the app
sys.exit(App.exec())

输出 :

PyQt5 - 设置固定的高度或宽度的窗口大小

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程