MarkZ
MarkZ

Reputation: 23

PyQt custom widget not visible

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_()

Upvotes: 2

Views: 1274

Answers (1)

musicamante
musicamante

Reputation: 48231

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() to layout = 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:

  1. 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.
  2. always use capitalized names for classes (CustomWidget, not customWidget), as lower cased names should only be used for variable and function names.

Upvotes: 1

Related Questions