GF
Glep FingermanJan. 10, 2021, 11:52 a.m.

Сигналы и слоты в PyQt5

UI

Пример тестового интерфейса с описанием подключения слота и сигнала, но оно не срабатывает по непонятным причинам.

import sys, binascii, glob, asyncio 
from PyQt5.QtCore import QObject, pyqtSlot, QDateTime, Qt, QTimer 
from PyQt5 import QtCore, QtGui, QtWidgets 
from PyQt5.QtWidgets import (QApplication, QCheckBox, QComboBox, QDateTimeEdit,
        QDial, QDialog, QGridLayout, QGroupBox, QHBoxLayout, QLabel, QLineEdit,
        QProgressBar, QPushButton, QRadioButton, QScrollBar, QSizePolicy,
        QSlider, QSpinBox, QStyleFactory, QTableWidget, QTabWidget, QTextEdit,
        QVBoxLayout, QWidget, QMainWindow, QMessageBox) 

class Ui_MainWindow(object): 
    def setupUi(self, MainWindow): 
        MainWindow.setObjectName("MainWindow"); MainWindow.resize(400, 300);
        self.centralWidget = QtWidgets.QWidget(MainWindow); self.centralWidget.setObjectName("centralWidget");
        self.gridLayout = QtWidgets.QGridLayout(self.centralWidget); self.gridLayout.setContentsMargins(11,11,11,11);
        self.gridLayout.setSpacing(6); self.gridLayout.setObjectName("gridLayout");
        self.verticalLayout = QtWidgets.QVBoxLayout(); self.verticalLayout.setSpacing(6);
        self.verticalLayout.setObjectName("verticalLayout");
        self.pushButtonFirst = QtWidgets.QPushButton(self.centralWidget);
        self.pushButtonFirst.setObjectName("pushButtonFirst");self.verticalLayout.addWidget(self.pushButtonFirst);
        self.pushButtonSecond = QtWidgets.QPushButton(self.centralWidget);
        self.pushButtonSecond.setObjectName("pushButtonSecond");self.verticalLayout.addWidget(self.pushButtonSecond);
        self.checkBox = QtWidgets.QCheckBox(self.centralWidget);
        self.checkBox.setObjectName("checkBox"); self.verticalLayout.addWidget(self.checkBox);
        self.lineEdit = QtWidgets.QLineEdit(self.centralWidget);
        self.lineEdit.setObjectName("lineEdit"); self.verticalLayout.addWidget(self.lineEdit);
        self.gridLayout.addLayout(self.verticalLayout,0,0,1,1);MainWindow.setCentralWidget(self.centralWidget); 
        self.menuBar = QtWidgets.QMenuBar(MainWindow);self.menuBar.setGeometry(QtCore.QRect(0,0,400,21));
        self.menuBar.setObjectName("menuBar");MainWindow.setMenuBar(self.menuBar);
        self.mainToolBar = QtWidgets.QToolBar(MainWindow);self.mainToolBar.setObjectName("mainToolBar");
        MainWindow.addToolBar(QtCore.Qt.TopToolBarArea, self.mainToolBar);
        self.statusBar = QtWidgets.QStatusBar(MainWindow);self.statusBar.setObjectName("statusBar");
        MainWindow.setStatusBar(self.statusBar);self.retranslateUi(MainWindow);
        QtCore.QMetaObject.connectSlotsByName(MainWindow);

    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
        self.pushButtonFirst.setText(_translate("MainWindow", "PushButton"))
        self.pushButtonSecond.setText(_translate("MainWindow", "PushButton"))
        self.checkBox.setText(_translate("MainWindow", "CheckBox"))

class MainWindow(QtWidgets.QMainWindow, Ui_MainWindow):
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent); self.setupUi(self);
        self.pushButtonFirst.released.connect(self.pushButtonClicked)
        #self.pushButtonFirst.clicked.connect(self.pushButtonClicked) 

    @QtCore.pyqtSlot() 
    def pushButtonClicked(self):
        try:
            sender = self.sender();
            self.statusBar().showMessage(sender.text() + ' was pressed')
            msg = QMessageBox();
            msg.setIcon(QMessageBox.Information);
            msg.setText("This is a message box");
            msg.setInformativeText("This is additional information");
            msg.setWindowTitle("MessageBox demo");
            msg.setDetailedText("The details are as follows:");
            msg.setStandardButtons(QMessageBox.Ok | QMessageBox.Cancel);
            msg.exec_(); 
        except  Exception as e: 
            return str(e);

