Qt C++ Custom QWidget with Templates - c++

I've trying to combine a Custom QWidget which should contain some Template parameter insider, but I don't know how to do this because I'm not allowed by the Qt.
My Template Class:
template<typename T>
struct AbstractData {
QWidget* displayedItem{};
T* data;
};
Now what I'm trying to do it's to create a custom Widget like a QScrollArea (similar, not the same).
But when someone will click on one element I want to emit a signal which will contain that data structure which the user had provide.
For example:
template<typename T>
class PlaylistController : public QWidget {
Q_OBJECT
private:
QLayout *m_layout{};
std::vector<AbstractData<T> *> m_vecAbsData{};
std::vector<DelegateItem *> m_items{};
public:
explicit PlaylistController(QWidget *parent = nullptr);
protected:
void paintEvent(QPaintEvent *event) override;
void wheelEvent(QWheelEvent *event) override;
signals:
void clicked(T elem);
public slots:
void loadElements(const std::vector<AbstractData<T> *> &elements);
};
Here the m_vecAbsData consists of AbstractData which will contain the QWidget that I want to display on screen as on element (because I will have a list where you can scroll between elements). And also the T is going to be whatever data the user wants.
Is there any way in which I can obtain what I wanned? Because so far the QT is going to send me an error message:
Error: Template classes not supported by Q_OBJECT
How can I combine Templates and QWidget in such a way that I can emit a signal with a data type T which can be anything?
I know about the answer from here but I can't do that because I don't know what kind of data my user wants to use. Is there any workaround?

How can I combine Templates and QWidget in such a way that I can emit a signal with a data type T which can be anything?
You can't. The moc needs a completely defined type. There's a pretty good explanation here.
You can have template classes derive from QObjects as long as they don't use signals or slots in the template. It would looks something like this:
class SomeBase : public QObject
{
Q_OBJECT
...
signals:
void someSignal();
};
template<class T>
class SomeTemplate : SomeBase
{
// Don't use Q_OBJECT macro
// Don't use signals or slots
};

Related

How pass data with signal/slot from one QObject to another QQuickItem object in qml?

i have a class like this:
class MyClass : public QObject
{
Q_OBJECT
public:
CircularList<unsigned char> buffer_[2];
explicit MyClass(QObject *parent = 0);
signals:
void dataReady(short *buff,int len);
};
and the other one is:
class WaveItem:public QQuickItem
{
Q_OBJECT
public:
WaveItem(QQuickItem *parent = 0);
public slots:
void setSamples(short *buff,int len);
protected:
QSGNode * updatePaintNode(QSGNode *node, UpdatePaintNodeData *data);
};
i need to connect this class in qml with signal(dataReady)/slot(setSamples). how is it possible?
If you check qt docs about exposing signals it describes very well.
First, you need to register your QObject derived class to QML engine.
qmlRegisterType<Myclass>("MyclassLib", 1, 0, "Myclass");
This way, you can create Myclass objects in QML.
But if you like to create objects in C++ and use that particular object in QML then you need to use QQmlContext::setContextProperty
QQuickView view;
Myclass myClass;
view.engine()->rootContext()->setContextProperty("myclass", &myClass);
After you registered type or set your object to QML, you can now use them.
Myclass {
onDataReady: waveItem.setSamples(buff, len);
}
Alternatively, you can also use connect(),
Myclass {
id: myClass
Component.onCompleted: myClass.dataReady.connect(waveItem.setSamples);
}
Note: You might also look to Connections.

Qt: How to implement common base-class signal/slot functionality for all widgets and widget types (via a virtual base class slot)?

