简体   繁体   English

我的Qt程序显示带有标题的空白窗口

[英]My Qt program showing blank window with title

I am new to Qt and I have this code that is supposed to display a slider bar and number box in Qt main window. 我是Qt的新手,我有这段代码应该在Qt主窗口中显示一个滑块和数字框。 But all I am getting is the main window itself and nothing in it. 但是我所得到的只是主窗口本身,里面什么也没有。 I did use show() function but nothing happend 我确实使用了show()函数,但没有任何反应

#include "mainwindow.h"
#include <QApplication>
#include <QSpinBox>
#include <QSlider>
#include <QHBoxLayout>
#include <QtGui/QApplicationStateChangeEvent>



int main(int argc, char *argv[])
{
    QApplication app(argc, argv);
    QMainWindow program ;

    program.setWindowTitle("Title of window");


    QSpinBox *spinboxx = new QSpinBox();
    QSlider *slider = new QSlider(Qt::Horizontal);
    spinboxx->setRange(1,40);
    slider->setRange(1,40);

QObject::connect(spinboxx, SIGNAL(valueChanged(int)), slider, SLOT(setValue(int)));
QObject::connect(slider, SIGNAL(valueChanged(int)), spinboxx, SLOT(setValue(int)));
QHBoxLayout *layout = new QHBoxLayout;

layout->addWidget(slider);
layout->addWidget(spinboxx);
program.setLayout(layout);
    program.show();

    return app.exec();
}

There is an important warning when compiling your code: 编译代码时有一个重要警告:

QWidget::setLayout: Attempting to set QLayout "" on QMainWindow "", which already has a layout QWidget :: setLayout:尝试在已经有布局的QMainWindow“”上设置QLayout“”

In fact, you cannot set a layout for QMainWindow , since it has its own layout. 实际上,您不能为QMainWindow设置布局,因为它具有自己的布局。 From the Documentation of Qt5 : Qt5文档中

A main window provides a framework for building an application's user interface. 主窗口提供了用于构建应用程序用户界面的框架。 Qt has QMainWindow and its related classes for main window management. Qt具有用于主窗口管理的QMainWindow及其相关类。 QMainWindow has its own layout to which you can add QToolBars, QDockWidgets, a QMenuBar, and a QStatusBar. QMainWindow有其自己的布局 ,您可以在其中添加QToolBars,QDockWidgets,QMenuBar和QStatusBar。 The layout has a center area that can be occupied by any kind of widget. 布局具有可被任何类型的小部件占据的中心区域。

You should assign a widget to the QMainWindow program instead like so: 您应该像这样将小部件分配给QMainWindow 程序

QWidget *window = new QWidget;
QSpinBox *spinboxx = new QSpinBox();
QSlider *slider = new QSlider(Qt::Horizontal);

QHBoxLayout *layout = new QHBoxLayout;
layout->addWidget(slider);
layout->addWidget(spinboxx);

window->setLayout(layout);


QMainWindow program ;
program.setWindowTitle("Title of window");
program.setCentralWidget(window);
program.show();

PS: I kept the name convention you chose to make the changes clearer. PS:我保留了您选择的名称约定,以使更改更清晰。 I would rather use widget than window and window than program 我宁愿使用小部件而不是窗口,窗口而不是程序

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM