gpt4 book ai didi

python - 在 PyQt5 中对齐弹出窗口小部件

转载 作者:行者123 更新时间:2023-12-01 00:17:37 25 4
gpt4 key购买 nike

我在 SO 上看到了很多关于此事的回复,但不是专门针对 QMenu 和 QToolButton 的。希望能提供一些有关将弹出窗口小部件与按钮右侧对齐的指示。这是我正在处理的基本代码..

import sys
from PyQt5.QtWidgets import *


class test(QWidget):
def __init__(self):
super().__init__()
self.resize(200, 100)
layout = QHBoxLayout(self)
label = QLabel('Testing QToolButton Popup')
toolbutton = QToolButton()
toolbutton.setPopupMode(QToolButton.InstantPopup)

widget = QWidget()
widgetLayout = QHBoxLayout(widget)
widgetLabel = QLabel('Popup Text')
widgetSpinbox = QSpinBox()
widgetLayout.addWidget(widgetLabel)
widgetLayout.addWidget(widgetSpinbox)

widgetAction = QWidgetAction(toolbutton)
widgetAction.setDefaultWidget(widget)

widgetMenu = QMenu(toolbutton)
widgetMenu.addAction(widgetAction)
toolbutton.setMenu(widgetMenu)

layout.addWidget(label)
layout.addWidget(toolbutton)


if __name__ == '__main__':
app = QApplication(sys.argv)
win = test()
win.show()
sys.exit(app.exec_())

结果如下所示:

popup image

最佳答案

Qt 开发人员认为默认位置是正确的,因此如果您想修改对齐方式,则必须移动 QMenu,如下所示:

import sys
from PyQt5.QtCore import QPoint
from PyQt5.QtWidgets import (
QApplication,
QHBoxLayout,
QLabel,
QMenu,
QSpinBox,
QToolButton,
QWidgetAction,
QWidget,
)


class Menu(QMenu):
def showEvent(self, event):
if self.isVisible():
button = self.parentWidget()
if button is not None:
pos = button.mapToGlobal(button.rect().bottomRight())
self.move(pos - self.rect().topRight())
super().showEvent(event)


class Test(QWidget):
def __init__(self):
super().__init__()
self.resize(200, 100)
layout = QHBoxLayout(self)
label = QLabel("Testing QToolButton Popup")
toolbutton = QToolButton(popupMode=QToolButton.InstantPopup)

widgetLabel = QLabel("Popup Text")
widgetSpinbox = QSpinBox()

widget = QWidget()
widgetLayout = QHBoxLayout(widget)
widgetLayout.addWidget(widgetLabel)
widgetLayout.addWidget(widgetSpinbox)

widgetAction = QWidgetAction(toolbutton)
widgetAction.setDefaultWidget(widget)

widgetMenu = Menu(toolbutton)
widgetMenu.addAction(widgetAction)
toolbutton.setMenu(widgetMenu)

layout.addWidget(label)
layout.addWidget(toolbutton)


if __name__ == "__main__":
app = QApplication(sys.argv)
win = Test()
win.show()
sys.exit(app.exec_())

关于python - 在 PyQt5 中对齐弹出窗口小部件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59201657/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com