S
S
samaelka2021-10-19 12:23:14
Qt
samaelka, 2021-10-19 12:23:14

How to call methods anywhere in the program?

There is a class that displays action logs in QListWidget
log.h

#ifndef LOG_H
#define LOG_H
#include <QtWidgets>

#include "server.h"
#include "database.h"
#include "delegates.h"
class CLog : public QWidget
{
    Q_OBJECT
signals:
    void signalADDlog(const QString&);    // Сигнал для передачи
public:
    explicit CLog(QObject *parent = nullptr);
    QListWidget *p_loglist;
public slots:
    void SlotAddLog (QString in_log);

};

#endif


log.cpp
#include "log.h"
#include "extern.h"
#include <QStringList>

CLog::CLog(QWidget *parent) : QWidget(parent)
{
    p_loglist = new QListWidget();   
    QVBoxLayout *mainLayout = new QVBoxLayout;    
    mainLayout->addWidget(p_loglist);
    setLayout(mainLayout);
     connect(this, &CLog::signalADDlog, this, &CLog::SlotAddLog);

    emit signalADDlog("Start and add fist new log events");
}
void CLog::SlotAddLog (QString in_log)
{
    p_loglist->addItem(in_log);
}


How can I use SlotAddLog in any other program class?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alexander Ananiev, 2021-10-19
@SaNNy32

Create an object of the CLog class and call its signalADDlog signal with the desired test. True, it is not clear why the signal is here, if you can use the usual method instead.

X
xandox, 2021-10-19
@xandox

There are three ways. One is inconvenient, the second is bad, the third is funny :)
Inconvenient: In the main window, create the CLog class as early as possible and pass its instance to all places that can generate logs. The inconvenience of this method lies in the fact that you need to drag the logger instance everywhere. On the good side, the signal is really not needed here, the function is enough, and it is better to make the ILog interface in order to replace the implementations later, if necessary.
Bad: Make CLog a singleton.
Kuteshny: Use the Qt logging system (qDebug, qInfo, etc.), for this you can use https://doc.qt.io/qt-5/qtglobal.html#qInstallMessa... to redirect the output

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question