I’m working on a PyQt6 application and I’ve encountered an issue where clicking a button does not trigger the connected method. I’ve broken down my project into three main files: the main window, the buttons layout, and an example.
MainWindow.py
import sys
from PyQt6.QtWidgets import QMainWindow, QApplication, QWidget, QGridLayout
from .right_buttons.right_buttons import RightButtons
class MainWindow(QMainWindow):
def __init__(self):
super().__init__(parent=None)
self.setWindowTitle("Vocanki")
self.mainWidget = QWidget(self) # Central widget
self.setCentralWidget(self.mainWidget)
central_grid_layout = QGridLayout(self.mainWidget)
right_buttons = RightButtons(central_grid_layout, vocabulary_manager)
central_grid_layout.addLayout(right_buttons.right_vertical_layout, 0, 1)
if __name__ == "__main__":
app = QApplication(sys.argv)
main_window = MainWindow()
main_window.show()
sys.exit(app.exec())
right_buttons.py
from PyQt6.QtWidgets import QVBoxLayout, QPushButton
from .one_kanji_button import OneKanjiButton
class RightButtons:
def __init__(self, central_grid_layout, vocabulary_manager):
self.right_vertical_layout = QVBoxLayout()
self.one_kanji_button = OneKanjiButton(vocabulary_manager)
self.right_vertical_layout.addLayout(self.one_kanji_button.layout)
self.right_vertical_layout.addWidget(QPushButton("Top"))
self.right_vertical_layout.addWidget(QPushButton("Top"))
one_kanji_button.py
from PyQt6.QtWidgets import QWidget, QHBoxLayout, QFormLayout, QLineEdit, QPushButton
class OneKanjiButton(QWidget):
def confirm(self):
print(self.kanji_line_edit.text())
def __init__(self, vocabulary_manager):
super().__init__()
self.vocabulary_manager = vocabulary_manager
self.layout = QHBoxLayout()
self.formLayout = QFormLayout()
self.kanji_line_edit = QLineEdit()
self.formLayout.addRow("Enter Kanji:", self.kanji_line_edit)
self.enter_button = QPushButton("Confirm")
self.enter_button.clicked.connect(self.confirm)
self.layout.addLayout(self.formLayout)
self.layout.addWidget(self.enter_button)
I instantiate the “enter_button” as a QPushButton and connect the signal to the “confirm” method. However, when pressing this button, nothing happens.
When I instantiate this button in the “MainWindow” class, it works.
Any insights?
Yanis Julien is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.