Установка стиля при использовании QStyleFactory из списка стилей в QComboBox

Я реализовывал приложение, используя PyQt4.

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".

1 ответ

Решение

Вам не нужен глобальный список стилей, потому что он уже доступен в 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_())
Другие вопросы по тегам