Project

General

Profile

Dbo::ptr in event handler ยป wt_dbo_thread.cpp

Tibor Miseta, 04/06/2023 11:00 PM

 
/*
* wt_dbo_thread.cpp
*
* Created on: Apr 3, 2023
* Author: oldfashioned
*/

#include <Wt/WApplication.h>
#include <Wt/WTreeView.h>
#include <Wt/WContainerWidget.h>
#include <Wt/WStandardItem.h>
#include <Wt/WStandardItemModel.h>

#include <Wt/Dbo/Dbo.h>
#include <Wt/Dbo/backend/Sqlite3.h>

class
Location : public Wt::Dbo::Dbo<Location> {
public:
std::string name;

template<class Action>
void persist(Action& a)
{
Wt::Dbo::field(a, name, "name");
}

Location() {};
};

class LocationWidget : public Wt::WTreeView
{
public:
LocationWidget( Wt::Dbo::ptr<Location> &location,
std::shared_ptr<Wt::WStandardItemModel> &model);

void showPopup(const Wt::WModelIndex& item, const Wt::WMouseEvent& event);

private:
Wt::Dbo::ptr<Location> location_;
std::shared_ptr<Wt::WStandardItemModel> model_;
};

LocationWidget::
LocationWidget( Wt::Dbo::ptr<Location> &location,
std::shared_ptr<Wt::WStandardItemModel> &model)
: Wt::WTreeView(),
location_(location),
model_(model)
{
setModel(model_);

setAttributeValue // disables browser's context menu
("oncontextmenu",
"event.cancelBubble = true; event.returnValue = false; return false;");

mouseWentUp().connect(this, &LocationWidget::showPopup);

std::cout << location_->name << " in LocationWidget() works" << std::endl;
};

void
LocationWidget::
showPopup(const Wt::WModelIndex& item, const Wt::WMouseEvent& event)
{
if (event.button() == Wt::MouseButton::Right)
{
std::cout << "showPopup() is running" << std::endl;
std::cout << location_->name << " in showPopup() does not work" << std::endl;
// Results "Wt: error during event handling: using orphaned dbo ptr"
}
}


class HelloApplication : public Wt::WApplication
{
public:
HelloApplication(const Wt::WEnvironment& env)
: Wt::WApplication(env)
{
setTitle("Dbo thread");

auto sqlite3 = std::make_unique<Wt::Dbo::backend::Sqlite3>(":memory:");
Wt::Dbo::Session session;
session.setConnection(std::move(sqlite3));

session.mapClass<Location>("Location");

session.createTables();
{
Wt::Dbo::Transaction transaction(session);
auto loc = std::make_unique<Location>();
loc->name = "Location1";
session.add<Location>(std::move(loc));
}

Wt::Dbo::ptr<Location> rootLoc;
{
Wt::Dbo::Transaction transaction(session);
rootLoc = session.find<Location>().where("name=?").bind("Location1");
}
std::cout << rootLoc->name << " in HelloApplication() works" << std::endl;

auto model = std::make_shared<Wt::WStandardItemModel>();
for(int i=0; i<5; i++)
{
auto item = std::make_unique<Wt::WStandardItem>();
item->setText("Item");
model->invisibleRootItem()->appendRow(std::move(item));
}

root()->addWidget(std::make_unique<LocationWidget>(rootLoc, model));
}
};

int main(int argc, char **argv)
{

return Wt::WRun(argc, argv, [](const Wt::WEnvironment& env) {
return std::make_unique<HelloApplication>(env);
});
}


    (1-1/1)