【问题标题】:How to set relative path in Qt Stylesheet?如何在 Qt 样式表中设置相对路径?
【发布时间】:2021-05-28 12:22:20
【问题描述】:

我正在尝试使用样式表将图片添加到 PyQt5 中的按钮。如果我使用图片的绝对路径,它工作正常,但我需要使用相对路径。我已经尝试过pythonic方式(注释掉的部分),但它可能因为反斜杠而无法正常工作。我知道 Qt 资源,但我不明白如何使用它们。 link

import os, sys
from PyQt5.QtWidgets import *

class MainWindow(QMainWindow):

    def __init__(self, *args, **kwargs):
        super(MainWindow, self).__init__(*args, **kwargs)

        #scriptDir = os.path.dirname(os.path.realpath(__file__))
        #pngloc = (scriptDir + os.path.sep + 'resources' + os.path.sep + 'min.png')

        button1 = QPushButton("", self)
        button1.setStyleSheet('QPushButton {'
                               'background-image: url(e:/new/resources/min.png);'
                               '}')

app = QApplication(sys.argv)
window = MainWindow()
window.show()
sys.exit(app.exec_())

【问题讨论】:

    标签: python pyqt pyqt5 qtstylesheets


    【解决方案1】:

    如果您想使用相对路径,那么一个不错的选择是使用创建虚拟路径的Qt Resource System。 .qrc 的优点是它们允许应用程序不依赖本地文件,因为资源被转换为 python 代码。

    对于这种情况,可以使用以下 .qrc:

    resource.qrc

    <!DOCTYPE RCC><RCC version="1.0">
      <qresource>
        <file>resources/min.png</file>
      </qresource>
    </RCC>
    

    所以你需要使用 pyrcc5 将 .qrc 转换为 .py:

    pyrcc5 resource.qrc -o resource_rc.py
    

    python -m PyQt5.pyrcc_main resource.qrc -o resource_rc.py
    

    然后你需要将文件导入到脚本中:

    ma​​in.py

    import os, sys
    from PyQt5.QtWidgets import QApplication, QMainWindow, QPushButton
    
    import resource_rc
    
    
    class MainWindow(QMainWindow):
        def __init__(self, *args, **kwargs):
            super(MainWindow, self).__init__(*args, **kwargs)
    
            button1 = QPushButton(self)
            button1.setStyleSheet(
                """QPushButton {
                    background-image: url(:/resources/min.png);
                }"""
            )
    
    
    def main():
        app = QApplication(sys.argv)
        window = MainWindow()
        window.show()
        sys.exit(app.exec_())
    
    
    if __name__ == "__main__":
        main()
    
    ├── main.py
    ├── resource.qrc
    ├── resource_rc.py
    └── resources
        └── min.png
    

    【讨论】:

    • 谢谢。 PyQt5.pyrcc_main我一直在为此寻找几天,但在文档中没有提到它,所有内容都显示为 pyrcc5。这是唯一可行的方法,您在哪里找到的?
    猜你喜欢
    • 2012-01-15
    • 1970-01-01
    • 1970-01-01
    • 2019-05-03
    • 2011-06-06
    • 2016-05-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多