我写了下面的代码:
import sys
from PyQt4 import QtCore, QtGui
class MainWindow(QtGui.QMainWindow):
def __init__(self, parent=None):
super(MainWindow, self).__init__(parent)
self.central_widget = QtGui.QStackedWidget()
self.setCentralWidget(self.central_widget)
Login_Widget = LoginPage(self)
self.central_widget.addWidget(Login_Widget)
self.central_widget.setCurrentWidget(Login_Widget)
self.setStyleSheet("background-color:#FFDA00;")
class LoginPage(QtGui.QWidget):
def __init__(self, parent=None):
super(LoginPage, self).__init__(parent)
self.Username = QtGui.QLineEdit(self)
self.Password = QtGui.QLineEdit(self)
self.Password.setEchoMode(QtGui.QLineEdit.Password)
self.buttonLogin = QtGui.QPushButton('Login', self)
self.cancelButton = QtGui.QPushButton('Cancel', self)
loginLayout = QtGui.QFormLayout()
loginLayout.addRow("Username", self.Username)
loginLayout.addRow("Password", self.Password)
horizontallayout = QtGui.QHBoxLayout()
horizontallayout.addWidget(self.buttonLogin)
horizontallayout.addWidget(self.cancelButton)
layout = QtGui.QVBoxLayout(self)
layout.addLayout(loginLayout)
layout.addLayout(horizontallayout)
self.setLayout(layout)
if __name__ == "__main__":
app = QtGui.QApplication(sys.argv)
window = MainWindow()
window.show()
app.exec_()
使用上面的代码,当我运行代码时,它将所有内容设置为橙色。我想设置背景为橙色,lineedit
白色和按钮银灰色。如何为单个widget
项设置不同的颜色?还有什么方法可以设置窗口栏的颜色(包含窗口标题,退出按钮,最小化按钮和重新调整大小按钮的栏)
任何帮助将不胜感激!
答案 0 :(得分:2)
您可以为各个小部件设置不同的样式属性。
请查看此链接Qt Style Sheets Examples,因为它涵盖了如何为大多数小部件设置不同的样式属性。
您还可以将stylesheeet保存为.qss
文件并将其保存在外部。
css = '''
QMainWindow
{
background:orange;
}
QLineEdit
{
background:white;
}
QPushButton
{
background:qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1,
stop: 0 #FAFFFA, stop: 0.4 #F5F7F5,
stop: 0.5 #F0F2F0, stop: 1.0 #EDEDED);
}
'''
class MainWindow(QtGui.QMainWindow):
def __init__(self, parent=None):
super(MainWindow, self).__init__(parent)
self.central_widget = QtGui.QStackedWidget()
self.setCentralWidget(self.central_widget)
Login_Widget = LoginPage(self)
self.central_widget.addWidget(Login_Widget)
self.central_widget.setCurrentWidget(Login_Widget)
class LoginPage(QtGui.QWidget):
def __init__(self, parent=None):
super(LoginPage, self).__init__(parent)
self.Username = QtGui.QLineEdit(self)
self.Password = QtGui.QLineEdit(self)
self.Password.setEchoMode(QtGui.QLineEdit.Password)
self.buttonLogin = QtGui.QPushButton('Login', self)
self.cancelButton = QtGui.QPushButton('Cancel', self)
loginLayout = QtGui.QFormLayout()
loginLayout.addRow("Username", self.Username)
loginLayout.addRow("Password", self.Password)
horizontallayout = QtGui.QHBoxLayout()
horizontallayout.addWidget(self.buttonLogin)
horizontallayout.addWidget(self.cancelButton)
layout = QtGui.QVBoxLayout(self)
layout.addLayout(loginLayout)
layout.addLayout(horizontallayout)
self.setLayout(layout)
if __name__ == "__main__":
app = QtGui.QApplication(sys.argv)
app.setStyleSheet(css)#<------------set your stylesheet
window = MainWindow()
window.show()
app.exec_()
对于窗口标题栏,无法设置颜色或任何属性。最好的办法是隐藏它并实现自己的窗口标题栏。