简体   繁体   English

如何在 QFileDialog 上设置样式表?

[英]How to set stylesheet on QFileDialog?

I'm trying to set my QFileDialog style sheet but is has not effect.我正在尝试设置我的QFileDialog样式表,但没有效果。 Here is the code:这是代码:

dial = QFileDialog()
dial.setStyleSheet(self.styleSheet())
path = dial.getOpenFileName(self, "Specify File")

Any ideas why this don't work?任何想法为什么这不起作用?

Calling setStylesheet on an instance of QFileDialog has no effect when you use the static functions .使用 静态函数时,在QFileDialog的实例上调用setStylesheet无效。 Those functions will create their own internal file-dialog, and so the stylesheet will be ignored.这些函数将创建它们自己的内部文件对话框,因此样式表将被忽略。

If you want to use your own stylesheet, you will need to use the file-dialog instance you created:如果您想使用自己的样式表,则需要使用您创建的文件对话框实例:

    dial = QFileDialog()
    dial.setStyleSheet(self.styleSheet())
    dial.setWindowTitle('Specify File')
    dial.setFileMode(QFileDialog.ExistingFile)
    if dial.exec_() == QFileDialog.Accepted:
        path = dial.selectedFiles()[0]

However, this may mean that you get Qt's built-in file-dialog, rather than your platform's native file-dialog.但是,这可能意味着您将获得 Qt 的内置文件对话框,而不是您平台的本机文件对话框。

PS: PS:

If you do get the native file-dialog and the stylesheet has no effect on it, the only work-around will be to fallback to Qt's built-in file-dialog.如果您确实获得了本机文件对话框并且样式表对其没有影响,则唯一的解决方法是回退到 Qt 的内置文件对话框。 To do that, just add this line:为此,只需添加以下行:

    dial.setOption(QFileDialog.DontUseNativeDialog)

I recommend to always set parents and use the inheritance of style sheets wherever possible.我建议始终设置父项并尽可能使用样式表的继承。 That way you can also use the static functions of QFileDialog .这样你也可以使用QFileDialog的静态函数。

I can confirm ekhumoros suspicion that the native file-dialog ignores the stylesheet.我可以确认ekhumoros 怀疑本机文件对话框忽略了样式表。 It indeed does on Windows.在 Windows 上确实如此。

Here the example using the Qt's built-in file-dialog.这里的示例使用 Qt 的内置文件对话框。

from PyQt5 import QtWidgets

def show_file_dialog():
    QtWidgets.QFileDialog.getOpenFileName(b, options=QtWidgets.QFileDialog.DontUseNativeDialog)

app = QtWidgets.QApplication([])

b = QtWidgets.QPushButton('Test')
b.setStyleSheet("QWidget { background-color: yellow }")
b.clicked.connect(show_file_dialog)
b.show()

app.exec_()

which looks like看起来像

在此处输入图片说明

Also for C++ version , the DontUseNativeDialog option works fine.同样对于 C++ 版本, DontUseNativeDialog 选项工作正常。

QString text = QFileDialog::getOpenFileName(parent,
                                                        tr("title message"),
                                                        folder_path_string,
                                                        tr("filter (*.extension)"),
                                                        nullptr,
                                                        QFileDialog::DontUseNativeDialog);

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

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