Qt之視窗的父子關係:Widget與按鈕
阿新 • • 發佈:2021-02-19
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();
}
--