if __name__ == "__main__":
    app=QtWidgets.QApplication(sys.argv); w=MainWindow(); w.show(); sys.exit(app.exec_())

We recommend hosting TIMEWEB
We recommend hosting TIMEWEB
Stable hosting, on which the social network EVILEG is located. For projects on Django we recommend VDS hosting.

Do you like it? Share on social networks!

2
Михаиллл
  • Jan. 11, 2021, 7:36 a.m.

Попробуйте сделать всю работу с одном в одном классе. И лучше проверяйте нажатие кнопки.

    GF
    • Feb. 21, 2021, 2:03 p.m.

    Решение стало следующим: после конвертации файла Ui из QtDesigner мне никак не выгодно продолжать работать в этом же файле, т.к. я постоянно продолжаю дорабатывать интерфейс, а его поведение я описываю в другом файле, поэтому я делаю следующее описание

    # Импорт класса графического интерфейса 
    import GUISignalWriter as GUI 
    

    Затем я создаю класс, в котором описываю подключение интерфейса и создание слотов для элементов управления

    #%% Точка входа в программу 
    class MainWindow(QtWidgets.QMainWindow, GUI.Ui_MainWindow): 
        def __init__(self, parent=None): 
            # инициализация интерфейса 
            super(MainWindow, self).__init__(parent); self.setupUi(self);
    

    В таком случае я безпрепятственно постоянно могу корректировать интерфейс и безпрепятственно ориентироваться в другом классе для управления поведением новыми элементами управления.

      Comments

      Only authorized users can post comments.
      Please, Log in or Sign up
      AD

      C ++ - Test 004. Pointers, Arrays and Loops

      • Result:50points,
      • Rating points-4
      m

      C ++ - Test 004. Pointers, Arrays and Loops

      • Result:80points,
      • Rating points4
      m

      C ++ - Test 004. Pointers, Arrays and Loops

      • Result:20points,
      • Rating points-10
      Last comments
      i
      innorwallNov. 14, 2024, 7:03 a.m.
      How to make game using Qt - Lesson 3. Interaction with other objects what is priligy tablets What happens during the LASIK surgery process
      i
      innorwallNov. 14, 2024, 4:09 a.m.
      Using variables declared in CMakeLists.txt inside C ++ files where can i buy priligy online safely Tom Platz How about things like we read about in the magazines like roid rage and does that really
      i
      innorwallNov. 12, 2024, 6:12 a.m.
      Django - Tutorial 055. How to write auto populate field functionality Freckles because of several brand names retin a, atralin buy generic priligy
      i
      innorwallNov. 12, 2024, 2:23 a.m.
      QML - Tutorial 035. Using enumerations in QML without C ++ priligy cvs 24 Together with antibiotics such as amphotericin B 10, griseofulvin 11 and streptomycin 12, chloramphenicol 9 is in the World Health Organisation s List of Essential Medici…
      i
      innorwallNov. 11, 2024, 11:50 p.m.
      Qt/C++ - Lesson 052. Customization Qt Audio player in the style of AIMP It decreases stress, supports hormone balance, and regulates and increases blood flow to the reproductive organs buy priligy online safe Promising data were reported in a PDX model re…
      Now discuss on the forum
      i
      innorwallNov. 14, 2024, 8:39 a.m.
      добавить qlineseries в функции Listen intently to what Jerry says about Conditional Acceptance because that s the bargaining chip in the song and dance you will have to engage in to protect yourself and your family from AMI S…
      i
      innorwallNov. 11, 2024, 6:55 p.m.
      Всё ещё разбираюсь с кешем. priligy walgreens levitra dulcolax carbs The third ring was found to be made up of ultra relativistic electrons, which are also present in both the outer and inner rings
      9
      9AnonimOct. 25, 2024, 4:10 p.m.
      Машина тьюринга // Начальное состояние 0 0, ,<,1 // Переход в состояние 1 при пустом символе 0,0,>,0 // Остаемся в состоянии 0, двигаясь вправо при встрече 0 0,1,>…

      Follow us in social networks