如何在 Qt 的主窗口中添加按钮? [英] How to add buttons to a main window in Qt?

查看:67
本文介绍了如何在 Qt 的主窗口中添加按钮?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 qt 编程的新手,所以如果你觉得这是一个菜鸟问题,请不要介意.我在主窗口中添加了一个按钮,但是当我运行代码时,该按钮没有显示.这是我的代码:

I'm new to qt programming so please don't mind if you find it a noob question. I've added a button to my main window but when I run the code the button is not displayed. Here's my code:

mainwindow.cpp

mainwindow.cpp

#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QtWidgets>

MainWindow::MainWindow(QWidget *parent)
{
QPushButton *train_button = new QPushButton(this);
train_button->setText(tr("something"));
train_button->move(600, 600);
train_button->show();
}

主窗口.h

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>

namespace Ui {
class MainWindow;
}

class MainWindow : public QMainWindow  
{  
Q_OBJECT

public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();

private:
Ui::MainWindow *ui;
};

#endif // MAINWINDOW_H


MainWindow::~MainWindow()
{
delete ui;
}

我该怎么办?

推荐答案

在主窗口中你应该使用 central widget .你有两个选择:

In main window you should use central widget . You have two choices :

设置中央小部件的按钮(不是很好的选择):

QPushButton *train_button = new QPushButton(this);
train_button->setText(tr("something"));
setCentralWidget(train_button);

添加一个小部件并将按钮添加到该小部件并为 centralWidget 设置小部件:

QWidget * wdg = new QWidget(this);
QPushButton *train_button = new QPushButton(wdg);
train_button->setText(tr("something"));
setCentralWidget(wdg);

当然你可以为你的 centralWidget 使用布局:

And surely you can use Layouts for your centralWidget:

QWidget * wdg = new QWidget(this);
QVBoxLayout *vlay = new QVBoxLayout(wdg);
QPushButton *btn1 = new QPushButton("btn1");
vlay->addWidget(btn1);
QPushButton *btn2 = new QPushButton("btn2");
vlay->addWidget(btn2);
QPushButton *btn3 = new QPushButton("btn3");
vlay->addWidget(btn3);
wdg->setLayout(vlay);
setCentralWidget(wdg);

这篇关于如何在 Qt 的主窗口中添加按钮?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