Derive UIC generated Qt UI class from custom interface - qt

I've a simple Qt Question. I want that automatically generated UIC files are derived from a custom interface class like in:
Intention
class MyUiInterface {
public:
virtual void setupUi(QWidget* w) = 0;
virtual void retranslateUi(QWidget*w) = 0;
};
Generated UIC file should look like:
class Ui_MyWidget {
public:
void setupUi(QWidget* w) {
...
}
void retranslateUi(QWidget* w) {
...
}
};
namespace Ui {
class MyWidget : public MyUiInterface , public Ui_MyWidget {};
}
Why?
Every Ui::Class would then implement MyUiInterface. In each class that derives from Ui::Class (see The Multiple Inheritance Approach) I would be able to call setupUi and retranslateUi which makes sense if the class that derives from UI::Class class is a base class either. I want every widget to be derived from my abstrcat base class MyWidgetBase. Consider following:
class MyWidgetBase abstract : public QWidget, protected MyUiInterface {
protected:
void changeEvent(QEvent *e) {
QWidget::changeEvent(e);
if (e->type() == QEvent::LanguageChange) {
retranslateUi(this); // Still abstract here
}
}
};
class MyWidget : public MyWidgetBase : public Ui::MyWidget {
};
The effect is, every time MyWidget::changeEvent() is callled, retranslateUi of that specific class is called. Otherwise changeEvent had to be reimplemented in each class. This would be a bit against "code reuse" concept.
I think Qt UIC is not able to handle this situation isn't it? Is there a similar way to solve this problem?

Unfortunately, reading XML Schema for ui files is telling us that this is not possible to automate using uic compiler.
However, it is unclear to me why you would want to implement that automatically - even if the Uic somehow manages to implement your interface, you will still need to add bodies of the functions by hand, editing generated .h file, as I am sure that there is no way to include custom code in xml file which will translate as C++ code.
Why you just don't reimplement setupUi and retranslateUi in your MyWidget class? Every Ui class will have one of these classes, so you can implement this on this level, instead of base class. It is possible that I am missing something, but I see this as an appropriate way to do this.
class MyWidget : public MyWidgetBase, public Ui::MyWidget {
public:
void setupUi(QWidget* w) {
...
}
void retranslateUi(QWidget* w) {
...
}
};
With this approach, you don't need to reimplement changeEvent() in any of your custom widgets, and changeEvent will still call the appropriate retranslateUi().

Related

QObject connect fails in Qt

everyone!
I am having a problem using QObject::connect with some custom classes I've created. First of all, I have created 2 classes that inherit from QObject, they are called: Valve and PushButton. They are instantiated inside controllers called PanelController and SynopticController, which are also QObjects. And these controllers are instantiated inside another class called MasterController, also a QObject. I find this information useful since I think it is a problem of referencing the classes or the way I might be instantiating my classes inside these controllers. I strongly think this, because in my main method, when I do the following snippet of code, the connection works:
...
avionics::synoptic::Valve valveTest(nullptr, avionics::synoptic::ValveName::ABV);
avionics::panel::PushButton pushButtonTest(nullptr, avionics::panel::PanelNames::RECIRC);
QObject::connect(&pushButtonTest, &avionics::panel::PushButton::onStateColorChanged, &valveTest, &avionics::synoptic::Valve::updateState);
...
Basically, the controller classes are:
// MasterController
class MasterController : public QObject {
...
private:
panel::PanelController* panelController{nullptr};
synoptic::SynopticController* synopticController{nullptr};
}
// Panel Controller
class PanelController : public QObject {
...
explicit PanelController(QObject *parent = nulptr){
this->pushButtons.append(new avionics::panel::PushButton(_panelController, avionics::panel::PanelNames::RECIRC));
}
private:
QList<avionics::panel::PushButton*> pushButtons{};
}
// SynopticController
class SynopticController : public QObject {
private:
QList<avionics::synoptic::Valve*> iceValves{};
explicit SynopticController(QObject *parent = nullptr) {
antiIcePneumaticLines.append(new avionics::synoptic::PneumaticLine(_synopticController, avionics::synoptic::PneumaticLineName::APU_2_ABV));
}
}
My problem is that when I do the same call for the QObject::connect either from my MasterController constructor or my main method, the signal doesn't call the slot function. I want to connect pushButtons to valves, and to do this I am using getters from my controllers. The call to QObject::connect that doesn't work is:
QObject::connect(panelController->getpushButtons().at(1), &avionics::panel::PushButton::onStateColorChanged, synopticController->getValves().at(1), &avionics::synoptic::Valve::updateState);
// Example of getter
QList<avionics::panel::PushButton*> PanelController::getPushButtons(){
return pushButtons;
}
I've put some prints inside the method that emits the signal and tried debugging it, but the signal is emitted and the slot isn't called. The classes return from the getters are not undefined or null, I've checked it. Let me know if something wasn't clear. Thanks in advance!

