2016-05-02 48 views
2

我已經使用Qt Designer在PyQt4中創建了一個嚮導。在嚮導的一個頁面上,存在QTextBrowser類型的「text_Browser」對象。我正在使用函數QTextBrowser.append()根據一些處理向其添加文本。如何在PyQt嚮導中顯示頁面後連接信號。

我希望在顯示此頁面後執行追加功能,而不是將動作(信號)連接到上一頁上的下一個或任何其他按鈕。我如何去做這件事?

回答

1

您可以在QTextBrowser中重新實現showEvent

# from PySide import QtGui 
from PyQt4 import QtGui 

class CustomTextBrowser(QtGui.QTextBrowser): 
    '''Reimplment show event to append text''' 

    def showEvent(self, event): 
     # do stuff here 
     #self.append('This random text string ') 
     event.accept() 

請予以警告,這將小部件顯示每次追加到QTextBrowser的字符串,這意味着切換此控件的可見性可能會導致意外行爲的其他的Qt事件。由於這個原因,使用信號和插槽是可取的,但由於您明確使用而不是來使用信號/插槽,因此這裏是showEvent上的QEvent版本,並帶有公正的警告。

一種解決方案,以避免附加文字多次是設置一個實例變量,和切換值小窗口已經顯示後:

# from PySide import QtGui 
from PyQt4 import QtGui 

class CustomTextBrowser(QtGui.QTextBrowser): 
    '''Reimplment show event to append text''' 

    def __init__(self, *args, **kwds): 
     super(CustomTextBrowser, self).__init__(*args, **kwds) 

     self._loaded = False 

    def showEvent(self, event): 
     if not self._loaded: 
      # do stuff here 
      #self.append('This random text string ') 
      self._loaded = True 
     event.accept() 

另一種解決方案將是使用信號/槽策略爲或者覆蓋__init__以自動在您的子類中附加文本。信號/插槽機制可能是Qt程序員最直觀,最合理的。