Unable to pass variable value from QMainWindow to QDialog in Qt5.4 - qt5.4

I would like to pass the values of variable or in other words, i would like initialize the variables of Dialog class in MainWindow and execute Dialog window. I can successfully initialize the variables of Dialog class using constructor. But when I try to initialize the private or public variables using the defined public function in Dialog class, it doesn't work. Please see below code:
dialog.h
#ifndef DIALOG_H
#define DIALOG_H
#include <QDialog>
namespace Ui {
class Dialog;
}
class Dialog : public QDialog
{
Q_OBJECT
public:
explicit Dialog(const QString &d, QWidget *parent = 0);
~Dialog();
void setDat(const QString &k);
private:
Ui::Dialog *ui;
QString msg;
QString msg2;
};
#endif // DIALOG_H
dialog.cpp
#include "dialog.h"
#include "ui_dialog.h"
Dialog::Dialog(const QString &d, QWidget *parent) :
QDialog(parent),
ui(new Ui::Dialog)
{
ui->setupUi(this);
msg = d;
ui->label->setText(msg);
ui->label_2->setText(msg2);
}
void Dialog::setDat(const QString &k)
{
msg2 = k;
}
Dialog::~Dialog()
{
delete ui;
}
mainwindow.cpp
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "dialog.h"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::on_pushButton_clicked()
{
QString temp = "Hello....";
Dialog dg(temp);
dg.setDat(temp);
dg.exec();
}

Related

Arduino C++ classes needing each other

Here an example relating to my problem:
class classA
{
private:
int Value = 100;
public:
int get_Value()
{
return Value;
}
void set_Value(int p)
{
if (p == 0) Value = B.get_Value();
else Value = 5;
}
};
classA A = classA();
class classB
{
private:
int Value = 200;
public:
int get_Value()
{
return Value;
}
void set_Value(int p)
{
if (p == 0) Value = A.get_Value();
else Value = 5;
}
};
classB B = classB();
The problem is that class A can't access class B because it's definition is below it's own. My question is how can I define it so that class A has access to class B.
I tried to something like class classB; or class classB; classB B = classB; before classA begins.
Because I'm relatively new to programming I don't know how to solve such (probably easy) problems. Hope for some help!
This is a problem with circular dependencies. Luckily this one is pretty easy to fix: Just put the declaration and definition into separate files.
ClassA.h:
// Include guards to prevent double includes
#ifndef CLASS_A_H
#define CLASS_A_H
class classA
{
private:
int Value = 100;
public:
// Here we only declare, but not define the functions
int get_Value();
void set_Value(int p);
};
#endif // CLASS_A_H
ClassB.h:
// Include guards to prevent double includes
#ifndef CLASS_B_H
#define CLASS_B_H
class classB
{
private:
int Value = 200;
public:
// Here we only declare, but not define the functions
int get_Value();
void set_Value(int p);
};
#endif // CLASS_B_H
And now we need to actually define the functions, but in different files
ClassA.cpp:
#include "A.h"
#include "B.h"
// Use extern to tell the compiler that this declaration can be
// found in any of the other files and it will not complain as
// long as it is found somewhere
extern classB B;
int classA::get_Value()
{
return Value;
}
void classA::set_Value(int p)
{
if (p == 0) Value = B.get_Value();
else Value = 5;
}
ClassB.cpp:
#include "A.h"
#include "B.h"
// Use extern to tell the compiler that this declaration can be
// found in any of the other files and it will not complain as
// long as it is found somewhere
extern classA A;
int classB::get_Value()
{
return Value;
}
void classB::set_Value(int p)
{
if (p == 0) Value = A.get_Value();
else Value = 5;
}
Then, in your main file just include the two headers and you're good to go:
#include "A.h"
#include "B.h"
classB B = classB();
classA A = classA();
By the way, when you're on Arduino you can just create new .h and .cpp files and put them next to the .ino file and it should be found. You can even put them in folders, but then the include paths must be relative to each files, for example: #include "../include/file.h"

Robust type caster for STL-vector-like classes

