gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 03:33:34 26 4
gpt4 key购买 nike

我是 Qt 的新手,我有这段代码应该在 Qt 主窗口中显示一个 slider 和数字框。但我得到的只是主窗口本身,里面什么也没有。我确实使用了 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 而不是 program

关于c++ - 我的 Qt 程序显示带有标题的空白窗口,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42754501/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com