2017-04-04 27 views
0

我正在尋找一種簡單的方式將手動編碼設計鏈接到Qt中的小部件應用程序的用戶界面。我打算使用UI構建器來輕鬆調整佈局並獲得適當的間距,這在沒有UI構建器的情況下很難做到。
我要創建我打算使用QVector< QVector<QPushButton*> >按鈕的3×3格(我不知道我怎麼會在UI建設者做到這一點。)Qt:如何將手動編寫的UI與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; 
     } 

    } 
} 

任何幫助將是apprec iated。

回答

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"