PyQt4 - 小部件未显示
我用 Python 和 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_()
解释器没有给我任何错误,但没有显示“彩色”小部件。为什么? 感谢
I've made this program in Python and 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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您的类
colorButton
继承自QWidget
,但您在构造函数中调用QPushButton.__init__()
。也许您希望它继承自QPushButton
?通过使用以下类定义,您的代码对我有用:
Your class
colorButton
inherits fromQWidget
, yet you are callingQPushButton.__init__()
in the constructor. Maybe you want it to inherit fromQPushButton
?By using the following class definition, your code works for me:
您需要为小部件提供一个paintEvent。
You need to give the widget a paintEvent.
在更改颜色之前(在 setStylesheet 调用之前)尝试将 autoFillBackground 设置为 True。我认为你需要设置调色板。此评论假设您的意思是“小部件的颜色未显示”。请检查语法,因为下面所示的语法适用于 Qt4.3,我没有检查最新的语法。设置托盘后,无需设置样式表。
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.
我认为你需要给你的 ColorDialog 一个布局,
然后使用类似的东西将你的按钮添加到布局中
,否则我不确定简单地给你的按钮 ColorDialog 作为父级是否足以显示。
I think you need to give your ColorDialog a Layout using
then add your button to the layout with something like
Otherwise I am not sure if simply giving your button the ColorDialog as parent is sufficient for display.