歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux編程 >> Linux編程

Qt錯誤:Q_ASSERT failed in qt_win_display_dc()

在Qt中編程調試時有時會發生一個奇怪的錯誤,在qt_win_display_dc()函數中會發生Assert Failed,導致程序崩潰。該函數的代碼如下:

  1. Q_GUI_EXPORT HDC qt_win_display_dc()                  // get display DC   
  2. {  
  3.     Q_ASSERT(qApp && qApp->thread() == QThread::currentThread());  
  4.     if (!displayDC)  
  5.         displayDC = GetDC(0);  
  6.     return displayDC;  
  7. }   

Assert所判斷的意思是當前運行的線程不是程序的主線程,也就是Qt中認為這段程序應該在主線程中執行才可以。最後知道是在其他的線程中要調用字體顯示方面的函數,才導致這裡的異常。

也有人說可以將這句Assert注釋掉在編譯Qt的源碼來解決該問題,但是個人覺得既然源程序中這麼寫總是有原因的,簡單的去掉這個Assert可能會造成其他的未知錯誤。所以還是從程序結構上來考慮如何避免該操作。

在Qt的文檔中有這樣的一些說明,摘錄如下供參考。

In GUI applications, the main thread is also called the GUI thread because it's the only thread that is allowed to perform GUI-related operations.

Although QObject is reentrant, the GUI classes, notably QWidget and all its subclasses, are not reentrant. They can only be used from the main thread.

As mentioned, each program has one thread when it is started. This thread is called the "main thread" (also known as the "GUI thread" in Qt applications). The Qt GUI must run in this thread. All widgets and several related classes, for example QPixmap, don't work in secondary threads. A secondary thread is commonly referred to as a "worker thread" because it is used to offload processing work from the main thread.

Copyright © Linux教程網 All Rights Reserved