QT学习笔记之QT代码编写控件不显示的问题

写在前面

由于之前都是采用托控件的方式进行界面的编辑,觉得自己对于UI编程的领悟还是那么的有欠缺,所以现在自己想通过代码的形式进行界面的编辑。

问题以及解决思路

新建一个QT工程,在MainWindow的构造函数写下如下代码后,界面仍是一片空白。

QPushButton* button_1 = new QPushButton("one");
    QPushButton* button_2 = new QPushButton("two");
    QPushButton* button_3 = new QPushButton("three");

    QHBoxLayout* hLayout = new QHBoxLayout();
    //QVBoxLayout* vLayout = new QVBoxLayout();

    hLayout->addWidget(button_1);
    hLayout->addWidget(button_2);
    hLayout->addWidget(button_3);

    this->setLayout(hLayout);

控件到哪里去了?原来在QT里面,控件的显示是通过QWidget来进行显示的,QMainWindow不算是QWidget,所以这样无法显示。为了解决这个问题,就可以在代码中这么解决:

 QWidget* w = new QWidget();
    this->setCentralWidget(w);
    QPushButton* button_1 = new QPushButton("one");
    QPushButton* button_2 = new QPushButton("two");
    QPushButton* button_3 = new QPushButton("three");

    QHBoxLayout* hLayout = new QHBoxLayout();
    //QVBoxLayout* vLayout = new QVBoxLayout();

    hLayout->addWidget(button_1);
    hLayout->addWidget(button_2);
    hLayout->addWidget(button_3);

    w->setLayout(hLayout);

细心的读者看到了这两段代码的区别了吗?没错,这就是解决方案。

如果我们新建的工程是QWidget会不会也出现这个问题呢?继续探讨:

Widget::Widget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget)
{
    ui->setupUi(this);

        QPushButton* button_1 = new QPushButton("one");
        QPushButton* button_2 = new QPushButton("two");
        QPushButton* button_3 = new QPushButton("three");

        QHBoxLayout* hLayout = new QHBoxLayout();
        //QVBoxLayout* vLayout = new QVBoxLayout();

        hLayout->addWidget(button_1);
        hLayout->addWidget(button_2);
        hLayout->addWidget(button_3);

        this->setLayout(hLayout);
}

结果如下:
这里写图片描述

正如我们预期的那样,所以可以得出这么一个结论,在QT里面的所有的控件均是通过QWidget来进行显示的。

本文转自:https://www.cnblogs.com/WIT-Evan/p/7289749.html

原文地址:https://www.cnblogs.com/sggggr/p/12674670.html