QGraphics框架如何工作?

问题描述 投票:0回答:1

我正在尝试通过PyQT了解GUI。我写了一个垄断游戏,但我没办法正确,我正在使用QGraphicsLayouts获得想要的结果:

Monopoly board

但是我对QGraphics框架的了解是:

Disappointement

这里是代码:

class Board(QGraphicsView):
   def __init__(self):
      super().__init__()

      self.scene = QGraphicsScene()
      self.board = QGraphicsWidget()
      self.board_layout = QGraphicsGridLayout()

      self.properties = [
         "Free Parking", "Strand", "Fleet Street", "Chance", "Trafalgar Square",
         "Fenchurch Street station", "Leicester Square", "Coventry Street", "Water Works", "Piccadilly", "Go to Jail",
         "Vine Street", "", "", "", "", "", "", "", "", "", "Regent Street",
         "Marlborough Street", "", "", "", "", "", "", "", "", "", "Oxford Street",
         "Community Chest", "", "", "", "", "", "", "", "", "", "Community Chest",
         "Bow Street", "", "", "", "", "", "", "", "", "", "Bond Street",
         "Marylebine station", "", "", "", "", "", "", "", "", "", "Liverpool Street station",
         "Northumberland Avenue", "", "", "", "", "", "", "", "", "", "Chance",
         "Whitehall", "", "", "", "", "", "", "", "", "", "Park Lane",
         "Electric Company", "", "", "", "", "", "", "", "", "", "Super Tax",
         "Pall Mall", "", "", "", "", "", "", "", "", "", "Mayfair",
         "Visit Jail", "Pentonville Road", "Euston Road", "Chance", "The Angel Islington", "King's Cross station",
         "Income Tax", "Whitechapel Road", "Community Chest", "Old Kent Road", "Start"
      ]

      positions = [(i, j) for i in range(11) for j in range(11)]

      for position, name in zip(positions, self.properties):
         if name == "":
            continue

         tile = self.scene.addItem(Tile(name, self.scene))
         self.board_layout.addItem(tile, *position)

      self.board.setLayout(self.board_layout)

      self.scene.addItem(self.board)
      self.setScene(self.scene)

class Tile(QGraphicsWidget):
   def __init__(self, name, scene):
      super().__init__()
      self.name = name
      self.tokens = []
      self.layout = QGraphicsLinearLayout()
      self.layout.setOrientation(Qt.Vertical)
      text = QGraphicsTextItem(self.name)
      self.layout.addItem(text)
      print(self.layout.itemAt(1))
      self.setLayout(self.layout)

我的最终目标是在磁贴上显示玩家,以及财产的属性以访问磁贴的内容->如果它是拥有的,当前在其中的玩家,租金价格等...但是我认为我没有正确使用QGraphics框架。关于如何实现我想要的任何建议或提示?

python qt pyqt5
1个回答
0
投票

您没有将磁贴添加到布局中:

        tile = self.scene.addItem(Tile(name, self.scene))
        print(tile)
>>> None

self.scene.addItem()与其他便利函数(返回QGraphicsItem)的其他scene.add(例如addRect,addLine等)不同:addItem返回None,因为该项已经存在,因此您尝试添加nothing 分配到布局,这就是为什么它们未按应对齐的原因。

只需获取tile对象引用,然后将that添加到布局中;同样,也不需要将其添加到场景中:由于您已将它们添加到Board父项中,因此一旦将其添加到场景中,它们就会自动出现。

         tile = Tile(name, self.scene)
         self.board_layout.addItem(tile, *position)

PS:您的示例包含许多不必要的代码,需要进行一些编辑才能使其实际运行并最终解决问题;请考虑对其进行编辑以使其保持为minimal, reproducible example,并记住以后也要进行此操作。

© www.soinside.com 2019 - 2024. All rights reserved.