I am trying to write a very simple class where the main window is supposed to resize when central widget resizes. The problem is that the sizehint of the button gives the same random value independet of the actual size of the button
from PyQt5.QtWidgets import QApplication, QTextEdit, QMainWindow, QVBoxLayout, QPushButton, QWidget, QSizePolicy
class MainWindow(QMainWindow):
def __init__(self, parent=None):
super(MainWindow, self).__init__(parent)
self.layout = QVBoxLayout(self)
self.layout.activate()
#add a button
self.button = QPushButton("Hello Wolrd", self)
self.button.setFixedSize(600, 200) # set width to 300 pixels and height to 200 pixels
self.button.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
self.button.clicked.connect(self.resize_fun)
self.layout.addWidget(self.button)
container = QWidget()
container.setLayout(self.layout)
self.setCentralWidget(container)
print(self.button.sizeHint())
def resize_fun(self):
self.button.setFixedSize(200, 100)
print(self.button.sizeHint())
app = QApplication([])
window = MainWindow()
window.show()
app.exec_()
window.resize_fun()
Output: PyQt5.QtCore.QSize(112, 34) <- before button is clicked PyQt5.QtCore.QSize(112, 34) <- after button is clicked
both valued are obviously wrong. The also do not depend on the button text.
I found some brute force way to fix this by overriding sizeHint in the Button class, but this seems to defeat the purpose of sizeHint to me.
The solution to resize the main window is equally ugly.
Suggestions are very welcome: