[SOLVED]Where are wrong,I need operate UI widget in my.cpp



  • I had add a listwidget in mainwindow.ui,Then i want to add item in testcalss.cpp by SIGNAL/SLOT,but i failed.My code are followed,where are wrong?Any help will very appreciated.

    mainwindow.h

    #ifndef MAINWINDOW_H
    #define MAINWINDOW_H
    
    #include <QMainWindow>
    
    namespace Ui {
    class MainWindow;
    }
    
    class MainWindow : public QMainWindow
    {
        Q_OBJECT
    
    public:
        explicit MainWindow(QWidget *parent = 0);
        ~MainWindow();
    
    public slots:
        void additem(const QString& text);
        //void getadd(const QString& text);
    
    private:
        Ui::MainWindow *ui;
    };
    
    #endif // MAINWINDOW_H
    

    mainwindow.cpp

    #include "mainwindow.h"
    #include "ui_mainwindow.h"
    #include "testclass.h"
    
    MainWindow::MainWindow(QWidget *parent) :
        QMainWindow(parent),
        ui(new Ui::MainWindow)
    {
        ui->setupUi(this);
        ui->listWidget->addItem("text");
    
        testclass t;
        t.em();
    }
    
    void MainWindow::additem(const QString& text)
    {
        ui->listWidget->addItem("text");
        ui->listWidget->addItem(text);
    }
    
    MainWindow::~MainWindow()
    {
        delete ui;
    }
    
    

    testclass.h

    #ifndef TESTCLASS_H
    #define TESTCLASS_H
    
    #include <QObject>
    #include <mainwindow.h>
    
    class testclass : public QObject
    {
        Q_OBJECT
    public:
        explicit testclass(QObject *parent = 0);
        ~testclass();
    
        void em();
    
    signals:
        void add(const QString& text);
    
    public slots:
    
    private:
        //MainWindow *mainwindow;
    };
    
    #endif // TESTCLASS_H
    

    testclass.cpp

    #include "testclass.h"
    
    testclass::testclass(QObject *parent) : QObject(parent)
    {
        connect(this,SIGNAL(add(const QString&)),parent,SLOT(additem(const QString&)));
    }
    
    void testclass::em()
    {
        emit add("simulation");
    }
    
    testclass::~testclass()
    {
    
    }
    


  • Hi,

    the problem is that you create the testsclass instance t inside the MainWindow constructor and when it goes out of the scope it is destroyed (also invalidating connections).
    Also you used the parent in the connect function but you never set it.

    You could define t as member of MainWindow or, better, in the main() function.



  • @mcosta Thank you.I have many mistake in my code,like what you said.


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.