I would like to derive all of my widgets from a base class widget that automatically establishes a signal/slot connection between a slot for the class and a (rarely called) signal.
The slot is a virtual function, so that any widgets for which I wish to implement custom functionality can derive from the virtual slot function. In the desired scenario, all my widgets would derive from this base class with the virtual slot, so that by default all of my widget instances would be connected to the desired signal with a slot defined for the object (with default behavior from the base class).
I know that virtual slots are allowed in Qt. However, deriving from two QObject classes is not supported, so that, for example, the following code is disallowed:
class MySignaler : public QObject
{
Q_OBJECT
public:
MySignaler : QObject(null_ptr) {}
signals:
void MySignal();
}
MySignaler signaler;
class MyBaseWidget: public QObject
{
Q_OBJECT
public:
MyBaseWidget() : QObject(null_ptr)
{
connect(&signaler, SIGNAL(MySignal()), this, SLOT(MySlot()));
}
public slots:
virtual void MySlot()
{
// Default behavior here
}
}
// Not allowed!
// Cannot derive from two different QObject-derived base classes.
// How to gain functionality of both QTabWidget and the MyBaseWidget base class?
class MyTabWidget : public QTabWidget, public MyBaseWidget
{
Q_OBJECT
public slots:
void MySlot()
{
// Decide to handle the signal for custom behavior
}
}
As the sample code demonstrates, it seems impossible to gain both the benefits of (in this example) the QTabWidget, and also the automatic connection from the desired signal function to the virtual slot function.
Is there some way, in Qt, to have all my application's widget classes share common base-class slot and connect() functionality while allowing my widgets to nonetheless derive from Qt widget classes such as QTabWidget, QMainWindow, etc.?
Sometimes when inheritance is problematic, one can replace it, or a part of it, with composition.
That's the approach needed in Qt 4: instead of deriving from a QObject, derive from a non-QObject class (MyObjectShared) that carries a helper QObject that is used as a proxy to connect the signal to its slot; the helper forwards that call to the non-QObject class.
In Qt 5, it is not necessary to derive from a QObject at all: signals can be connected to arbitrary functors. The MyObjectShared class remains the same.
Should Qt 4 compatibility be generally useful in other areas of the code, one can use a generic connect function that connects signals to functors in both Qt 4 and Qt 5 (in Qt 4, it would use an implicit helper QObject).
// https://github.com/KubaO/stackoverflown/tree/master/questions/main.cpp
#include <QtCore>
#include <functional>
#include <type_traits>
class MySignaler : public QObject {
Q_OBJECT
public:
Q_SIGNAL void mySignal();
} signaler;
#if QT_VERSION < 0x050000
class MyObjectShared;
class MyObjectHelper : public QObject {
Q_OBJECT
MyObjectShared *m_object;
void (MyObjectShared::*m_slot)();
public:
MyObjectHelper(MyObjectShared *object, void (MyObjectShared::*slot)())
: m_object(object), m_slot(slot) {
QObject::connect(&signaler, SIGNAL(mySignal()), this, SLOT(slot()));
}
Q_SLOT void slot() { (m_object->*m_slot)(); }
};
#endif
class MyObjectShared {
Q_DISABLE_COPY(MyObjectShared)
#if QT_VERSION < 0x050000
MyObjectHelper helper;
public:
template <typename Derived>
MyObjectShared(Derived *derived) : helper(derived, &MyObjectShared::mySlot) {}
#else
public:
template <typename Derived, typename = typename std::enable_if<
std::is_base_of<MyObjectShared, Derived>::value>::type>
MyObjectShared(Derived *derived) {
QObject::connect(&signaler, &MySignaler::mySignal,
std::bind(&MyObjectShared::mySlot, derived));
}
#endif
bool baseSlotCalled = false;
virtual void mySlot() { baseSlotCalled = true; }
};
class MyObject : public QObject, public MyObjectShared {
Q_OBJECT
public:
MyObject(QObject *parent = nullptr) : QObject(parent), MyObjectShared(this) {}
// optional, needed only in this immediately derived class if you want the slot to be a
// real slot instrumented by Qt
#ifdef Q_MOC_RUN
void mySlot();
#endif
};
class MyDerived : public MyObject {
public:
bool derivedSlotCalled = false;
void mySlot() override { derivedSlotCalled = true; }
};
void test1() {
MyObject base;
MyDerived derived;
Q_ASSERT(!base.baseSlotCalled);
Q_ASSERT(!derived.baseSlotCalled && !derived.derivedSlotCalled);
signaler.mySignal();
Q_ASSERT(base.baseSlotCalled);
Q_ASSERT(!derived.baseSlotCalled && derived.derivedSlotCalled);
}
int main(int argc, char *argv[]) {
test1();
QCoreApplication app(argc, argv);
test1();
return 0;
}
#include "main.moc"
To share some code between two QObjects, you could have the QObject as a member of the class,an interposing non-object class that uses generic class that's parametrized only on the base type. The generic class can have slots and signals. They must be made visible to moc only in the immediately derived class - and not in any further derived ones.
Alas, you generally cannot connect any of the generic class's signals or slots in the constructor of the class, since at that point the derived class isn't constructed yet, and its metadata isn't available - from Qt's perspective, the signals and slots don't exist as such. So the Qt 4-style runtime-checked connect will fail.
The compile-time-checked connect will not even compile, because the this pointer it works on has an incorrect compile-time type, and you know nothing about the type of the derived class.
A workaround for Qt-4 style connect only is to have a doConnections method that the derived constructor has to call, where the connections are made.
Thus, let's make the generic class parametric on the base and the derived class as well - the latter is known as the Curiously Recurring Template Pattern, or CRTP for short.
Now you have access to the derived class's type, and can use a helper function to convert this to a pointer to the derived class, and use it in the Qt 5-style compile-time-checked connects.
The Qt 4-style runtime checked connect still needs to be invoked from doConnections. So,if you use Qt 5, that's not an issue. You shouldn't be using Qt 4-style connect in Qt 5 code anyway.
The slots require slightly different treatment depending on whether the class immediately derived from the generic class overrides them or not.
If a slot is virtual and has an implementation in the immediately derived class, you should expose it to moc in the normal fashion - using a slots section or the Q_SLOT macro.
If a slot doesn't have an implementation in the immediately derived class (whether virtual or not), its implementation in the generic class should be made visible to moc only, but not to the compiler - you don't wish to override it, after all. Thus the slot declarations are wrapped in #ifdef Q_MOC_RUN block that is only active when moc is reading the code. The generated code will refer to the generic implementations of the slots.
As we wish to make sure this indeed works, we'll add some booleans to track whether the slots were invoked.
// main.cpp
#include <QtWidgets>
template <class Base, class Derived> class MyGenericView : public Base {
inline Derived* dthis() { return static_cast<Derived*>(this); }
public:
bool slot1Invoked, slot2Invoked, baseSlot3Invoked;
MyGenericView(QWidget * parent = 0) : Base(parent),
slot1Invoked(false), slot2Invoked(false), baseSlot3Invoked(false)
{
QObject::connect(dthis(), &Derived::mySignal, dthis(), &Derived::mySlot2); // Qt 5 style
QObject::connect(dthis(), &Derived::mySignal, dthis(), &Derived::mySlot3);
}
void doConnections() {
Q_ASSERT(qobject_cast<Derived*>(this)); // we must be of correct type at this point
QObject::connect(this, SIGNAL(mySignal()), SLOT(mySlot1())); // Qt 4 style
}
void mySlot1() { slot1Invoked = true; }
void mySlot2() { slot2Invoked = true; }
virtual void mySlot3() { baseSlot3Invoked = true; }
void emitMySignal() {
emit dthis()->mySignal();
}
};
The generic class is very simple to use. Remember to wrap any non-virtual overridden slots in a moc-only guard!
Also recall the general rule that applies to all Qt code: if you have a slot, it should be declared to moc only once. So, if you had a class that further derives from MyTreeWidget or MyTableWidget, you don't want a Q_SLOT or slots macro in front of any necessarily virtual slot overrides. If present, it'll subtly break things. But you definitely want Q_DECL_OVERRIDE.
If you're on Qt 4, remember to call doConnections, otherwise the method is unnecessary.
The particular choice of QTreeWidget and QTableWidget is completely arbitrary, meaningless, and shouldn't be taken to mean that such use makes any sense (it likely doesn't).
class MyTreeWidget : public MyGenericView<QTreeWidget, MyTreeWidget> {
Q_OBJECT
public:
bool slot3Invoked;
MyTreeWidget(QWidget * parent = 0) : MyGenericView(parent), slot3Invoked(false) { doConnections(); }
Q_SIGNAL void mySignal();
#ifdef Q_MOC_RUN // for slots not overridden here
Q_SLOT void mySlot1();
Q_SLOT void mySlot2();
#endif
// visible to the C++ compiler since we override it
Q_SLOT void mySlot3() Q_DECL_OVERRIDE { slot3Invoked = true; }
};
class LaterTreeWidget : public MyTreeWidget {
Q_OBJECT
public:
void mySlot3() Q_DECL_OVERRIDE { } // no Q_SLOT macro - it's already a slot!
};
class MyTableWidget : public MyGenericView<QTreeWidget, MyTableWidget> {
Q_OBJECT
public:
MyTableWidget(QWidget * parent = 0) : MyGenericView(parent) { doConnections(); }
Q_SIGNAL void mySignal();
#ifdef Q_MOC_RUN
Q_SLOT void mySlot1();
Q_SLOT void mySlot2();
Q_SLOT void mySlot3(); // for MOC only since we don't override it
#endif
};
Finally, this little test case shows that it indeed works as desired.
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MyTreeWidget tree;
MyTableWidget table;
Q_ASSERT(!tree.slot1Invoked && !tree.slot2Invoked && !tree.slot3Invoked);
emit tree.mySignal();
Q_ASSERT(tree.slot1Invoked && tree.slot2Invoked && tree.slot3Invoked);
Q_ASSERT(!table.slot1Invoked && !table.slot2Invoked && !table.baseSlot3Invoked);
emit table.mySignal();
Q_ASSERT(table.slot1Invoked && table.slot2Invoked && table.baseSlot3Invoked);
return 0;
}
#include "main.moc"
This approach gives you the following:
The common code class derives from the base class, and can thus easily invoke or override the behavior of the base class. In this particular example, you can reimplement the QAbstractItemView methods etc.
There is full support for signals and slots. Even though the signals and slots are declared as such in the metadata of the derived class, you can still use them in the generic class.
In this situation you may make use of composition rather than multiple inheritance. Something like this:
class MySignaler : public QObject
{
Q_OBJECT
public:
MySignaler : QObject(NULL) {}
signals:
void MySignal();
}
MySignaler signaler;
class MyBaseWidgetContainer: public QWidget
{
Q_OBJECT
public:
MyBaseWidgetContainer() : QObject(NULL), widget(NULL)
{
connect(&signaler, SIGNAL(MySignal()), this, SLOT(MySlot()));
}
public slots:
virtual void MySlot()
{
// Default behavior here
}
private:
QWidget *widget;
}
class MyTabWidgetContainer : public MyBaseWidgetContainer
{
Q_OBJECT
public:
MyTabWidgetContainer() {
widget = new QTabWidget(this);
QLayout *layout = new QBoxLayout(this);
layout->addWidget(widget);
}
public slots:
void MySlot()
{
// Decide to handle the signal for custom behavior
}
}

