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

标签 c++ qt qt5 qpushbutton qlayout

有人已经问过类似的问题,但是那个人正在与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. To add a widget to a layout, use the addWidget() function; to add a child layout, use the addLayout() function provided by the relevant QLayout 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/

相关文章:

c++ - Visual Build专业编译错误?

c++ - 在QT应用程序中制作一个透明孔

c++ - UI 中的 Qt5 小部件属性

c++ - 调整 QGLWidget 的大小以适应我拥有的每个 Sprite 大小

qt - QML 在 ListView 中显示的相机照片被破坏

c++ - 在 C++ 中,我想从一个函数返回一个对象数组并在另一个函数中使用它

c++ - 动态分配 float 组并将其设置为零

c++ - 运行时检查失败 #2 : Stack around the variable 'expression' was corrupted

visual-studio - QT构建因NMAKE : fatal error U1077: 'echo' : return code '0x1' 而失败

qt - 如何将 QML View 嵌入 native 窗口