How to use protected function setLocalPort?

I should use setlocalport for my socket connection but the property is protected and i have an error of compilation.
This is in qt application.
m_pSocket = new QTcpSocket();
m_pSocket->setLocalPort(m_iLocalPort);
error: ‘void QAbstractSocket::setLocalPort(quint16)’ is protected
If you want to use protected member like a public one, then you should provide a custom class that is the child of the class whose protected method you intend to use. There is nothing that would forbid you to create a child class inheriting QTcpSocket, and then using the protected method you want. Example for the QTcpSocket case that has been described here can be the following.
// Let us define CustomTcpSocket, i.e. the class inheriting QTcpSocket
#pragma once
#include <QTcpSocket>
class CustomTcpSocket
: public QTcpSocket
{
Q_OBJECT
public:
CustomTcpSocket(QObject* parent = nullptr);
virtual ~CustomTcpSocket();
// This method will be used to call QTcpSocket::setLocalPort which is protected.
void SetLocalPort(quint16 port);
};
Then, we provide the implementation itself.
#include "CustomTcpSocket.h"
CustomTcpSocket::CustomTcpSocket(QObject* parent)
: QTcpSocket(parent)
{
}
CustomTcpSocket::~CustomTcpSocket()
{
}
void CustomTcpSocket::SetLocalPort(quint16 port)
{
// Since method is protected, and scope is the child one, we can easily call this method here.
QAbstractSocket::setLocalPort(port);
}
Now we can easily use this newly created class in the following way.
auto customTcpSocketInstance = new CustomTcpSocket();
customTcpSocketInstance->SetLocalPort(123456);
Through usage of polymorphism, instances of CustomTcpSocket should be accepted by other Qt's APIs. However, there is no guarantee it will work as you would expect it to. Qt developers wanted this method to be protected for some of the reasons. So, use it with caution.

Calling qmlRegisterType() in the registered class on debug crashes application

I want to use qmlRegiterType() in registered class itself. I tried to use method from this topic but whenever I try to run application in debug mode it crashes the application with error
read access violation at 0x0
Crashes on macro QML_GETTYPENAMES inside qqml.h (235 line).
TestClass.h:
class RegisterQmlTest : public QObject
{
Q_OBJECT
public:
explicit RegisterQmlTest(QObject *parent = 0);
};
TestClass.cpp:
QML_REGISTER(RegisterQmlTest);
RegisterQmlTest::RegisterQmlTest(QObject *parent) : QObject(parent)
{ }
void RegisterQmlTest::foo()
{
qDebug() << "Foo test";
}
I tried to compile application on MSVC2013x64 on Qt 5.6.2, on Windows.
You are not the only one that it is happening to : https://github.com/benlau/quickflux/issues/7, and I believe it is likely due to the
static initialization order fiasco.
One solution could be to use Q_COREAPP_STARTUP_FUNCTION to ensure the call to qmlRegisterType is not done too early.
You can use this macro in a .cpp file like so :
static void registerMyQmlTypes() {
qmlRegisterType<MyType>("MyImortUri", 1, 0, "MyType");
}
Q_COREAPP_STARTUP_FUNCTION(registerMyQmlTypes)
I had the exact same issue. The problem is that the staticMetaObject associated to your class is not initialized at the moment the macro invokes the call to qmlRegisterType. As already stated in this answer (from the same topic), you're more flexible without macros. I solved this by introducing one static type per custom class.
appQmlRegister.hpp
#include <functional>
#include <QtQml>
#include <QList>
namespace app {
namespace Qml {
namespace Register {
auto Init() -> void;
static auto GetList()->QList<std::function<void(void)>>&;
template <class T>
struct Type {
Type() {
auto initializer = []() {
qmlRegisterType<T>();
};
GetList().append(initializer);
}
};
}
}
}
appQmlRegister.cpp
#include "appQmlRegister.hpp"
namespace app {
namespace Qml {
namespace Register {
auto Init() -> void {
for (auto registerFunc : GetList()) {
registerFunc();
}
}
auto GetList()->QList<std::function<void(void)>>& {
static QList<std::function<void(void)>> List;
return List;
}
}
}
}
The type app::Qml::Register::Type takes a template argument (the type of your custom class) and wraps the call to qmlRegisterType in a lambda. And that's the basic concept. Instead of an immediate call you now have full control of when to register all your custom types via app::Qml::Register::Init(). By calling that function at runtime but before starting the QML engine you can ensure that the staticMetaObjects are initialized properly and you're safe to register them.
This requires a bit of typing on a per-custom-class level though. You'd have to declare a static member in the header of the class you want to register in QML:
MyCustomClass.hpp
#include "appQmlRegister.hpp"
namespace app {
class MyCustomClass : public QObject {
Q_OBJECT
private:
static Qml::Register::Type<MyCustomClass> Register;
// stuff...
}
}
and then define it in the .cpp file like this:
MyCustomClass.cpp
#include "MyCustomClass.hpp"
namespace app {
Qml::Register::Type<MyCustomClass> MyCustomClass::Register;
}
This can of course be extended to support other sorts of type registration like registering uncreatable types, custom versions/names etc. I implemented this in a QML showcase/template project on GitHub
Hope this helps!