How do I share code via class structure in C++?

I am writing for the Qt framework and I want to create a QWidget. QWidget exposes some interfaces such as mousePressEvent and mouseReleaseEvent. I want to extend this class to allow mouseClickEvent and mouseDoubleClickEvent. Normally, you would think to extend QWidget and implement those functions. The problem is that there are other classes (QPushButton for example) provided as part of the library which extend QWidget. Therefore, how do I get that added functionality into those classes without having to extend each one and copy the code?
class ClickHandeler : public QWidget {
virtual void mouseClickEvent();
virtual void mouseDoubleClickEvent();
int clickCount; //initialized to 0;
void mouseReleaseEvent(QEvent *event){
clickCount++;
QTimer::singleShot(500, this, SLOT(checkClick()));
}
void checkClick(){
if (clickCount == 2){
this->mouseDoubleClickEvent();
clickCount = clickCount-2;
} else {
this->mouseDoubleEvent()
clickCount--;
}
}
}
// QPushButton inherits QWidget too! Yikes!
class MyPushButton : public QPushButton, public ClickHandeler {
void mouseClickEvent(){
alert("i have been clicked");
}
void mouseDoubleClickEvent(){
alert("i have been double clicked");
}
}
I want something like MyPushButton, but I am worried that the function overriding will not work as expected.
Im sorry if this question is obvious to people, but I do not know what the terminology is. I have googled interfaces for c++ and I get abstract interfaces (which doesnt properly solve this problem). If I'm just being stupid and need to know a better term for google, let me know in the comments and Ill remove the question.
I think you just need to extend the QWidget and call the QWidget same functions.
For example:
class QWidget {
public:
void mouseClickEvent();
};
class QPushButton {
public:
void mouseClickEvent();
};
class MyWidget : public QWidget, public QPushButton {
public:
void mouseClickEvent()
{
//base::mouseClickEvent();// ambiguous
QWidget::mouseClickEvent();
QPushButton::mouseClickEvent();
/* Do your own code here */
}
};

