gpt4 book ai didi

c++ - 如何在更改文本后调整 QWidgetAction 显示的 QLabel 的大小

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:10:40 25 4
gpt4 key购买 nike

我使用 QWidgetAction 将标题添加到上下文菜单(与 addSection() 相比,无论使用何种样式,它也会显示在 Windows 上>,实际上并不总是显示标题)。

该操作的小部件是一个QLabel。每次调用上下文菜单都会更改其文本。菜单是在我的类的构造函数中设置的,并且 QWidgetAction 是这样添加的(所有 m_ 变量都是在 header 中声明的成员变量):

m_contextMenu = new QMenu(this);
m_menuTitle = new QLabel;
m_menuTitle->setAlignment(Qt::AlignCenter);
m_menuTitle->setMargin(4);
QWidgetAction *titleAction = new QWidgetAction(m_contextMenu);
titleAction->setDefaultWidget(m_menuTitle);
m_contextMenu->addAction(titleAction);
m_contextMenu->addSeparator();

当菜单被请求时,标签的文本被改变,菜单显示如下:

m_menuTitle->setText(tr("%1 „%2“").arg(some_variable, some_other_variable));
...
m_contextMenu->exec(place_to_display);

第一次设置标签文本时(标签文本设置为短文本),一切正常:

enter image description here

但是当它设置为一些更长的文本时,大小保持不变并且文本被裁剪:

enter image description here

我试图解决这个问题,但我找到的唯一可行的解​​决方案是定义在构造函数的菜单中显示的 QAction,由 this 拥有,设置标签的文本,清除菜单并再次添加操作,如下所示:

m_contextMenu->clear();

m_menuTitle->setText(tr("%1 „%2“").arg(some_variable, some_other_variable));

m_contextMenu->addAction(m_menuTitleAction);
m_contextMenu->addSeparator();
m_contextMenu->addAction(m_editAction);
m_contextMenu->addAction(m_deleteAction);

m_contextMenu->exec(place_to_display);

有没有办法调整标题的大小而不用每次都重建菜单?

最佳答案

解决方案是改为发送调整大小事件:

m_menuTitle->setText(tr("%1 „%2“").arg(some_variable, some_other_variable));
...
QResizeEvent re(new_size, m_contextMenu->size());
qApp->sendEvent(m_contextMenu, &re);

这将设置 QMenu 的内部 itemsDirty 标志,并在显示菜单时强制重新计算几何图形。 请注意,事件中的新大小并不重要,因为菜单会根据其 sizeHint() 调整大小!

关于c++ - 如何在更改文本后调整 QWidgetAction 显示的 QLabel 的大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42122985/

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