Issue
Following the examples outlined in "Create simple GUI" I have tried to create Custom Widget, but nothing seems to by shown. It seems to be the simplest widget that I can imagine but still something is missing and I have no idea what.
from PyQt5.QtWidgets import *
import sys
class customWidget(QWidget):
def __init__(self, *args, **kwargs):
super(customWidget, self).__init__(*args, **kwargs)
layout = QHBoxLayout()
label = QLabel("Que chinga")
layout.addWidget(label)
class MainWindow(QMainWindow):
def __init__(self, *args, **kwargs):
super(MainWindow, self).__init__(*args, **kwargs)
self.setWindowTitle("Esta locura")
label = customWidget()
self.setCentralWidget(label)
app = QApplication(sys.argv)
window = MainWindow()
window.show()
app.exec_()
Solution
Do any of the following in the __init__
of customWidget
(they are the conceptually the same thing):
- add
self.setLayout(layout)
after creating the layout; - change
layout = QHBoxLayout()
tolayout = QHBoxLayout(self)
;
The reason is that you're not setting the layout for the widget, so the QLabel has no parent and won't be shown on its own.
In practice, the customWidget
instance could know anything about those objects, so there's no reason for which it should show them.
I also suggest you to:
- read about classes and instances: while it's not directly related to this issue, it has lots of aspects in common, since the parenthood relation of Qt objects (such as QWidget subclasses) is closely related to the OOP aspects of instances.
- always use capitalized names for classes (
CustomWidget
, notcustomWidget
), as lower cased names should only be used for variable and function names.
Answered By - musicamante
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.