在QMain窗口上添加QT布局的代码

Adding Layout in QT on QMain WIndow using a code

本文关键字:布局 代码 QT 添加 QMain 窗口      更新时间:2023-10-16

我需要一些帮助,我需要为我的应用程序设置布局,但我不知道如何在QmainWindow上设置布局。

下面是我的一部分window.cpp:

window::window(QWidget *parent)
    : QMainWindow(parent)
{

    createFilesTable();
    queryopen();
    exitButton = createButton("E&xit",SLOT(programout()));
    insertButton = createButton("&Add", SLOT(insert()));
    editButton = createButton("&Edit", SLOT(edit()));
    clearButton = createButton("&Clear", SLOT(clear()));
    selectButton = createButton("&Select", SLOT(select()));
    QHBoxLayout *buttonsLayout = new QHBoxLayout;
    buttonsLayout->addStretch();
    buttonsLayout->addWidget(selectButton);
    buttonsLayout->addWidget(insertButton);
    buttonsLayout->addWidget(editButton);
    buttonsLayout->addWidget(clearButton);
    buttonsLayout->addWidget(exitButton);
    txtid   = new QLineEdit;
    txtname = new QLineEdit;
    txtdesc = new QLineEdit;
    label1 = new QLabel("ID:");
    label2 = new QLabel("Name:");
    label3 = new QLabel("Description:");
    QGridLayout *mainLayout = new QGridLayout;
    mainLayout->addWidget(label1,1,0,1,1);
    mainLayout->addWidget(txtid,1,1,1,2);
    mainLayout->addWidget(label2,2,0,1,1);
    mainLayout->addWidget(txtname,2,1,1,3);
    mainLayout->addWidget(label3,3,0,1,1);
    mainLayout->addWidget(txtdesc,3,1,1,3);
    mainLayout->addLayout(buttonsLayout,4,1,1,3);
    mainLayout->addWidget(filesTable,6,0,6,5);
    setLayout(mainLayout);

    setWindowTitle("Database Connection");
    resize(450,300);
}

对于QMainWindow,您使用setCentralWidget(QWidget*),不像所有其他QWidget子类。

原因是QMainWindow已经有自己的布局,其中包括菜单栏,状态栏,dock窗口等的位置。因此,您创建另一个QWidget并将布局设置为所需的布局,然后使QWidget成为QMainWindow的中心小部件。

()这种不一致已经让我好几次…但一旦你明白了发生了什么,它就有意义了)