I have a class that is quite similar to an STL-vector (the differences are not important for the pybind11 type caster, so I will ignore them here). I have written a type caster for this class. A minimal working example of my code is given below. An example showing the problem is included below the code.
The problem is that my caster is quite limited (because I have used py::array_t). In principle the interface does accept tuples, lists, and numpy-arrays. However, when I overload based on typename, the interface fails for inputted tuples and lists (simply the first overload is selected even though it is the incorrect type).
My question is: How can I make the type caster more robust? Is there an effective way to re-use as much as possible existing type casters for STL-vector-like classes?
C++ code (including pybind11 interface)
#include <iostream>
#include <vector>
#include <pybind11/pybind11.h>
#include <pybind11/stl.h>
#include <pybind11/numpy.h>
namespace py = pybind11;
// class definition
// ----------------
template<typename T>
class Vector
{
private:
std::vector<T> mData;
public:
Vector(){};
Vector(size_t N) { mData.resize(N); };
auto data () { return mData.data (); };
auto data () const { return mData.data (); };
auto begin() { return mData.begin(); };
auto begin() const { return mData.begin(); };
auto end () { return mData.end (); };
auto end () const { return mData.end (); };
size_t size () const { return mData.size (); };
std::vector<size_t> shape() const { return std::vector<size_t>(1, mData.size()); }
std::vector<size_t> strides() const { return std::vector<size_t>(1, sizeof(T) ); }
template<typename It> static Vector<T> Copy(It first, It last) {
Vector out(last-first);
std::copy(first, last, out.begin());
return out;
}
};
// C++ functions: overload based on type
// -------------------------------------
Vector<int> foo(const Vector<int> &A){ std::cout << "int" << std::endl; return A; }
Vector<double> foo(const Vector<double> &A){ std::cout << "double" << std::endl; return A; }
// pybind11 type caster
// --------------------
namespace pybind11 {
namespace detail {
template<typename T> struct type_caster<Vector<T>>
{
public:
PYBIND11_TYPE_CASTER(Vector<T>, _("Vector<T>"));
bool load(py::handle src, bool convert)
{
if ( !convert && !py::array_t<T>::check_(src) ) return false;
auto buf = py::array_t<T, py::array::c_style | py::array::forcecast>::ensure(src);
if ( !buf ) return false;
auto rank = buf.ndim();
if ( rank != 1 ) return false;
value = Vector<T>::Copy(buf.data(), buf.data()+buf.size());
return true;
}
static py::handle cast(const Vector<T>& src, py::return_value_policy policy, py::handle parent)
{
py::array a(std::move(src.shape()), std::move(src.strides()), src.data());
return a.release();
}
};
}} // namespace pybind11::detail
// Python interface
// ----------------
PYBIND11_MODULE(example,m)
{
m.doc() = "pybind11 example plugin";
m.def("foo", py::overload_cast<const Vector<int > &>(&foo));
m.def("foo", py::overload_cast<const Vector<double> &>(&foo));
}
Example
import numpy as np
import example
print(example.foo((1,2,3)))
print(example.foo((1.5,2.5,3.5)))
print(example.foo(np.array([1,2,3])))
print(example.foo(np.array([1.5,2.5,3.5])))
Output:
int
[1 2 3]
int
[1 2 3]
int
[1 2 3]
double
[1.5 2.5 3.5]
A very easy solution is to specialise pybind11::detail::list_caster. The type caster now becomes as easy as
namespace pybind11 {
namespace detail {
template <typename Type> struct type_caster<Vector<Type>> : list_caster<Vector<Type>, Type> { };
}} // namespace pybind11::detail
Note that this does require Vector to have the methods:
clear()
push_back(const Type &value)
reserve(size_t n) (seems optional in testing)
Complete example
#include <iostream>
#include <vector>
#include <pybind11/pybind11.h>
#include <pybind11/stl.h>
#include <pybind11/numpy.h>
namespace py = pybind11;
// class definition
// ----------------
template<typename T>
class Vector
{
private:
std::vector<T> mData;
public:
Vector(){};
Vector(size_t N) { mData.resize(N); };
auto data () { return mData.data (); };
auto data () const { return mData.data (); };
auto begin() { return mData.begin(); };
auto begin() const { return mData.begin(); };
auto end () { return mData.end (); };
auto end () const { return mData.end (); };
size_t size () const { return mData.size (); };
void push_back(const T &value) { mData.push_back(value); }
void clear() { mData.clear(); }
void reserve(size_t n) { mData.reserve(n); }
std::vector<size_t> shape() const { return std::vector<size_t>(1, mData.size()); }
std::vector<size_t> strides() const { return std::vector<size_t>(1, sizeof(T) ); }
template<typename It> static Vector<T> Copy(It first, It last) {
printf("Vector<T>::Copy %s\n", __PRETTY_FUNCTION__);
Vector out(last-first);
std::copy(first, last, out.begin());
return out;
}
};
// C++ functions: overload based on type
// -------------------------------------
Vector<int> foo(const Vector<int> &A){ std::cout << "int" << std::endl; return A; }
Vector<double> foo(const Vector<double> &A){ std::cout << "double" << std::endl; return A; }
// pybind11 type caster
// --------------------
namespace pybind11 {
namespace detail {
template <typename Type> struct type_caster<Vector<Type>> : list_caster<Vector<Type>, Type> { };
}} // namespace pybind11::detail
// Python interface
// ----------------
PYBIND11_MODULE(example,m)
{
m.doc() = "pybind11 example plugin";
m.def("foo", py::overload_cast<const Vector<double> &>(&foo));
m.def("foo", py::overload_cast<const Vector<int > &>(&foo));
}

smart pointer to manage socket file descriptor