QT permission member between classes

I would like to send a member parentWidget, definited in a class function, to another class by a connection because I want to to add it in a list.
Unfornately I have got a error with this member permissions.
The respond error is:
C2248: 'QGraphicsWidget::QGraphicsWidget': cannot access private member declared in class 'QGraphicsWidget'
So here is my function
void DiagramScene::insertWidget(DiagramItem::DiagramType diagramtype)
{
QGraphicsWidget parentWidget;
//some code
connect(this,SIGNAL(sendToItemList(QGraphicsWidget)),diagramitem,SLOT(addToItemList(QGraphicsWidget)));
emit this->sendToItemList(parentWidget);
}
and this is my slot:
void DiagramItem::addToItemList(QGraphicsWidget widget)
{
QGraphicsWidget * newWidget;
memmove(newWidget,&widget,sizeof(QGraphicsWidget));
items.append(newWidget);
}
QGraphicsWidget inherits QObject, so it is uncopyable. The addToItemList function receives its argument by value, which leads to a copy attempt. One possible solution is to change the function's argument type to QGraphicsWidget* and create the object as QGraphicsWidget *parentWidget = new QGraphicsWidget(). This would also eliminate a very strange and incorrect use of memmove from your code.
I might be wrong but as far as I know you can't copy QGraphicsWidget since it inherits from QObject. (Can be read here)
My suggestion:
void DiagramScene::insertWidget(DiagramItem::DiagramType diagramtype)
{
QGraphicsWidget* parentWidget = new QGraphicsWidget();
//some code
connect(this,SIGNAL(sendToItemList(QGraphicsWidget)),diagramitem,SLOT(addToItemList(QGraphicsWidget)));
emit this->sendToItemList(parentWidget);
}
void DiagramItem::addToItemList(QGraphicsWidget* widget)
{
items.append(widget);
}

create object for class inheriting QLayout

I have a screen class as
class Screen : public QLayout
{
public:
Screen();
~Screen();
void paintEvent(QPaintEvent *e);
};
When I am creating the object I got an error that can not create an object for pure abstract class. Since QLayoput is pure abstract , How can I create an object for a class which is inherits the QLayout ?
definitions:
Screen::Screen( )
{
}
Screen::~Screen()
{
delete this ;
//Screen(new QSize (100,100));
}
void Screen::paintEvent(QPaintEvent *e)
{
}
QLayout is pure abstract, meaning it has virtual members without a definition. To subclass it, you need to provide definitions for all such methods in your class. Specifically, Qt Docs state that
To make your own layout manager, implement the functions addItem(),
sizeHint(), setGeometry(), itemAt() and takeAt().
For more, see there (there are additional optional advices for further functions which should be implemented): http://qt-project.org/doc/qt-4.8/qlayout.html

Resources