问题描述
你如何制作一个指定大小的 QGraphicsScene 和一个 QGraphicsView 来监控相同大小的场景?
How do you make a QGraphicsScene with a specified size and a QGraphicsView to monitor that scene with the same size?
这听起来像是一个愚蠢的问题,但请考虑以下测试代码 [1]
This sounds like a stupid question but consider the following test code [1]
import sys
from PyQt4 import QtGui, QtCore
class MainWindow(QtGui.QMainWindow):
def __init__(self):
QtGui.QMainWindow.__init__(self)
self.scene = QtGui.QGraphicsScene(0, 0, 200, 200, self)
self.view = QtGui.QGraphicsView(self.scene, self)
#self.view.setMaximumSize(200, 200)
self.setCentralWidget(self.view)
if __name__ == '__main__':
app = QtGui.QApplication(sys.argv)
win = MainWindow()
win.show()
sys.exit(app.exec_())
当我运行它时,我得到一个带有 QGraphicsView 的小窗口,没有滚动条.如果我缩小窗口滚动条,因为我使视图小于指定的场景大小.如果我放大窗口,条形就会消失,并且视图会随着窗口调整大小.所有这些都是有道理的.
When I run this I get a little window with the QGraphicsView and no scroll bars. If I shrink the window scroll bars appear because I've made the view smaller than the specified size of the scene. If I enlarge the window the bars go away and the view resizes with the window. All of this makes sense.
现在我再次运行相同的代码,但注释行(以# 开头)未注释.窗口与视图一起出现,但视图有滚动条.当我缩小窗口时,视图也会缩小,但是当我放大窗口时,视图只会放大到一定大小.这并不奇怪. 令人惊讶的是,当视图处于最大尺寸时,滚动条仍然存在.我不明白这是因为视图的最大大小与代码中的场景大小显式匹配.
Now I run the same code again but with the commented line (preceded by #) un-commented. The Window appears with the view inside, but the view has scroll bars. When I shrink the window the view also shrinks, but when I enlarge the window the view only enlarges to a certain size. This is not surprising. What is surprising is that with the view at it's maximum size, the scroll bars are still there. I don't understand this because the maximum size of the view is explicitly matched to the size of the scene in the code.
为什么会发生这种情况?
Why does this happen?
我知道其他问题已经解释了如何强制场景和视图组合在一起,但我想了解我实际制作的视图和场景的尺寸,因此我尝试使用明确指定的尺寸.
I am aware that other questions have explained how to force the scene and view to fit together but I want to understand what size view and scene I have actually made, hence my attempt to use explicitly specified sizes.
[1] 我正在使用 PyQt,C++ 用户只是将self"读作this",将import"读作#include"
[1] I'm using PyQt, C++ users just read "self" as "this" and "import" as "#include"
下面接受的答案是绝对正确的.我只想为阅读本文的其他人补充一点,如果您的视图在布局中,您还必须考虑布局边距.这些可以在 QtDesigner 等中明确设置.
The accepted answer below is absolutely correct. I would just like to add for others who read this that if your view is in a layout you have to account for the layout margins as well. These can be explicitly set in the QtDesigner etc.
推荐答案
好的,我为你解决了!
QGraphicsView(QFrame 的子类)有一个边框.如果您将以下行添加到您的 init 方法中:
The QGraphicsView (which subclasses QFrame) has a border. If you add the below line to your init method:
self.view.setFrameShape(QtGui.QFrame.NoFrame)
然后您删除 1px 框架,它按预期工作!
then you remove the 1px frame and it works as you expect!
这篇关于QGraphicsView/QGraphicsScene 大小匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!