如何在Qt小部件中保持按钮彼此靠近(水平)?

时间:2012-09-26 04:49:19

标签: qt widget qpushbutton

    QGridLayout *layout = new QGridLayout ();
    centralWidget->setLayout (layout);
    layout->addWidget (refresh, 0, 0);
    layout->addWidget (zoomIn, 1, 0);
    layout->addWidget (zoomOut, 1, 1);
    layout->addWidget (panLeft, 2, 0);
    layout->addWidget (panRight, 2, 1);
    layout->addWidget (panTop, 3, 0);
    layout->addWidget (panBottom, 3, 1);
    layout->addWidget (findInfo, 4, 0);
    layout->addWidget (textEdit, 5, 0);

    window->setCentralWidget (centralWidget);

enter image description here

1 个答案:

答案 0 :(得分:1)

我认为我们需要更多的背景。我把你的代码包装成以下完整的示例应用程序:

#include <QGridLayout>
#include <QPushButton>
#include <QTextEdit>
#include <QApplication>
#include <QMainWindow>

int main(int argc, char ** argv) {
    QApplication app( argc, argv );
    QMainWindow win;

    QWidget* centralWidget = new QWidget(&win);
    QPushButton* refresh = new QPushButton("Start R");
    QPushButton* zoomIn = new QPushButton("Zoom in");
    QPushButton* zoomOut = new QPushButton("Zoom out");
    QPushButton* panLeft = new QPushButton("Left");
    QPushButton* panRight = new QPushButton("Right");
    QPushButton* panTop = new QPushButton("Top");
    QPushButton* panBottom = new QPushButton("Bottom");
    QPushButton* findInfo = new QPushButton("Find Info");
    QTextEdit* textEdit = new QTextEdit("Vehicle Info. Will be shown here.");

///////////////////////////// Your Code
    QGridLayout *layout = new QGridLayout ();
    centralWidget->setLayout (layout);
    layout->addWidget (refresh, 0, 0);
    layout->addWidget (zoomIn, 1, 0);
    layout->addWidget (zoomOut, 1, 1);
    layout->addWidget (panLeft, 2, 0);
    layout->addWidget (panRight, 2, 1);
    layout->addWidget (panTop, 3, 0);
    layout->addWidget (panBottom, 3, 1);
    layout->addWidget (findInfo, 4, 0);
    layout->addWidget (textEdit, 5, 0);

    window->setCentralWidget (centralWidget);
///////////////////////////// End your code

    win.show();
    app.connect( &app, SIGNAL( lastWindowClosed() ), &app, SLOT( quit() ) );
    return app.exec();
}

这导致以下布局:

Screenshot

看起来您在按钮上添加了一些尺寸限制,因为它们在屏幕截图中的大小都相同(除了“开始”按钮)。