QT構建窗體(父窗體傳為野指標)異常案例

2021-09-07 17:19:11 字數 2518 閱讀 2543

原始碼

工作中,時常會遇到各種各樣的異常場景,有些異常場景很常見,必要備錄,以防再犯。

分享本案例為:qt建立窗體時parent父窗體傳野指標引起異常。

本案例原始碼如下:

1.1 預設新建乙個qt工程(ps:本地qt版本為5.3)

(1)工程目錄結構

(2)工程pro檔案

1 qt       +=core gui

23 greaterthan(qt_major_version, 4): qt +=widgets

45 target =customcombobox78

9 sources +=main.cpp\

10mainwindow.cpp \

11customcombobox.cpp

1213 headers +=mainwindow.h \

14customcombobox.h

1516 forms += mainwindow.ui

1.2 實現自定義控制項

(1)customcombobox.h

1

#ifndef customcombobox_h

2#define customcombobox_h

34 #include 5

6class customcombobox : public

qcombobox7;

1112

#endif

//customcombobox_h

(2)customcombobox.cpp

1 #include "

customcombobox.h"2

3 customcombobox::customcombobox(qwidget *parent)

4: qcombobox(parent)

5

1.3 利用自定義控制項

(1)mainwindow.h

1

#ifndef mainwindow_h

2#define mainwindow_h

34 #include 5 #include 6 #include "

customcombobox.h"7

8namespaceui9

1213

class mainwindow : public

qmainwindow14;

2930

#endif

//mainwindow_h

(2)mainwindow.cpp

1 #include "

mainwindow.h

"2 #include "

ui_mainwindow.h"3

4 mainwindow::mainwindow(qwidget *parent)

5: qmainwindow(parent)

6 , m_pui(new

ui::mainwindow)711

12 mainwindow::~mainwindow()

1316

17void

mainwindow::init()

18

1.4 main函式

(1)main.cpp

1 #include "

mainwindow.h"4

int main(int argc, char *ar**)

5

分析

2.1 崩潰堆疊

除錯**,異常堆疊是梳理問題的關鍵:由堆疊可定位發生問題的過程(即函式)。

2.2 區域性物件

檢視區域性物件值,便於更具體的定位問題:由區域性物件值可定位發生問題的物件(即成員變數)。

2.3 原始碼剖析(ps: 本地qt版本5.3,不同的qt版本,原始碼異常位置可能不同!)

qt原始碼分析(關於qt原始碼除錯,參見隨筆《qtcreator除錯原始碼》),更具體查糾問題點:由原始碼可「知其然,更知其所以然」(即異常根本原因)

2.4 復原異常現場

結合以上所有的過程,弄清楚異常的來龍去脈。

總結切記,類中定義的指標成員變數,務必使用初始化列表規範進行強制初始化(預設置為null)。

good good study, day day up.

順序 選擇 迴圈 總結

C 子窗體重新整理父窗體

子窗體 from2 重新整理父窗體 from1 父窗體中有重新整理方法 refersh 1.所有權法 from1中 form2 f2 new form2 f2.owner this f2.show form2中 form1 f1 form1 this.owner f1.refersh 2.自身傳遞法...

窗體間傳值 ,子窗體傳給父窗體

第一種方法 將form1整個窗體作為值傳給form2 form1 button1彈出 from2,from2 numericupdown1的值改變,使form1 textbox1的值改變。form1 第一種方法 將整個窗體作為值傳給form2 private void button1 click o...

C WinForm 父窗體 子窗體 傳值

本次示例效果如下 form1為父窗體 包含textbox1 button1 form2為子窗體 包含textbox2 button2 父窗體給子窗體傳值 1.點選form1的button1 開啟form2 父窗體給子窗體傳值 可以呼叫過載子窗體的建構函式 直接傳入相關數值 public partia...