如何将 QPushButton 锚定到 QScrollArea 上的特定位置?

How can you anchor a QPushButton to a specific location on a QScrollArea?

我有一张包含在可滚动区域内的大地图。我想要做的是点击一个国家的名称,名称是 PyQt5 QPushButton。我现在拥有的是一个按钮,它相对于屏幕而不是地图保持在同一个位置:

import sys

from PyQt5.QtGui import QPixmap, QPalette
from PyQt5.QtWidgets import QApplication, QScrollArea, QLabel, QPushButton


class MapGUI(QScrollArea):

    def __init__(self):
        super().__init__()
        self.initUI()

    def initUI(self):
        screen_resolution = app.desktop().screenGeometry()
        width, height = screen_resolution.width(), screen_resolution.height()
        self.setGeometry(0, 0, height, height)
        self.setWindowTitle("The World")

        self.label = QLabel()
        self.pixmap_unscaled = QPixmap("The_World.png")
        # Scaling the image to half the size
        self.pixmap = self.pixmap_unscaled.scaled(int(self.pixmap_unscaled.width() * 0.5), int(self.pixmap_unscaled.height() * 0.5))
        self.label.setPixmap(self.pixmap)

        self.button = QPushButton('PyQt5 button', self)
        self.button.setToolTip('This is an example button')
        self.button.setGeometry(100, 100, 100, 50)


        self.setBackgroundRole(QPalette.Dark)
        self.setWidget(self.label)

        self.show()


if __name__ == "__main__":

    app = QApplication(sys.argv)

    map = MapGUI()

    sys.exit(app.exec_())

通过这样做按钮是静态的。有没有办法将地图的移动与按钮的移动联系起来,这样当我滚动按钮时按钮就会随之移动?

小部件的位置是相对于您的 parent 的,在您的例子中,按钮的 parent 是 QScrollArea,但由于您希望它移动到QLabel,这必须是你的 parent,在你的情况下它会改变:

self.button = QPushButton('PyQt5 button', self)

至:

self.button = QPushButton('PyQt5 button', self.label)