问:如何将手动编码的UI与UI构建器相关联?

时间:2017-04-04 17:54:42

标签: qt

我正在寻找一种简单的方法将手动编码设计链接到Qt中的小部件应用程序的UI。我计划使用UI构建器轻松调整布局并获得适当的间距,如果没有UI构建器,我很难做到这一点。
  我想创建一个3x3按钮网格,我计划使用QVector< QVector<QPushButton*> >(我不知道如何在UI构建器中执行此操作。)

以下是我的尝试,为什么即使我将每个按钮的父级设置为小部件,按钮也不会显示?

的main.cpp

#include "window.h"
#include <QApplication>

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

    return a.exec();
}

window.h中

#ifndef WINDOW_H
#define WINDOW_H

#include <QWidget>
#include <QPushButton>

namespace Ui {
class Window;
}

class Window : public QWidget
{
    Q_OBJECT

public:
    explicit Window(QWidget *parent = 0);
    ~Window();

private:
    Ui::Window *ui;
    static const int tiles = 50, height = 600, width = 500;
    QVector< QVector<QPushButton*> > cells;
};

#endif // WINDOW_H

window.cpp

#include "window.h"
#include "ui_window.h"

Window::Window(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Window)
{
    ui->setupUi(this);
    this->resize(width, height);

    int j = 0;
    for(auto &row : cells)
    {
        int i = 0;
        for(auto &col : row)
        {
            col = new QPushButton(this);
            col->setGeometry(i, j, tiles, tiles);
            i += tiles;
        }

        j += tiles;
    }
}

Window::~Window()
{
    delete ui;
    for(auto &row : cells)
    {
        for(auto &col : row)
        {
            delete col;
        }

    }
}

任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:2)

向量是空的,所以你迭代什么都没有。您可以利用网格布局而不是手动管理这些内容。

唉,您通过所有手动内存管理和几何管理不必要地使事情变得复杂。这是不必要的。您需要做的就是将小部件添加到您提到的布局中。即便如此,我也不知道如何将布局降级为.ui文件可以帮助您,因为布局必须为空。所以是的:你可以设置间距,但在运行代码之前你不会看到它们。所以这似乎是一个毫无意义的练习,除非你有其他的元素,你没有告诉我们(为什么你不是 - 你已经到目前为止)。

以下是尽可能简化的最小示例,但请参阅this answer and the links therein了解更多信息。

// https://github.com/KubaO/stackoverflown/tree/master/questions/button-grid-43214317
#include <QtWidgets>

namespace Ui { class Window {
public:
   // Approximate uic output
   QGridLayout *layout;
   void setupUi(QWidget * widget) {
      layout = new QGridLayout(widget);
   }
}; }

class Window : public QWidget
{
   Q_OBJECT
   Ui::Window ui;
   QPushButton * buttonAt(int row, int column) {
      auto item = ui.layout->itemAtPosition(row, column);
      return item ? qobject_cast<QPushButton*>(item->widget()) : nullptr;
   }

public:
   explicit Window(QWidget *parent = {});
};

Window::Window(QWidget *parent) : QWidget(parent) {
   ui.setupUi(this);
   for (int i = 0; i < 5; ++i)
      for (int j = 0; j < 6; ++j)
      {
         auto b = new QPushButton(QStringLiteral("%1,%2").arg(i).arg(j));
         ui.layout->addWidget(b, i, j);
      }
}

int main(int argc, char *argv[])
{
   QApplication a(argc, argv);
   Window w;
   w.show();
   return a.exec();
}
#include "main.moc"