Issue
I saw there is a solution if every widget is on a layout, but in my program I did't use any layouts. How can I make the QPushButtons and QLabels auto-resize if I resize the program's window?
Some code:
from PyQt5.QtWidgets import QApplication, QPushButton, QMainWindow, QLabel
from PyQt5 import QtCore
import sys
class Window(QMainWindow):
def __init__(self):
super().__init__()
self.setWindowTitle("Resizable Widgets")
self.setGeometry(500, 200, 300, 100)
self.UiComponents()
self.show()
def UiComponents(self):
label = QLabel("Label", self)
label.setGeometry(0, 0, 300, 50)
label.setAlignment(QtCore.Qt.AlignCenter | QtCore.Qt.AlignVCenter)
button = QPushButton("Button", self)
button.setGeometry(100, 50, 100, 40)
if __name__ == "__main__":
App = QApplication(sys.argv)
window = Window()
sys.exit(App.exec_())
Solution
If you don’t use layouts, it might look like this:
import sys
from PyQt5.QtWidgets import QApplication, QPushButton, QMainWindow, QLabel
from PyQt5 import QtCore
class Window(QMainWindow):
def __init__(self):
super().__init__()
self.setWindowTitle("Resizable Widgets")
# self.setGeometry(500, 200, 300, 100)
self.w = 300
self.h = 100
self.resize(self.w, self.h)
self.setMinimumSize(self.w/2, self.h/2)
self.widthFactor = 1
self.heightFactor = 1
self.UiComponents()
def UiComponents(self):
self.label = QLabel("Label", self)
# label.setGeometry(0, 0, 300, 50)
self.label.setStyleSheet("font: {}pt Arial;".format(20*self.heightFactor))
self.label.resize(self.w*self.widthFactor, self.h*0.25*self.heightFactor)
self.label.setAlignment(QtCore.Qt.AlignCenter) # | QtCore.Qt.AlignVCenter)
self.button = QPushButton("Button", self)
# button.setGeometry(100, 50, 100, 40)
self.button.resize(self.w*0.25*self.widthFactor, self.h*0.2*self.heightFactor)
def resizeEvent(self, event):
self.widthFactor = self.rect().width() / 300
self.heightFactor = self.rect().height()/ 100
self.label.resize(self.w*self.widthFactor, self.h*0.25*self.heightFactor)
self.label.move(self.rect().center() - self.label.rect().center() - QtCore.QPoint(0, self.h/4*self.heightFactor))
self.label.setStyleSheet("font: {}pt Arial;".format(20*self.heightFactor))
self.button.resize(self.w*0.25*self.widthFactor, self.h*0.2*self.heightFactor)
self.button.move(self.rect().center() - self.button.rect().center() - QtCore.QPoint(0, -self.h*0.3*self.heightFactor))
super(Window, self).resizeEvent(event)
if __name__ == "__main__":
App = QApplication(sys.argv)
window = Window()
window.show()
sys.exit(App.exec_())
Answered By - S. Nick
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.