Maigcally I can't inherit from QWidget using PyQt 4:
from PyQt4.QtGui import QApplication, QMainWindow, QWidget
class MyWidget(QWidget):
pass
if __name__ == "__main__":
app = QApplication([])
window = QMainWindow()
window.resize(200, 200)
widget1 = MyWidget(window)
widget1.resize(100, 100)
widget1.setStyleSheet("background-color:#FFFFFF")
window.show()
app.exec_()
It doesn't work. I just can't see the widget. But, using QLabel instead of QWidget works.
Thanks.
Solution
Reimplement paintEvent:
class MyWidget(QWidget):
def paintEvent(self, event):
o = QStyleOption()
o.initFrom(self)
p = QPainter(self)
self.style().drawPrimitive(QStyle.PE_Widget, o, p, self)
You are subclassing correctly. The "problem" is just that the QWidget has the same background colour as the main window (your call to setStyleSheet is not working).
As proof, run this code from a terminal:
from PyQt4.QtGui import QApplication, QMainWindow, QWidget, QLabel
class MyWidget(QWidget):
def enterEvent(self, evt):
print 'a'
if __name__ == "__main__":
app = QApplication([])
window = QMainWindow()
window.resize(200, 200)
widget1 = MyWidget(window)
widget1.resize(100, 100)
widget1.setStyleSheet("background-color:#FFFFFF")
window.show()
app.exec_()
When you move your mouse into the first 100,100 pixel square, you will see the letter 'a' being printed in the terminal