A smart pointer clears the memory if the pointer gets out of scope. I wanted to adapt this to a file descriptor, like a socket. There you need a user defined deleter, because close() is the function to free the file descriptor (fd) resources.
I found this useful page, unfortunately, most approaches did not work for me. Below is a working solution I found up to now, which is a little nasty. Because uniqu_ptr expects a pointer I created int *fd to store the fd value, therefore, I had to close(*fd) and delete fd in my custom deleter.
(1) Is there a better way?
Options A and B, which are based on the hints provided by the mentioned web page, are much nicer but causing odd compiler errors.
(2) Does anyone know how to correctly use these alternatives?
I'm using Qt Creator 3.0.1 with CONFIG += c++11 option and gcc version 4.8.2
#include "ccommhandler.h"
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <memory>
#include <qdebug.h>
//for Option A and B
struct CloseHandleDeleter {
typedef int pointer;
void operator()(int handle) const
{
}
};
//custom deleter, working
class MyComplexDeleter
{
public:
MyComplexDeleter() {}
void operator()(int* ptr) const
{
qDebug() << "Deleting ";
close(*ptr);
delete ptr;
}
};
CCommHandler::CCommHandler()
{
//Option A doesn't work
//std::unique_ptr<int, CloseHandleDeleter> file( socket(AF_INET, SOCK_STREAM, 0) );
//Option B doesn't work
//std::unique_ptr<int, int()(int)> filePtr( socket(AF_INET, SOCK_STREAM, 0) , close);
MyComplexDeleter deleter;
int *fd = new int;
*fd = socket(AF_INET, SOCK_STREAM, 0);
std::unique_ptr<int, MyComplexDeleter> p( fd , deleter);
}
Edit:
The posted answer by Nevin is right, it solves my initial problem.
The comment of learnvst caused to rethink my problem, and I have to say I may made it much more complex than needed, because the following simple class should also solve my problem of auto-free the memory of a resource or as in my case, to close the file descriptor:
class SocketHandler
{
int _fd;
public:
SocketHandler(int FD):_fd(FD){}
~SocketHandler() { if(_fd!=-1) close(_fd); }
operator int() const { return _fd; }
};
Because fd isn't a pointer, I wouldn't try to pigeonhole it into unique_ptr. Instead, create a custom class whose interface is based on unique_ptr, as in (caution: totally untested):
class unique_fd
{
public:
constexpr unique_fd() noexcept = default;
explicit unique_fd(int fd) noexcept : fd_(fd) {}
unique_fd(unique_fd&& u) noexcept : fd_(u.fd_) { u.fd_ = -1; }
~unique_fd() { if (-1 != fd_) ::close(fd_); }
unique_fd& operator=(unique_fd&& u) noexcept { reset(u.release()); return *this; }
int get() const noexcept { return fd_; }
operator int() const noexcept { return fd_; }
int release() noexcept { int fd = fd_; fd_ = -1; return fd; }
void reset(int fd = -1) noexcept { unique_fd(fd).swap(*this); }
void swap(unique_fd& u) noexcept { std::swap(fd_, u.fd_); }
unique_fd(const unique_fd&) = delete;
unique_fd& operator=(const unique_fd&) = delete;
// in the global namespace to override ::close(int)
friend int close(unique_fd& u) noexcept { int closed = ::close(u.fd_); u.fd_ = -1; return closed; }
private:
int fd_ = -1;
};

Compile error with boost bind in std::find_if

Consider this snippet:
#include <vector>
#include <algorithm>
#include <boost/function.hpp>
#include <boost/bind.hpp>
template<typename PODType>
class SomeClass
{
public:
SomeClass() : m_pred(boost::bind(&SomeClass<PODType>::someMethodA, this, _1))
{
}
bool someMethodA(const PODType& elem)
{
return false;
}
bool someMethodB(const std::vector<PODType>& vec)
{
return (std::find_if(vec.begin(), vec.end(), m_pred(_1)) != vec.end());
}
private:
boost::function<bool(PODType)> m_pred;
};
int main(int argc, char* argv[])
{
SomeClass<int> obj;
std::vector<int> v;
obj.someMethodB(v);
return 0;
}
The compiler gives
error: no match for call to '(boost::function<bool(int)>) (boost::arg<1>&)'
note: no known conversion for argument 1 from 'boost::arg<1>' to 'int'
for the line return (std::find_if(vec.begin(), vec.end(), m_pred(_1)));
I'm trying to call someMethodA within the member predicate for the find_if calls.
Just pass m_pred, no need for m_pred(_1).

how to call a function of c++ file in .m file?

I have a header file test.h
#ifndef __visibilty_test__test__
#define __visibilty_test__test__
#include <iostream>
using namespace std;
class test{
public:
void print(string s);
};
#endif
and test.mm
#include "test.h"
using namespace std;
void test:: print(string s){
cout << s << endl;
}
now I want to call print function in my AppDelegate.m file in an iOS Application. Can anyone help me?
Thanks in advance
Rename AppDelegate.m to AppDelegate.mm.
Call the method as you would in C++:
test t;
t.print("Hello");
Your object:
#include <iostream>
using namespace std;
class test
{
public:
void print(string s)
{
cout << s << endl;
}
};
call from mm file
test *t = new test;
t->print("hello");