Adding new functionality to a class

I'm studying the Qt4 library and I want to add some functionality to all the children of QWidget in my project. I need all widgets to have mousePressEvent overridden. Obviously I do not need to override it in every particular widget I use(I use many of them and I they to follow DRY rule) , instead I create a Foo class:
class Foo : public QWidget
{
Q_OBJECT
protected:
/* implementation is just a test */
virtual void mousePressEvent(QMouseEvent*) { this->move(0,0); }
};
And derive my button from it:
class FooButton : public QPushButton , public Foo
{
public:
FooButton (QWidget* parent) : QPushButton(parent) { };
};
But the event seems to be not overridden... What am I doing wrong?
Thanks in advance.
For the mousePressEvent access, try QObject::installEventFilter().
http://doc.qt.digia.com/stable/qobject.html
You are inheriting twice now from QWidget. This is problematic (see diamond problem).
Instead, drop your Foo class and move your custom mouse press event handler to your FooButton class:
class FooButton : public QPushButton
{
Q_OBJECT
protected:
/* implementation is just a test */
virtual void mousePressEvent(QMouseEvent*) { this->move(0,0); }
public:
FooButton (QWidget* parent) : QPushButton(parent) { };
};
If this doesn't suit the design of your application, then try using virtual inheritance instead. That is, change Foo to:
class Foo : public virtual QWidget
If that doesn't help, you should follow the advice of the other answers and install an event handler.
(You can read about virtual inheritance in its Wikipedia article.)
I suspect that the problem is that you're inheriting from QWidget twice, once through QPushButton and once through Foo.
From the way you phrased the question, I'm assuming that you want to do this for varying kinds of widgets, and thus don't want to have to subclass QPushButton, QLabel, QCheckBox, etc. If this is not the case then you should use Nikos's answer.
If not, your best bet is probably doing to be to use an event filter.
class MousePressFilter : public QObject {
Q_OBJECT
public:
MousePressFilter(QObject *parent) : QObject(parent) { }
protected:
bool eventFilter(QObject *watched, QEvent *event) {
QWidget *widget = dynamic_cast<QWidget*>(watched);
widget->move(0,0);
return false;
}
};
And then in your Foo class constructor:
class Foo {
Foo() {
installEventFilter( new MousePressFilter(this) );
}
};

