寫自己的網格佈局,像這樣:
頭
#ifndef MY_GRID_LAYOUT_H
#define MY_GRID_LAYOUT_H
#include <QGridLayout>
class my_grid_layout : public QGridLayout
{
public:
my_grid_layout(QWidget *parent, int max_column_count);
~my_grid_layout();
void add_widget(QWidget* p_widget);
private:
int m_max_column_count;
};
#endif // MY_GRID_LAYOUT_H
來源
#include "my_grid_layout.h"
my_grid_layout::my_grid_layout(QWidget *parent, int max_column_count)
: QGridLayout(parent)
{
m_max_column_count = max_column_count;
}
my_grid_layout::~my_grid_layout()
{
}
void my_grid_layout::add_widget(QWidget* p_widget)
{
int current_row = 0;
int current_column = 0;
while(itemAtPosition(current_row, current_column) != 0)
{
if(current_column == (m_max_column_count-1))
{
current_column = 0;
++current_row;
}
else
{
++current_column;
}
}
QGridLayout::addWidget(p_widget, current_row, current_column);
}
測試在主窗口
#include "test_1.h"
Test_1::Test_1(QWidget *parent, Qt::WFlags flags)
: QMainWindow(parent, flags)
{
m_grid_layout = new my_grid_layout(this,4);
m_grid_layout->add_widget(new QPushButton("Widget 0", this));
m_grid_layout->add_widget(new QPushButton("Widget 1", this));
m_grid_layout->add_widget(new QPushButton("Widget 2", this));
m_grid_layout->add_widget(new QPushButton("Widget 3", this));
m_grid_layout->add_widget(new QPushButton("Widget 4", this));
m_grid_layout->add_widget(new QPushButton("Widget 5", this));
m_grid_layout->add_widget(new QPushButton("Widget 6", this));
m_grid_layout->add_widget(new QPushButton("Widget 7", this));
m_grid_layout->add_widget(new QPushButton("Widget 8", this));
m_grid_layout->add_widget(new QPushButton("Widget 9", this));
m_grid_layout->add_widget(new QPushButton("Widget 10", this));
m_grid_layout->add_widget(new QPushButton("Widget 11", this));
m_grid_layout->add_widget(new QPushButton("Widget 12", this));
m_grid_layout->add_widget(new QPushButton("Widget 13", this));
QWidget* central_widget = new QWidget(this);
central_widget->setLayout(m_grid_layout);
setCentralWidget(central_widget);
}
Test_1::~Test_1()
{
}
結果
雖然已經有在特定位置處的項目,切換到在網格佈局中的下一個位置,這在我的示例爲4的最大列計數。我只是切換到下一列,直到我到達第四列。然後我將列重置爲0並切換到下一行。只要已經有一個項目,我會這樣做。只要那個地方沒有物品,我就把我的小部件放在那裏。
這只是一個簡單的例子,但也許它足以讓您使用。
你應該通過錯誤處理來加強它,小心無盡的循環等......
來源
2012-03-12 00:56:34
Exa