gpt4 book ai didi

c++ - QPushButton在第二个布局中不可单击

转载 作者:行者123 更新时间:2023-12-03 07:23:05 25 4
gpt4 key购买 nike

有人已经问过类似的问题,但是那个人正在与PyQt5和Designer一起工作,所以我找不到答案,因为我是从头开始编写的,是用C++编写的。
我是Qt的初学者,正在尝试将两个QPushButtons添加到特定布局的窗口中。
首先,我试图将它们添加到窗口中,如下图所示(这是窗口,并且textBrowser是QTextBrowser。这是按钮,已经正确初始化),它已添加到已经存在的QVBoxLayout中。
在这种情况下,按钮可以正常工作:

auto content = new QWidget(this);
auto windowLayout = new QVBoxLayout(content);
windowLayout->addWidget(textBrowser);

windowLayout->addWidget(button1, 0, Qt::AlignLeft);
windowLayout->addWidget(button2, 0, Qt::AlignRight);

setCentralWidget(content);
但是,这些按钮是垂直堆叠的。我希望它们在水平方向上彼此相邻,因此我尝试将按钮添加到QHBoxLayout中,然后将其添加到现有的QVBoxLayout中:
auto content = new QWidget(this);
auto windowLayout = new QVBoxLayout(content);
windowLayout->addWidget(textBrowser);

auto buttonLayout = new QHBoxLayout;
buttonLayout->addWidget(button1, 0, Qt::AlignRight);
buttonLayout->addWidget(button2, 0, Qt::AlignLeft);

windowLayout->addItem(buttonLayout);

setCentralWidget(content);
这些按钮显示在我希望它们出现的位置,但是不幸的是,即使它们未被禁用,它们也不再可单击。
为什么会这样?我的理论是布局可能会覆盖按钮,因此我尝试先将QHBoxLayout添加到QVBoxLayout,然后添加按钮,但没有任何更改。
任何帮助或信息,我们将不胜感激。

最佳答案

取自QLayout::addItem() documentation:

The function addItem() is not usually called in application code. Toadd a widget to a layout, use the addWidget() function; to add achild layout, use the addLayout() function provided by the relevantQLayout subclass.


因此,用 addItem()替换 addLayout()将解决您的问题。
要回答为什么 addItem()具有这种效果,您可以看一下 Qt's source code:
void QBoxLayout::addLayout(QLayout *layout, int stretch)
{
insertLayout(-1, layout, stretch);
}

void QBoxLayout::insertLayout(int index, QLayout *layout, int stretch)
{
Q_D(QBoxLayout);
if (!d->checkLayout(layout))
return;
if (!adoptLayout(layout))
return;
if (index < 0) // append
index = d->list.count();
QBoxLayoutItem *it = new QBoxLayoutItem(layout, stretch);
d->list.insert(index, it);
invalidate();
}

void QBoxLayout::addItem(QLayoutItem *item)
{
Q_D(QBoxLayout);
QBoxLayoutItem *it = new QBoxLayoutItem(item);
d->list.append(it);
invalidate();
}
addItem()相比, addLayout()调用 adoptLayout() ,它代表要添加的布局中的小部件。这样,父布局就可以控制小部件的大小并确定应定向到小部件的事件(鼠标悬停事件,鼠标按下事件等)。

关于c++ - QPushButton在第二个布局中不可单击,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64498275/

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