2014-01-06 141 views
1

我一直在使用PyQt4實現一個應用程序。從QComboBox中的樣式列表中使用QStyleFactory設置樣式

screenshot2

在這個應用我想根據用戶的選擇來設置風格,我想設置的樣式,而無需再次重新啓動的對話框。

這裏是我的一塊,其影響造型區號:

import sys 
from PyQt4.QtCore import * 
from PyQt4.QtGui import * 
from PyQt4 import QtGui 

styles = ["Plastique","Cleanlooks","CDE","Motif","GTK+"] 

class AppWidget(QWidget): 
    def __init__(self,parent=None): 
     super(AppWidget,self).__init__(parent) 

     global styles # declaring global 

     # I've skipped the useless codes 

     horizontalLayout = QHBoxLayout() 
     self.styleLabel =QLabel("Set Style:") 
     self.styleComboBox = QComboBox() 
     self.styleComboBox.addItems(styles) # adding the styles list 
     horizontalLayout.addWidget(self.styleLabel) 
     horizontalLayout.addWidget(self.styleComboBox) 

     # skip more code 

     self.setLayout(layout) 

    def getStyle(self): 
     return self.styleComboBox.currentIndex() # get the current index from combobox 

     # another way i also implement is : 
     # return self.styleComboBox.currentText() 
     # after that i remove the global and directly access using this method 
     # which is of no success 

if __name__ == "__main__": 
    global styles # declaring global 
    app = QApplication(sys.argv) 
    widgetApp = AppWidget() 

    i = widgetApp.getStyle() # assign the index here 
    QtGui.QApplication.setStyle(QtGui.QStyleFactory.create(styles[i])) # setting the style 

    widgetApp.show() 
    app.exec_() 
    print i 

但我一直得到只有「Plastique在」風格。

回答

3

您不需要樣式的全局列表,因爲已經可以從QStyleFactory.keys獲得。

您需要做的是將這些鍵加載到組合框中,將組合框索引設置爲當前樣式,然後將組合框activated信號連接到處理程序,以便可以更改樣式。

像這樣的東西應該工作:

import sys 
from PyQt4 import QtCore, QtGui 

class AppWidget(QtGui.QWidget): 
    def __init__(self, parent=None): 
     super(AppWidget, self).__init__(parent) 
     horizontalLayout = QtGui.QHBoxLayout() 
     self.styleLabel = QtGui.QLabel("Set Style:") 
     self.styleComboBox = QtGui.QComboBox() 
     # add styles from QStyleFactory 
     self.styleComboBox.addItems(QtGui.QStyleFactory.keys()) 
     # find current style 
     index = self.styleComboBox.findText(
        QtGui.qApp.style().objectName(), 
        QtCore.Qt.MatchFixedString) 
     # set current style 
     self.styleComboBox.setCurrentIndex(index) 
     # set style change handler 
     self.styleComboBox.activated[str].connect(self.handleStyleChanged) 
     horizontalLayout.addWidget(self.styleLabel) 
     horizontalLayout.addWidget(self.styleComboBox) 
     self.setLayout(horizontalLayout) 

    # handler for changing style 
    def handleStyleChanged(self, style): 
     QtGui.qApp.setStyle(style) 

if __name__ == "__main__": 

    app = QtGui.QApplication(sys.argv) 
    widgetApp = AppWidget() 
    widgetApp.show() 
    sys.exit(app.exec_()) 
+0

@LucyJaa。我已經爲我添加的行添加了評論。你不需要你的例子中的任何代碼用於'global styles'和'getStyle'。我還在一些地方添加了'QtGui'(但這不會有什麼區別)。除此之外,我的代碼與您的示例相同。 – ekhumoro