Pyside setStyleSheet() 和长行?

1 投票
2 回答
2203 浏览
提问于 2025-04-18 16:06

我还没找到办法把这些长代码行分割开来。不管我从哪个地方切断代码,都会导致字符串出错。有没有什么办法可以把这些代码分成更短的行呢?

self.setStyleSheet('ApplicationWindow { background-color: rgba(10, 10, 10, 10); } ButtonDefault { background-color: rgb(255, 10, 10); color: rgb(255, 255, 255); }')

我自己的解决办法是把样式表放到一个单独的 .css 文件里,然后从那里把整个内容作为一个简单的字符串处理。这样开发起来也更舒服,但这个方法听起来合理吗?

    stylesheet_string = ''

    # Opens external stylesheet file
    with open('stylesheet.css', 'r') as stylesheet:
        for line in stylesheet:
            line.replace('\n', ' ')
            line.replace('\t', ' ')

            stylesheet_string = stylesheet_string+line

    self.setStyleSheet(stylesheet_string)

2 个回答

2

我有点困惑,因为你的示例代码没有把一个字符串传给setStyleSheet。无论如何,你应该可以这样做:

self.setStyleSheet('ApplicationWindow { background-color: rgba(10, 10, 10, 10); } '
                   'ButtonDefault { background-color: rgb(255, 10, 10); '
                       'color: rgb(255, 255, 255); }')

如果你想把.css文件放在外面存储,那你现在的做法听起来是合理的。

2

如果你想让代码行变得更短,可以看看这个链接:如何在Python中拆分长代码行?

如果你特别想处理样式表,并且希望它们从文件加载,那就直接加载它们,不用替换任何东西。这样做是有效的!

with open('path', 'r', encoding='utf-8') as file:
    style_sheet = file.read()
app.setStyleSheet(style_sheet)

下面是一个示例,展示了这样做是有效的:

from PySide import QtGui

app = QtGui.QApplication([])
window = QtGui.QMainWindow()
window.setStyleSheet('/*\n some comment */\n\nbackground-color:black;\n\r\t\n')
window.show()

app.exec_()

尽管样式表字符串中有很多换行和注释,依然会显示一个黑色窗口。

撰写回答