QMainWindow和QWidget分别作为主窗体时对Layout的影响

最新写个小demo的时候,发现个问题,使用水平布局,最后所有的widget都堆在一起了,

分析得出的结论应该是layout出现错误了,

因为我使用qtcreator默认创建的是QMainWindow作为主窗体,

class MainWindow : public QMainWindow
{
    Q_OBJECT
    
public:
    explicit MainWindow(QWidget *parent = 0);
    ~MainWindow();
    
private:
    Ui::MainWindow *ui;
    
    QListWidget *m_leftList;
    QStackedWidget *m_stack;
    QLabel *label1;
    QLabel *label2;
    QLabel *label3;
};

是继承自QMainWindow的,所以在设置layout的时候需要使用下面的代码:

QWidget *w = new QWidget;
QHBoxLayout *mainLayout = new QHBoxLayout(w);
this->setCentralWidget(w);

完整代码:

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    
    QWidget *w = new QWidget;
    QHBoxLayout *mainLayout = new QHBoxLayout(w);
    this->setCentralWidget(w);
    
    m_leftList = new QListWidget(this);
    m_leftList->insertItem(0, tr("window1"));
    m_leftList->insertItem(1, tr("window2"));
    m_leftList->insertItem(2, tr("window3"));
    
    label1 = new QLabel(tr("windows1\n\t by craig"));
    label2 = new QLabel(tr("windows2\n\t by craig"));
    label3 = new QLabel(tr("windows3\n\t by craig"));
    
    m_stack = new QStackedWidget(this);
    m_stack->addWidget(label1);
    m_stack->addWidget(label2);
    m_stack->addWidget(label3);
    
    
    mainLayout->setMargin(5);
    mainLayout->setSpacing(5);
    mainLayout->addWidget(m_leftList);
    mainLayout->addWidget(m_stack, 0, Qt::AlignHCenter);
    mainLayout->setStretchFactor(m_leftList, 1);
    mainLayout->setStretchFactor(m_stack, 3);
    connect(m_leftList, SIGNAL(currentRowChanged(int)), m_stack, SLOT(setCurrentIndex(int)));
    
}

 

看来自己还是基础不扎实,需要多学习!大家可以分享自己的思路,谢谢

posted @ 2017-01-03 17:55  工控之家-Shrek  阅读(1655)  评论(0编辑  收藏  举报