简体   繁体   English

如何在 Qt 样式表中设置相对路径?

[英]How to set relative path in Qt Stylesheet?

I'm trying to add a picture to a button in PyQt5 using stylesheet.我正在尝试使用样式表将图片添加到 PyQt5 中的按钮。 It is working fine if I use an absolute path to the picture, but I need to use a relative path instead.如果我使用图片的绝对路径,它工作正常,但我需要使用相对路径。 I've tried the pythonic way (the commented out part), but it is not working probably because of the backslashes.我已经尝试过pythonic方式(注释掉的部分),但它可能因为反斜杠而无法正常工作。 I know about Qt resources but I don't understand how to use them.我知道 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_())

If you want to use relative paths then a good option is to use the Qt Resource System which creates virtual paths.如果您想使用相对路径,那么一个不错的选择是使用创建虚拟路径的Qt 资源系统 The advantage of.qrc is that they allow the application not to depend on local files since the resources are converted to python code. .qrc 的优点是它们允许应用程序不依赖本地文件,因为资源被转换为 python 代码。

For this case the following.qrc can be used:对于这种情况,可以使用以下.qrc:

resource.qrc资源.qrc

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

So you need to convert the.qrc to.py using pyrcc5:所以你需要使用 pyrcc5 将 .qrc 转换为 .py:

pyrcc5 resource.qrc -o resource_rc.py

or或者

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

Then you need to import the file into the script:然后你需要将文件导入到脚本中:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM