【问题标题】:Pyside setStyleSheet() and long lines?Pyside setStyleSheet() 和长线?
【发布时间】:2014-09-28 11:13:52
【问题描述】:

我还没有找到一种方法来减少这些部分的长代码行。无论我从哪一点切线到下一点,它都会断线。 有没有办法以某种方式将它们切成更短的线?

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)

【问题讨论】:

    标签: python pyside


    【解决方案1】:

    我有点困惑,因为您的示例代码行没有将字符串传递给 setStyleSheet。无论如何,您应该能够执行以下操作:

    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 的行。最后一行将整个字符串传递给 setStyleSheet()。它确实有效,但我有点担心我的方式可能是一个糟糕的方式。谢谢你的回答!
    • 我实际上是指您的第一个代码示例,其中字符串周围没有引号。但不用担心。我认为任何一种方式都很好。如果您不得不担心特殊字符等问题,有时解析文件可能会有点棘手,但这是值得的。就像您不想在每次样式表更改时都编辑代码文件一样。 :-)
    • 啊,是的,我忘了在这里添加''标记,对此感到抱歉:)
    【解决方案2】:

    对于一般较短的代码行,请参阅How can I break up this long line in 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_()
    

    尽管样式表字符串中有许多换行符和 cmets,但仍会显示一个黑色窗口。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-01-06
      • 1970-01-01
      • 2012-06-17
      • 1970-01-01
      • 1970-01-01
      • 2013-06-20
      • 1970-01-01
      相关资源
      最近更新 更多