【发布时间】:2017-08-15 05:13:35
【问题描述】:
我正在尝试构建一个 topBar 以放入其他小部件 layout 但我不知道为什么 `QPixmap 在我们更改应用程序窗口大小时没有重新缩放。代码如下:
QPixmap 位于 QHBoxLayout 的 QWidget 内的 QLabel 内,即 centralWidget 的 QMainWindow 内
QT 5.8 - Python 3.6
我已在 2017 年 3 月 24 日更新了此代码并删除了之前的版本。
0 - 依赖项
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *
import sys
1 - 主窗口
class MainWindow(QMainWindow):
def __init__(self):
print("I've been in main window")
super().__init__()
self.initUI()
def initUI(self):
self.setWindowTitle("I'm here, the main window")
2 - 顶栏
class topBar(QWidget):
def __init__(self):
print("I've been in topBar")
super().__init__()
self.initUI()
def initUI(self):
self.setObjectName("topBar")
self.setStyleSheet("""
QWidget {background-color: pink;}
QLabel {background-color: green; }""")
def resizeEvent(self,event):
resizeHandler(self,event) # You'll see this little dude right next
3 - resizeEvent 处理程序,我认为 问题 是
def resizeHandler(self,event):
print(" I've been in resizeHandler")
if self.objectName() == "topBar":
print("I've been resizing the topBar")
logo = QPixmap('some_Image')
# Debug
# You'll be able to see that it does re-scale, but it's not updating the Pixmap.
logo.scaled(event.size(),Qt.KeepAspectRatio).save("pixmap.png")
# ...
logoContainer = QLabel()
logoContainer.setPixmap(logo.scaled(event.size(),Qt.KeepAspectRatio,Qt.FastTransformation))
logoContainer.setMaximumSize(logo.width(),logo.height())
containerLayout = QHBoxLayout()
containerLayout.addWidget(logoContainer,0)
container = QWidget()
container.setLayout(containerLayout)
# Layout
layout = QHBoxLayout()
layout.addWidget(container,0)
self.setLayout(layout)
main.setCentralWidget(self)
4 - 测试
if __name__ == '__main__':
print("I've been in __main__")
app = 0
app = QApplication(sys.argv)
app.aboutToQuit.connect(app.deleteLater)
app.setWindowIcon(QIcon('someIcon'))
main = MainWindow()
main.layout().setSizeConstraint(QLayout.SetNoConstraint)
bar = topBar()
main.setCentralWidget(bar)
main.show()
app.exec_()
如果可能的话,我还想限制topBar itself 垂直不超过当前屏幕尺寸的 20%(setMaximumHeight?但基于什么?)但我不确定如何。
谢谢!
【问题讨论】:
-
是什么让您认为
container没有缩放?将self.setStyleSheet("""更改为container.setStyleSheet(""",您将看到container缩放直到达到您设置的最大大小。真正的问题不是logo没有缩放吗? -
有一刻我以为容器没有随着当前屏幕的缩小或扩大而调整大小。在过去的 3 天里,我一直在尝试解决这个非常简单的问题的许多方法,但我无法解决它。我删除了
setScaledContents(True)并尝试重新定义resizeEvent以将像素图更新为pixmap.scaled(main.width(),main.height(),Qt.KeepAspectRatio)的最新方法,但这也不起作用=/。 (主要是QMainWindow和topBar是CentralWidget) -
@G.M.我已经更新了问题和代码,看来真正的问题是
QPixmap没有更新它的大小。
标签: qt python-3.x pyqt qt5 pyqt5