1. 程式人生 > 其它 >Qt之視窗的父子關係:Widget與按鈕

Qt之視窗的父子關係:Widget與按鈕

技術標籤:qtguijsjavamatlab

1、新建專案-->其他專案--->Empty qmake project:只有一個pro程式

1、新建專案-->其他專案--->code snapped--->Gui application

2、修改main.cpp:在主視窗上顯示一個按鈕:也就是將按鈕的父視窗設定為widget[因為QPushButton 繼承QWidget],這樣widget就和button關聯起來了,當widget的show時候會呼叫button的show。

#include <QApplication>
#include <QWidget>
#include <QPushButton>
int main(int argc, char *argv[])
{
    QApplication app(argc, argv);

    QWidget w;

    QPushButton button;   /*按鈕是視窗*/
    button.setText("Button");
    button.setParent(&w);   //視窗物件的父子關係:設定父視窗是button
   
    w.show();
    w.setWindowTitle("Hello world");
    w.show();
    return app.exec();
}

1fb3d2510cafa614cecff99a1a9d78090b8.jpg

如果沒有設定父子關係,那麼這個程式就有兩個主視窗,按鈕視窗和widget視窗沒有關係,單獨顯示:

#include <QApplication>
#include <QWidget>
#include <QPushButton>
int main(int argc, char *argv[])
{
    QApplication app(argc, argv);

    QWidget w;

    QPushButton button;   /*按鈕是視窗*/
    button.setText("Button");
  //  button.setParent(&w);   //視窗物件的父子關係:設定父視窗是button
    button.show();  //必須
    w.show();
    w.setWindowTitle("Hello world");
    w.show();
    return app.exec();
}

5eeb032dce698c30583b787dd383a048047.jpg

3、新增訊號與槽機制

#include <QApplication>
#include <QWidget>
#include <QPushButton>
int main(int argc, char *argv[])
{
    QApplication app(argc, argv);

    QWidget w;

    QPushButton button;   /*按鈕是視窗*/
    button.setText("Button");
    button.setParent(&w);   //視窗物件的父子關係:設定父視窗是button
    //新增訊號與槽:當clicked()函式被呼叫,close()也被呼叫
    QObject::connect(&button, SIGNAL(clicked()), &w, SLOT(close()));
    w.show();
    w.setWindowTitle("Hello world");
    w.show();
    return app.exec();
}

效果是當按鈕被點選了,視窗就會退出。

4、設定button的位置

#include <QApplication>
#include <QWidget>
#include <QPushButton>
int main(int argc, char *argv[])
{
    QApplication app(argc, argv);

    QWidget w;

    QPushButton button;   /*按鈕是視窗*/
    button.setText("Button");
    button.setParent(&w);   //視窗物件的父子關係:設定父視窗是button
    button.setGeometry(30, 30, 100, 30);   //座標原點在視窗的左上角[不包括工具欄]
    //新增訊號與槽:當clicked()函式被呼叫,close()也被呼叫
    QObject::connect(&button, SIGNAL(clicked()), &w, SLOT(close()));
    w.show();
    w.setWindowTitle("Hello world");
    w.show();
    return app.exec();
}

3a081307d3e759b68a504d399fa1d820e29.jpg

--