我对 Qt Creator 非常陌生,希望应用我从 [https://qss-stock.devsecstudio.com/documentation.php] 到我的 Python 代码。我似乎无法让它正常工作。任何帮助将不胜感激。谢谢!
# This Python file uses the following encoding: utf-8
import sys
from PySide6.QtWidgets import QApplication, QMainWindow
from PySide6 import QtCore, QtGui
# Important:
# You need to run the following command to generate the ui_form.py file
# pyside6-uic form.ui -o ui_form.py, or
# pyside2-uic form.ui -o ui_form.py
from ui_form import Ui_MainWindow
class MainWindow(QMainWindow):
def __init__(self, parent=None):
super().__init__(parent)
self.ui = Ui_MainWindow()
self.ui.setupUi(self)
if __name__ == "__main__":
app = QApplication(sys.argv)
widget = MainWindow()
widget. Show()
sys.exit(app.exec())
File = QtCore.QFile("Adaptic.qss")
qss = QtCore.QTextStream(File)
window = QtGui.QMainWindow()
window.setStyleSheet(qss.readAll())
要将 QSS(Qt 样式表)应用到 Qt Creator 中的 Python 代码,您需要在应用程序的主窗口上设置样式表。在您提供的代码中,末尾有 QSS 代码,但它的位置不正确,并且也存在一些语法问题。通过将 QSS 代码放置在
__init__
类的 MainWindow
方法中并在主窗口实例上使用 setStyleSheet 方法,您可以将 QSS 样式正确应用到您的应用程序。
我根据您的代码创建了这个示例:
在main.py中
import os
import sys
from PySide6.QtWidgets import QApplication, QMainWindow
from ui_form import Ui_form # Import the Ui_form class from ui_form module
class MainWindow(QMainWindow):
def __init__(self, parent=None):
super().__init__(parent)
self.ui = Ui_form() # Create an instance of the Ui_form class
self.ui.setupUi(self)
# Load and apply the QSS stylesheet
with open("Adaptic.qss", "r") as qss_file:
self.setStyleSheet(qss_file.read())
if __name__ == "__main__":
app = QApplication(sys.argv)
window = MainWindow()
window.show()
sys.exit(app.exec())
在 Adaptic.qss
QWidget {
background-color: lightblue;
}
form.ui