我是 QT 的新人
我創建了一個視窗,我想在這個視窗上添加一個按鈕,但該按鈕在不同的視窗中打開。
如何將此按鈕添加到默認視窗
這是我的代碼;
主視窗.cpp
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "QPushButton"
#include "QDesktopWidget"
#include <iostream>
using namespace std;
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
QPushButton* buton1 = new QPushButton("Hello");
buton1 -> setGeometry(QRect(QPoint(100,100),QSize(200,50)));
connect(buton1, &QPushButton::released, this, &MainWindow::buton_fonk);
buton1 -> show();
ui->setupUi(this);
}
void MainWindow::buton_fonk()
{
cout << "here" << endl;
}
MainWindow::~MainWindow()
{
delete ui;
}
主檔案
#include "mainwindow.h"
#include <QApplication>
#include <QDesktopWidget>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MainWindow w;
w.setWindowState(Qt::WindowMaximized);
w.showFullScreen();
return a.exec();
}
uj5u.com熱心網友回復:
您需要創建QPushButton主視窗的子視窗才能在主視窗內呈現,否則QPushButton將是一個獨立的小部件。
通常所有的 Qt Widget 都接受一個指向父 widget 的指標,QPushButton也接受一個指向父 widtet 的指標。
QPushButton(const QString &text, QWidget *parent = nullptr)
要使 QPushButton 成為 MainWindow 的子視窗,請將this其作為第二個引數添加到 QPushButotn 建構式。
QPushButton* buton1 = new QPushButton("Hello", this); // Make MainWindow as parent of QPushButton
理想情況下,您應該創建一個布局并將所有小部件添加到此布局,然后將 MainWindow 的中央小部件設定為此布局。
QVBoxLayout *mainLayout = new QVBoxLayout;
mainLayout->addWidget(button1);
// Add anyother widget to your layout
this->setCentralWidget(mainLayout);
希望這可以幫助。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/494475.html
