Qt之窗口的父子关系:Widget与按钮

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();
}

如果没有设置父子关系,那么这个程序就有两个主窗口,按钮窗口和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();
}

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();
}

--

评论

暂无评论