Can QT create a widget and add it to the layout in one line ?
-
wrote on 1 Sept 2023, 11:45 last edited by
In QT, this usually requires two lines of code, and I think the increase in the number of lines of code makes reading more complex. I used the template method to implement it on one line, but I still need to manually distinguish between controls and layouts. Is there a better implementation method?
#include <QApplication> #include <QWidget> #include <QHBoxLayout> #include <QVBoxLayout> #include <QRadioButton> //#include "RangeSlider.h" template<class W, class L, class... Args> W* NewW(L* l, Args&&... args) { auto w = new W(std::forward<Args>(args)...); l->addWidget(w); return w; } template<class L1, class L0, class... Args> L1* NewL(L0* l0, Args&&... args) { auto l1 = new L1(std::forward<Args>(args)...); l0->addLayout(l1); return l1; } class SelectZ : public QWidget { public: SelectZ() { auto h1 = new QHBoxLayout(this); //auto rs = NewW<RangeSlider>(h1, Qt::Vertical, RangeSlider::Option::DoubleHandles, this); auto v1 = NewL<QVBoxLayout>(h1, this); auto h21 = NewL<QHBoxLayout>(h1, this); QRadioButton* radioBtn1 = NewW<QRadioButton>(h21, u8"aaa", this); QRadioButton* radioBtn2 = NewW< QRadioButton>(h21, u8"bbb", this); } }; int main(int argc, char* argv[]) { QApplication a(argc, argv); SelectZ w; w.resize(800, 600); w.show(); return a.exec(); }
-
In QT, this usually requires two lines of code, and I think the increase in the number of lines of code makes reading more complex. I used the template method to implement it on one line, but I still need to manually distinguish between controls and layouts. Is there a better implementation method?
#include <QApplication> #include <QWidget> #include <QHBoxLayout> #include <QVBoxLayout> #include <QRadioButton> //#include "RangeSlider.h" template<class W, class L, class... Args> W* NewW(L* l, Args&&... args) { auto w = new W(std::forward<Args>(args)...); l->addWidget(w); return w; } template<class L1, class L0, class... Args> L1* NewL(L0* l0, Args&&... args) { auto l1 = new L1(std::forward<Args>(args)...); l0->addLayout(l1); return l1; } class SelectZ : public QWidget { public: SelectZ() { auto h1 = new QHBoxLayout(this); //auto rs = NewW<RangeSlider>(h1, Qt::Vertical, RangeSlider::Option::DoubleHandles, this); auto v1 = NewL<QVBoxLayout>(h1, this); auto h21 = NewL<QHBoxLayout>(h1, this); QRadioButton* radioBtn1 = NewW<QRadioButton>(h21, u8"aaa", this); QRadioButton* radioBtn2 = NewW< QRadioButton>(h21, u8"bbb", this); } }; int main(int argc, char* argv[]) { QApplication a(argc, argv); SelectZ w; w.resize(800, 600); w.show(); return a.exec(); }
1/2