内容未被添加\显示在QWidget中

时间:2017-02-07 06:15:30

标签: c++ qt qwidget

我正在尝试向QWidget添加内容,但没有任何内容显示。窗口是空白的,空的,没有我试图包含的任何内容。

mainwindow.cpp

#include "mainwindow.h"

#include <QApplication>

MainWindow::MainWindow(QWidget *parent) :
    QWidget(parent, Qt::FramelessWindowHint | Qt::WindowSystemMenuHint)
{
    mainWin = new QWidget();

    // Create the button, make "this" the parent
    m_button = new QPushButton("My Button", this);
    // set size and location of the button
    m_button->setGeometry(QRect(QPoint(100, 100), QSize(200, 50)));

    hlayout = new QHBoxLayout;
    hlayout -> addWidget(m_button);

    mainWin -> setLayout(hlayout);
}

mainwindow.h

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QHBoxLayout>

class MainWindow : public QWidget
{
    Q_OBJECT

public:
    MainWindow(QWidget *parent = 0);

private:

    QPushButton *m_button;

    QHBoxLayout *hlayout;
};

#endif

main.cpp

#include "mainwindow.h"
#include <QtPlugin>
#include <QApplication>

#include <QDesktopWidget>

Q_IMPORT_PLUGIN(BasicToolsPlugin)

int main(int argc, char *argv[])
{
    QApplication app(argc, argv);
    MainWindow window;

    QDesktopWidget dw;

    int x=dw.width()*0.7;
    int y=dw.height()*0.7;
    window.setFixedSize(x, y);

    window.show();

    return app.exec();
}

我错过了什么或做错了什么?

提前谢谢大家。

1 个答案:

答案 0 :(得分:0)

您的代码不完整。我不得不做一些修改(包括,声明)来编译它。

无论如何,要开始看东西,你必须要么替换:

mainWin = new QWidget();

mainWin = new QWidget(this);

或替换:

mainWin -> setLayout(hlayout);

this -> setLayout(hlayout);

在后一种情况下,调用是没有意义的:

m_button->setGeometry(QRect(QPoint(100, 100), QSize(200, 50)));

因为m_button的位置和大小由布局自动处理。