PyQt, widget do not shown
I've this hort program in Python ad Qt4
#!/usr/bin/python
# -*- coding: utf-8 -*-
import sys
from PyQt4 import QtGui
from PyQt4 import QtCore
color = QtGui.QColor(99, 0, 0)
class colorButton(QtGui.QWidget):
def __init__(self, args):
QtGui.QWidget.__init__(self,args)
self.setGeometry(150, 22, 50, 50)
self.setStyleSheet("QWidget { background-color: %s }" % color.name())
class ColorDialog(QtGui.QWidget):
def __init__(self, parent=None):
QtGui.QWidget.__init__(self, parent)
self.setGeometry(40, 40, 220, 100)
self.setWindowTitle('ColorDialog')
button=colorButton(self)
app = QtGui.QApplication(sys.argv)
cd = ColorDialog()
cd.show()
app.exec_()
The intrpreter doesn't give me any error, but the "colored" widget isn't shown. Why? thank
Your class colorButton
inherits from QWidget
, yet you are calling QPushButton.__init__()
in the constructor. Maybe you want it to inherit from QPushButton
?
By using the following class definition, your code works for me:
class colorButton(QtGui.QPushButton):
def __init__(self, *args):
QtGui.QPushButton.__init__(self, *args)
self.setGeometry(150, 22, 50, 50)
self.setStyleSheet("QWidget { background-color: %s }" % color.name())
你需要给widget一个paintEvent。
#!/usr/bin/python
# -*- coding: utf-8 -*-
import sys
from PyQt4 import QtGui
from PyQt4 import QtCore
color = QtGui.QColor(99, 0, 0)
class colorButton(QtGui.QWidget):
def __init__(self, args):
QtGui.QWidget.__init__(self,args)
self.setGeometry(150, 22, 50, 50)
def paintEvent(self, event):
painter = QtGui.QPainter(self)
painter.fillRect(event.rect(), color)
class ColorDialog(QtGui.QWidget):
def __init__(self, parent=None):
QtGui.QWidget.__init__(self, parent)
self.setGeometry(40, 40, 220, 100)
self.setWindowTitle('ColorDialog')
button=colorButton(self)
app = QtGui.QApplication(sys.argv)
cd = ColorDialog()
cd.show()
app.exec_()
Try setting autoFillBackground to True before you change the color (before setStylesheet call). AND I think you need to set the pallete. This comment assumes that you meant "the color of the widget is not shown". Please review the syntax as the one illustrated below is for Qt4.3 and I didn't check the latest one. After you set the pallet, there is no need to set the stylesheet.
class colorButton(QtGui.QWidget)
def __init__(self, args):
QtGui.QPushButton.__init__(self,args)
self.setGeometry(150, 22, 50, 50)
self.setAutoFillBackground(True)
plt = QtGui.QPalette()
plt.setColor(QtGui.QPalette.Active,QtGui.QPalette.Window,color)
plt.setColor(QtGui.QPalette.Inactive,QtGui.QPalette.Window,color)
plt.setColor(QtGui.QPalette.Disabled,QtGui.QPalette.Window,color
self.setPalette(plt)
#self.setStyleSheet("QWidget { background-color: %s }" % color.name())
链接地址: http://www.djcxy.com/p/77398.html
上一篇: 在pyqt中清除布局中的所有小部件
下一篇: PyQt,小部件没有显示