c++ - 对 setVisible(false) 的调用在 QWidget 的构造函数中不起作用

标签 c++ qt

在QWidget的构造函数中调用this->setvisible(false)时,不一定会隐藏。在这里,我写了一个最小的例子,其中 mw 会隐藏而 mw2 不会。

但是,稍后仍可以通过调用连接将 mw2 设置为隐藏。

为什么隐藏的是 mw 而不是 mw2?

我想了解为什么要添加此附加内容以及我如何解决它。我做错了什么吗?


#ifndef MAINWINDOW_H
#define MAINWINDOW_H

/*
 * ui_mainwindow.h is the default generated file for the mainwindow. I just added
 * a QVerticalLayout containing a QPushButton and a ScrollArea inside the central widget
 * (aka: verticalLayout, pushButton, scrollArea).
*/
#include "ui_mainwindow.h"


#include <QMainWindow>
#include <QTextBrowser>

class MyWidget: public QTextBrowser{
    Q_OBJECT
public:
    explicit MyWidget(QWidget *parent = nullptr)
        : QTextBrowser(parent)
    {
        this->setText("content");
        innerHide();
    }
    void innerHide(){
        this->hide();
    }
};

class MainWindow : public QMainWindow
{
    Q_OBJECT

private:
    Ui::MainWindow *ui;
    MyWidget* mw2;
public:
    explicit MainWindow(QWidget *parent = nullptr):
        QMainWindow(parent),
        ui(new Ui::MainWindow)
    {
        ui->setupUi(this);
        MyWidget* mw = new MyWidget(this); // will hide
        mw2 = new MyWidget(this); // call for innerHide but won't hide
        ui->verticalLayout->addWidget(mw);
        ui->scrollArea->setWidget(mw2);

        connect(ui->pushButton, SIGNAL(clicked()), this, SLOT(callHide())); // will hide when triggered
    }
    ~MainWindow(){
        delete ui;
    }
public slots:
    void callHide(){
        mw2->innerHide();
    }
};

#endif // MAINWINDOW_H


#include <QApplication>


int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    MainWindow w;
    w.show();

    return a.exec();
}

最佳答案

调用此行 ui->scrollArea->setWidget(mw2); 将再次设置 mw2 可见。在构造函数末尾调用 MyWidget::innerHide:

class Widget: public QWidget
{
public:
    Widget()
    {
        QScrollArea * area = new QScrollArea();
        QLabel* label = new QLabel("Should be hidden");
        QVBoxLayout* layout = new QVBoxLayout(this);
        layout->addWidget(area);

        label->hide(); // Hidden but will not work if before the next line
        area->setWidget(label); // Visible
        label->hide(); // Hidden
    }
};

int main(int argc, char *argv[])
{
    QApplication app(argc, argv);
    Widget *w = new Widget();
    w->show();
    return app.exec();
}

关于c++ - 对 setVisible(false) 的调用在 QWidget 的构造函数中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55439961/

相关文章:

java - 将可绘制对象作为字节数组发送到android的jni部分

c++ - 等待单个对象 : how to get handle from _beginthreadex

qt - Qt 5.1 中的 glGenVertexArrays 和 glBindVertexArrays 在哪里?

qt - 我可以运行具有特定主题的 Qt 应用程序吗?

c++ - Qt:每x个字符插入一个字符

c++ - OpenGL 让物体粘在相机上

c++ - 为什么类内偏特化是良构的?

c++ - GetSystemDefaultLCID 返回错误数据 C++

qt - 使用 GYP 而不是 QMake 构建 MOC 文件?

c++ - 使用 QT 和 MinGW32 在 Windows 上检查内存泄漏