'Qt - Add item from a second window to ListWidget in MainWindow
I have a QDialog where I can enter a Text and add it to a ListWidget inside the MainWindow after I clicked OK. Therefore I created a Method in the MainWindow class AddMessageToList(message) where the entered message is added to the ListWidget. I call the Method inside my ListAdder class (2nd Window). However nothing gets added to the ListWidget.
Here are the codes:
listadder.cpp
#include "listadder.h"
#include "ui_listadder.h"
#include "mainwindow.h"
#include "ui_mainwindow.h"
ListAdder::ListAdder(QWidget *parent) :
QDialog(parent),
ui(new Ui::ListAdder)
{
ui->setupUi(this);
}
ListAdder::~ListAdder()
{
delete ui;
}
void ListAdder::on_buttonBox_accepted()
{
MainWindow mw;
QString message = ui->lnText->text();
mw.AddMessageToList(message);
}
mainwindow.cpp
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "listadder.h"
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::on_pbt_Edit_clicked()
{
ListAdder lsadd;
lsadd.exec();
}
void MainWindow::AddMessageToList(QString message)
{
ui->lsItems->addItem(message);
}
Solution 1:[1]
Fixed it!
I created a QString method GetMessage() where I return the entered text. In the MainWindow I call the method and add the text to the ListWidget.
listadder.cpp:
#include "listadder.h"
#include "ui_listadder.h"
#include "mainwindow.h"
#include "ui_mainwindow.h"
ListAdder::ListAdder(QWidget *parent) :
QDialog(parent),
ui(new Ui::ListAdder)
{
ui->setupUi(this);
}
ListAdder::~ListAdder()
{
delete ui;
}
QString ListAdder::GetMessage()
{
QString message = ui->lnText->text();
return message;
}
void ListAdder::on_buttonBox_accepted()
{
}
mainwindow.cpp:
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "listadder.h"
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::on_pbt_Edit_clicked()
{
ListAdder lsadd;
lsadd.exec();
ui->lsItems->addItem(lsadd.GetMessage());
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | nowsqwhat |