問題描述
我使用 Qt Designer 創建了一個簡單的 UI,并將其轉換為 Python 代碼.我搜索了任何方法來檢測窗口大小的變化.
I create a simple UI with Qt Designer and convert it to Python codes. I searched for any method to detect changing window size.
這是生成的代碼:
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?和本教程處理大小 建議覆蓋 resizeEvent 方法QMainWindow.
I found a similar question QWidget resize signal? and this tutorial to handle size that recommended overriding resizeEvent method of QMainWindow.
但其中任何一個都不能解決我的問題.是否有任何 resized 函數來檢測窗口調整大小,如下所示:
But any of them doesn't solve my problem. Is there any resized function to detect window resizing like below:
MainWindow.resized.connect(self.someFunction)
推薦答案
默認沒有這個信號,但是你可以創建resized
信號,我們在resizeEvent
函數.
There is no such signal by default, but you can create the resized
signal, we emit it in the resizeEvent
function.
例如:
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_())
這篇關于檢測 Widget-window resized 信號中的調整大小的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!