我的 Qt 程序显示空白 window 和标题

My Qt program showing blank window with title

我是 Qt 的新手,我有这段代码应该在 Qt main window 中显示滑动条和数字框。但我得到的只是主要 window 本身,里面什么也没有。我确实使用了 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();
}

编译您的代码时出现重要警告:

QWidget::setLayout: Attempting to set QLayout "" on QMainWindow "", which already has a layout

事实上,您无法为 QMainWindow 设置布局,因为它有自己的布局。来自 Documentation of 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. QMainWindow has its own layout to which you can add QToolBars, QDockWidgets, a QMenuBar, and a QStatusBar. The layout has a center area that can be occupied by any kind of widget.

您应该将小部件分配给 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:我保留了您选择的名称约定以使更改更清楚。我宁愿使用 widget 而不是 windowwindow 而不是 程序