我想创建一个小部件:
下面的代码实现了前四个功能,但是如下图所示,在调整窗口大小时,该代码无法保持居中。请注意,诸如heightForWidth
之类的其他方法并不对所有窗口大小都保持宽高比。
我应该如何调整代码以实现上面列出的全部五个功能?
import sys
from PyQt5 import QtWidgets, QtCore
class MyWidget(QtWidgets.QWidget):
def __init__(self, *args):
super().__init__(*args)
self.setAttribute(QtCore.Qt.WA_StyledBackground)
def sizeHint(self):
return QtCore.QSize(1200, 800)
def resizeEvent(self, event):
h = event.size().height()
w = event.size().width()
s = 1.5
if w > s*h:
w = int(s*h)
else:
h = int(w/s)
self.resize(w, h)
if __name__ == '__main__':
app = QtWidgets.QApplication(sys.argv)
dlg = QtWidgets.QDialog()
widget = MyWidget()
widget.setStyleSheet('background-color: rgb(1, 250, 1);')
widget.setMinimumSize( QtCore.QSize(300, 200) )
policy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Maximum, QtWidgets.QSizePolicy.Maximum)
widget.setSizePolicy(policy)
layout = QtWidgets.QHBoxLayout()
layout.addWidget(widget, 0, QtCore.Qt.AlignCenter)
dlg.setLayout(layout)
dlg.resize(600, 600)
dlg.show()
sys.exit(app.exec_())