Reputation: 9
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.
Upvotes: 0
Views: 193
Reputation: 9
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:
from PyQt5.QtCore import QEvent
from PyQt5.QtWidgets import QApplication, QTextEdit, QMainWindow, QVBoxLayout, QPushButton, QWidget, QSizePolicy
class MyButton(QPushButton):
def __init__(self, parent=None):
super(MyButton, self).__init__(parent)
self.setText("Click me")
self.setFixedSize(600, 200) # set width to 300 pixels and height to 200 pixels
self.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
self.clicked.connect(self.resize_fun)
def resize_fun(self):
self.setFixedSize(200, 100)
print(self.sizeHint())
def sizeHint(self):
print("sizeHint",self.size())
return self.size()
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 = MyButton()
self.layout.addWidget(self.button)
container = QWidget()
container.setLayout(self.layout)
self.setCentralWidget(container)
print(self.button.sizeHint())
def event(self, event) -> bool:
if event.type() == QEvent.LayoutRequest:
print("LayoutRequest",self.sizeHint())
self.setFixedSize(self.sizeHint())
return super().event(event)
app = QApplication([])
window = MainWindow()
window.show()
app.exec_()
window.resize_fun()
Upvotes: -1