No such signal in QT4

I have a signal and a slot that should fit together quite nicely.
class MemberVisitor: public QObject
{
Q_OBJECT
signals:
void processMember(Member* member, bool &breakLoop);
public:
void processList(QList<Member*>* list);
};
along with:
class MemberFinder: public QObject
{
Q_OBJECT
public slots:
void processMember(Member* member, bool &breakLoop);
public:
Member* member();
MemberFinder(QString memID): m_member(0), m_memID(memID) {};
private:
Member* m_member;
QString m_memID;
};
Not exactly complex, right? But I am definitely missing something, because QT keeps giving me the error: "Object::connect: No such signal MemberVisitor::processMember() in OperationsOnMembers.cpp:29"
Here's the code that should be hooking them up:
QObject::connect(visitor, SIGNAL(processMember()), finder, SLOT(processMember()));
I've also tried all the reasonable alternatives, like calling the function on finder. But I keep getting the same problem. What am I missing?
The call to connect() should be:
QObject::connect(visitor, SIGNAL(processMember(Member*, bool&)),
finder, SLOT(processMember(Member*, bool&)));
..provided that visitor and finder are pointers.
You need to include the parameter types (but not the parameter names) in the QObject::connect() call. e.g.
QObject::connect(visitor, SIGNAL(processMember(Member*, bool&)), finder, SLOT(processMember(Member*, bool&)));
That also lets you overload signals and slots, so you can emit signals with the same name but different parameters (same as overloading of a function, which is basically what a slot is).
This also lets you connect a signal to a slot that has fewer parameters. If your Member finder had a second slot as such :
class MemberFinder: public QObject
{
Q_OBJECT
public slots:
void processMember(Member* member, bool &breakLoop);
void processMember(Member* member);
public:
Member* member();
MemberFinder(QString memID): m_member(0), m_memID(memID) {};
private:
Member* m_member;
QString m_memID;
};
You could connect the same signal to the second slot as such :
QObject::connect(visitor, SIGNAL(processMember(Member*, bool&)), finder, SLOT(processMember(Member*)));