我使用Qt Designer创建一个简单的UI并将其转换为Python代码.我搜索了任何检测更改窗口大小的方法.
这是生成的代码:
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_MainWindow(object):
def onResize(event):
print(event)
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.setWindowTitle("MainWindow")
MainWindow.resize(200, 200)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
MainWindow.setCentralWidget(self.centralwidget)
MainWindow.resized.connect(self.someFunction)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
MainWindow = QtWidgets.QMainWindow()
ui = Ui_MainWindow()
ui.setupUi(MainWindow)
MainWindow.show()
sys.exit(app.exec_())
我发现了一个类似的问题QWidget resize signal?和this tutorial to handle size,建议覆盖QMainWindow的resizeEvent方法.
但他们中的任何一个都无法解决我的问题.是否有任何调整大小的函数来检测窗口大小调整,如下所示:
MainWindow.resized.connect(self.someFunction)
解决方法:
默认情况下没有这样的信号,但您可以创建调整大小的信号,我们在resizeEvent函数中发出它.
例如:
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.setWindowTitle("MainWindow")
MainWindow.resize(200, 200)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
MainWindow.setCentralWidget(self.centralwidget)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
class Window(QtWidgets.QMainWindow):
resized = QtCore.pyqtSignal()
def __init__(self, parent=None):
super(Window, self).__init__(parent=parent)
ui = Ui_MainWindow()
ui.setupUi(self)
self.resized.connect(self.someFunction)
def resizeEvent(self, event):
self.resized.emit()
return super(Window, self).resizeEvent(event)
def someFunction(self):
print("someFunction")
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
w = Window()
w.show()
sys.exit(app.exec_())