QT Signals and Slots, dynamic menubar - qt

I am new to qt and I want to know how to make a dynamic menu.
I did get it to make new submenus but I don't know how I can implement the "triggered() function" of these dynamic made submenus, so that I have access to what happens if I want to click on such a new submenu.
Here what I have so far (with: vector<QString> = vec; and some .ui Window named "New_Window")
in mainwindow.cpp
in some function:
QMenu *menu = this->menuBar()->addMenu("Chat Members");
for (int i = 0; i < vec.size(); ++i){
QString name = vec.at(i);
QAction *act = menu->addAction(name);
New_Window* new_window = new New_Window;
QObject::connect(act,SIGNAL(triggered()),
new_window,SLOT(actionReaction()));
}

here is an example of how a signal slot with a dynamic interface works ,
class A is created after starting the program, then the user clicks on a button from class A, for example, a class A is created many times and we need to determine from what object we get a signal to press the button, so
class A : public QMainWindow
{
Q_OBJECT
public:
A(QWidget *parent = nullptr);
~A();
void setID(const int id);
void getId() const;
signals:
void onButtonPress(int ID);
private:
int mID;
};
here we create a new class A and store it in the vector in such a way,
QVector<A*> mCreatingClassA;
void createNewClassA
{
QVector<A*> mCreatingClassA;
....
A* a = new A();
int id = // create your unique ID
a->setId(id);
connect(a,SIGNAL(onButtonPress(int)),this,SLOT(onyourSlot(int)));
mCreatingClassA.push_back(a);
....
}
detect the object from which the signal was received)
void onyourSlot(int ID)
{
for (int i = 0; i < mCreatingClassA.size(); ++i) {
if(mCreatingClassA[i]->getId()==ID)
{
mCreatingClassA[i] // received a signal from this object
}
}
}

Related

Subclassing QTreeWidgetItem

I am trying to subclass QTreeWidgetItem so I can fill-in class with data I need.
Went through all the code and couldn't find one complete example on how to do it right.
In my implementation something is wrong because application won't start up, but if I do it with QTreeWidgetItem then it works without any problems.
So I have created subclass as H file:
#ifndef XITEM_H
#define XITEM_H
#include <QTreeWidget>
class XItem : public QObject,public QTreeWidgetItem
{
Q_OBJECT
public:
XItem ();
void setText(int column, const QString &atext);
void addChild(QTreeWidgetItem *child);
};
#endif
And C file:
#include "X.h"
XItem ::XItem (): QTreeWidgetItem(UserType)
{
}
void XItem::setText(int column, const QString &atext){
setText(column,atext);
}
void XItem::addChild(QTreeWidgetItem *child){
addChild(child);
}
And code that runs it all:
QTreeWidget * tree = ui->treeWidget;
QTreeWidgetItem * topLevel = new QTreeWidgetItem();
topLevel->setText(0, "This is top level");
for(int i=0; i<5; i++)
{
//QTreeWidgetItem * item = new QTreeWidgetItem();
XItem *item = new XItem();
item->setText(0,"item " + QString::number(i+1));
topLevel->addChild(item);
}
tree->addTopLevelItem(topLevel);
If I run it like this application hangs and if I comment:
XItem *item = new XItem();
and un-comment:
QTreeWidgetItem * item = new QTreeWidgetItem();
it works.
Could anyone help out on this please.
Kind regards!
Anyway... after all years still simple mistake as this one can come along long hours coding.
ERROR:
void XItem::setText(int column, const QString &atext){
setText(column,atext);
}
void XItem::addChild(QTreeWidgetItem *child){
addChild(child);
}
Should be:
void XItem::setText(int column, const QString &atext){
QTreeWidgetItem::setText(column,atext);
}
void XItem::addChild(QTreeWidgetItem *child){
QTreeWidgetItem::addChild(child);
}

Is it possible to have a "wrap" behaviour in QMenu?

I have to store many items in a QMenu. If there is too many items QMenu wraps them ans begins a new column, but it happens only if these items can not fit into screen height.
I'd like to have QMenu which wraps items when the menu height reaches, for example, parent widget's height or any other custom value.
I wasn't able to find any properties in QMenu for achieving this. Setting maximumHeight gave no result. After digging into QMenu sources I found that the "wrapping logic" works based on popupGeometry method result. But popupGeometry uses screen size, and it is private so I don't know a way to change it.
As I didn't find the answer, I had to implement this control by myself.
It is a popup widget, using QToolButton as an owner. It can arrange items in a grid depending on item's height and required menu height.
class myLabel:public QLabel
{
Q_OBJECT
// QObject interface
public:
myLabel(QWidget* parent=0):QLabel(parent){}
bool event(QEvent *e)
{
if(e->type()==QEvent::MouseButtonPress)
emit clicked();
return QLabel::event(e);
}
void setAction(QAction *a)
{
setText(a->text());
_action=a;
}
QAction* action()
{
return _action;
}
signals:
void clicked();
private:
QAction* _action;
};
class myMenu: public QWidget
{
Q_OBJECT
public:
myMenu(QWidget* owner,QWidget* parent=0):QWidget(parent){
this->setWindowFlags(Qt::Popup);
l = new QGridLayout(this);
l->setContentsMargins(QMargins(3,3,3,3));
_owner=owner;
QString style="QLabel:hover{background-color: white;} ";
setStyleSheet(style);
}
void addAction(QAction*a){_actions.append(a);}
QVector<QAction*> actions(){return _actions;}
void setItemHeight(int val){_itemHeight=val;}
void setHeight(int val){_height=val;}
private:
QVector<QAction*> _actions;
QGridLayout *l ;
QWidget*_owner;
int _itemHeight=30;
int _height=200;
private slots:
void popup()
{
clear();
//move popup under toolbutton
QPoint p = _owner->geometry().bottomLeft();
p.setY(p.y()+1);
this->move(_owner->parentWidget()->mapToGlobal(p));
//calculate rows count
int rows = _height/_itemHeight;
//calculate cols count
int cols = _actions.size()/rows;
int d = _actions.size()%rows;
if(d>0)
cols++;
for(int i=0;i<rows;i++)
for(int j=0;j<cols;j++)
{
int index = i+j*rows;
if(index<_actions.size())
{
myLabel *lb = new myLabel(this);
connect(lb,SIGNAL(clicked()),this,SLOT(onClick()));
lb->setFixedHeight(_itemHeight);
lb->setAction(_actions[index]);
l->addWidget(lb,i,j);
}
}
this->repaint();
this->show();
}
void clear()
{
while(l->itemAt(0)!=NULL)
{
QLayoutItem* i = l->takeAt(0);
if(i->widget())
delete i->widget();
if(i->layout())
delete i->layout();
delete i;
}
}
void onClick()
{
myLabel *g = qobject_cast<myLabel*>(sender());
g->action()->trigger();
close();
}
// QWidget interface
protected:
void closeEvent(QCloseEvent *)
{
qobject_cast<QToolButton*>(_owner)->setDown(false);
}
signals:
void closed();
};
There's also an example showing how to create and fill myMenu and how to receive a selected action.
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
//set-up myMenu, btMyMenu is a QToolButton
myMenu *mMenu = new myMenu(ui->btMyMenu,this);
connect(ui->btMyMenu,SIGNAL(pressed()),mMenu,SLOT(popup()));
for(int i=0;i<20;i++)
{
QAction *a = new QAction("Action "+QString::number(i),this);
connect(a,SIGNAL(triggered(bool)),this,SLOT(onActSelected()));
mMenu->addAction(a);
}
//mMenu can be customized
mMenu->setHeight(100);
mMenu->setItemHeight(50);
}
void MainWindow::onActSelected()
{
QAction *a = qobject_cast<QAction*>(sender());
ui->btMyMenu->setText(a->text());
}
Any comments about how to improve this solution are appreciated!

QTreeView doesn't scale - is there a workaround to fetch fewer ModelIndexes?

I'm working on an app that uses Qt's QTreeView to display hierarchical data. In some cases a single leaf in the hierarchy will contain 100,000's of child nodes.
I've discovered that QTreeView can't handle too many child nodes.
This is because when the user opens a parent node, Qt fetches ALL of the child nodes' ModelIndexes, not just the ones that are needed to fill the QTreeView display.
Why does it do this, and is there any workaround to make it fetch fewer ModelIndexes?
My previous answer was unfortunately useless due to QTreeWidget(I am using QTreeWidget to simplyfy) sliders cannot be set by user.
Your goal could be achieved by using extra QScrollBar.
MainWidget.h
class MainWidget : public QWidget
{
Q_OBJECT
public:
MainWidget(QWidget *parent = 0);
private:
QTreeWidget* Tree;
QScrollBar* Bar;
private slots:
void tree(QTreeWidgetItem*);
void slider();
};
MainWidget.cpp
MainWidget::MainWidget(QWidget *parent): QWidget(parent) {
Tree = new QTreeWidget();
Tree->header()->hide();
connect(Tree,SIGNAL(itemExpanded(QTreeWidgetItem*)),this,SLOT(tree(QTreeWidgetItem*)));
Bar = new QScrollBar(Qt::Vertical);
Bar->setRange(0,100000);
connect(Bar,SIGNAL(sliderReleased()),this,SLOT(slider()));
for(uint i=0;i<10;i++) {
QTreeWidgetItem* Item=new QTreeWidgetItem(QStringList()<<QString::number(i)); //Add 10 topLevelItems
Tree->addTopLevelItem(Item);
for(uint j=0;j<30;j++) {
Item->addChild(new QTreeWidgetItem(QStringList()<<QString::number(j))); //Add first 30 items
}
}
QHBoxLayout* Lay = new QHBoxLayout();
Lay->addWidget(Tree);
Lay->addWidget(Bar);
setLayout(Lay);
}
void MainWidget::tree(QTreeWidgetItem* I) { //SLOT Only one item expanded
Tree->blockSignals(true); //Block SIGNAL(itemExpanded())
Tree->collapseAll();
Tree->expandItem(I);
Tree->blockSignals(false);//Allow SIGNAL(itemExpanded())
}
void MainWidget::slider() { //SLOT manage tree
for (int i=0;i<Tree->topLevelItemCount();i++) {
if (Tree->topLevelItem(i)->isExpanded()) {
for(uint j=Tree->topLevelItem(i)->childCount(); j>0;j--) { //Clear children
delete Tree->topLevelItem(i)->child(j-1);
}
uint Value = Bar->value();
for(uint j=0; j<30; j++) {
Tree->topLevelItem(i)->addChild(new QTreeWidgetItem(QStringList()<<QString::number(Value+j))); //Add 30 new children
}
break;
}
}
}
This way you have one slider to scroll the QTreeWidget and the second one to change content of expanded topLevelItem.

QTreeWidgetItem issue: Items set using setWidgetItem are dispearring after moving

I have a bunch of QTreeWidgetItems that have embedded widgets in them that i set using the setItemWidget() function in the QTreeWidgetItem class.
Problem is anytime I move QTreeWidgetItem using drag/drop or any other means the embedded widget I set before disappears. I've seen around various forums that others have had this same problem (see link below)
http://www.qtcentre.org/threads/40500-QTreeWidget-setItemWidget%28%29-item-disappears-after-moving-item
Any possible solutions?
The problem is caused by QTreeWidget's implementation. When items are moved within the model, it deletes items at old positions and recreates them at new positions. We need to ensure 3 thinngs:
Rescue embedded widget from being deleted when its item is deleted.
Attach some information to items so we can track them and choose which widget belongs to an item.
Re-insert widget after item is moved.
Here is proof-of-concept implementation. Tree_widget_keeper_wrapper ensures 1st objective, setItemWidget's reimplementation ensures the 2nd one, and rows_inserted slot ensures the 3rd one. I tested that it works but it should be improved before using in real projects. Qt::UserRole should be changed to a configurable role. We should use role that is not used by the model itself. I put all implementation to class declaration to make it more readable but you should separate them in real code.
class Tree_widget_keeper_wrapper : public QWidget {
Q_OBJECT
public:
Tree_widget_keeper_wrapper(QWidget* child) {
_child = child;
QVBoxLayout* layout1 = new QVBoxLayout(this);
layout1->setContentsMargins(0, 0, 0, 0);
layout1->addWidget(_child);
}
~Tree_widget_keeper_wrapper() {
if (_child->parent() == this) {
_child->hide();
_child->setParent(0);
}
}
private:
QWidget* _child;
};
class Fixed_tree_widget : public QTreeWidget {
Q_OBJECT
public:
Fixed_tree_widget(QWidget* parent) : QTreeWidget(parent) {
connect(model(), SIGNAL(rowsInserted(QModelIndex,int,int)),
this, SLOT(rows_inserted(QModelIndex,int,int)));
}
void setItemWidget(QTreeWidgetItem* item, int column, QWidget* widget) {
QTreeWidget::setItemWidget(item, column, new Tree_widget_keeper_wrapper(widget));
item->setData(column, Qt::UserRole, all_widgets.count());
all_widgets << widget;
}
private:
QWidgetList all_widgets;
private slots:
void rows_inserted(QModelIndex parent, int start, int end) {
for(int column = 0; column < model()->columnCount(parent); column++) {
for(int row = start; row <= end; row++) {
QModelIndex index = model()->index(row, column, parent);
QVariant data = model()->data(index, Qt::UserRole);
if (data.type() == QVariant::Int) {
int i = data.toInt();
QTreeWidgetItem* item = itemFromIndex(index);
if (item && i >= 0 && i < all_widgets.count()) {
setItemWidget(item, column, all_widgets[i]);
all_widgets[i]->show();
}
}
}
}
}
};
I tested it against InternalMove mode and dragging items with mouse. Maybe in some other cases you will need to listen to other model's signals.

multiple signals for one slot

For my GUI i would like to have two pairs of buttons that scroll up and down a scrollarea. The first set of buttons should work on say scrollarea1 and the second set of buttons should work on a scrollarea2. The widgets that I put in the scrollarea are called viewport1 and viewport2.
Since both both set of buttons should do the same (scrolling up and down) I thought I would make two slots called scrollUp and scrollDown that would handle the scrolling for both sets of buttons. Unfortunately I cannot make this work and need some help. I have tried the following:
QPushButton up;
QPushButton down;
QPushButton up2;
QPushButton down2;
connect(&up,SIGNAL(clicked()),&up,SLOT(scrollUp()));
connect(&up2,SIGNAL(clicked()),&up,SLOT(scrollUp()));
connect(&down,SIGNAL(clicked()),&down,SLOT(scrollDown()));
connect(&down2,SIGNAL(clicked()),&down,SLOT(scrollDown()));
void MainWindow::scrollDown()
{
QScrollArea area;
QWidget view;
if((QPushButton) &sender = down)
{
area=scrollArea;
view=viewport;
}
if((QPushButton) &sender = down2)
{
area=scrollArea;
view=viewport;
}
int curpos = area.verticalScrollBar()->value();
area.verticalScrollBar()->setValue(curpos+15);
int newpos = area.verticalScrollBar()->value();
QPoint topLeft = area.viewport()->rect().topLeft();
view.move(topLeft.x(),topLeft.y()-(newpos));
}
void MainWindow::scrollUp()
{
QScrollArea area;
QWidget view;
if((QPushButton) &sender = up)
{
area=scrollArea;
view=viewport;
}
if((QPushButton) &sender = up2)
{
area=scrollArea2;
view=viewport2;
}
int curpos = area.verticalScrollBar()->value();
area.verticalScrollBar()->setValue(curpos-15);
int newpos = area.verticalScrollBar()->value();
QPoint topLeft = area.viewport()->rect().topLeft();
view.move(topLeft.x(),topLeft.y()-(newpos));
}
But this doesn´t work for several reasons. I also tried giving the slot some arguments, something like:
connect(&up,SIGNAL(clicked()),&up,SLOT(scrollUp(scrollarea1,viewport1)));
connect(&up2,SIGNAL(clicked()),&up,SLOT(scrollUp(scrollarea2,viewport2)));
But again, no succes. Can anybody help me?
First of all, "It doesn't work" does not mean anything, and it is hard to help you if you do not say what errors you get. Then, there are few problems.
All QObject's derived classes are not copiable, it means you can not do
QWidget a;
QWidget b;
b = a; // Wrong
You should use pointers (or perhaps references).
QWidget a;
QWidget * b = new QWidget(...);
QWidget * c;
c = & a; // Ok
c = b; // Ok
Then your connect calls are wrong:
connect(&up, SIGNAL(clicked()), &up, SLOT(scrollUp()));
The third argument is the object who has the slot. up is a QPushButton, it does not have a scrollUp() slot, it is your MainWindow who does:
connect(&up, SIGNAL(clicked()), this, SLOT(scrollUp()));
(since connect is called in MainWindow's constructor this points to the current MainWindow object).
Also in C++ the single = sign means assignment, for equality comparison use =='. Andsender` is a function.
Your approach should work if implemented in the right way:
class MainWindow: public QWidget
{
QScrollArea * scroll1;
QScrollArea * scroll2;
QWidget * view1;
QWidget * view2;
QPushButton * up1;
QPushButton * up2;
QPushButton * down1;
QPushButton * down2;
public:
MainWindow()
{
// Here initialize member variables.
...
connect(up1, SIGNAL(clicked()), this, SLOT(scrollUp()));
connect(up2, SIGNAL(clicked()), this, SLOT(scrollUp()));
connect(down1, SIGNAL(clicked()), this, SLOT(scrollDown()));
connect(down2, SIGNAL(clicked()), this, SLOT(scrollDown()));
}
public slots:
void scrollDown()
{
QScrollArea * area;
QWidget * view;
if(qobject_cast<QPushButton>(sender()) == down1) {
area = & scroll1;
view = & view1;
} else if(qobject_cast<QPushButton>(sender()) == down2) {
area = & scroll2;
view = & view2;
} else {
// Error.
}
// Now `area` and `view` point to the right widgets.
...
}
void scrollUp()
{
// The same as before.
}
};
Another approach would be to extract the actual scrolling instructions to a separate function:
class MainWindow: public QWidget
{
// Same variables as before
...
public:
MainWindow()
{
// Here initialize member variables.
...
connect(up1, SIGNAL(clicked()), this, SLOT(scrollUp1()));
connect(up2, SIGNAL(clicked()), this, SLOT(scrollUp2()));
connect(down1, SIGNAL(clicked()), this, SLOT(scrollDown1()));
connect(down2, SIGNAL(clicked()), this, SLOT(scrollDown2()));
}
public slots:
void scrollDown(QScrollArea * area, QWidget * view)
{
// Here you scroll over `area` and `view`.
}
void scrollDown1()
{
scrollDown(scroll1, area1);
}
void scrollDown2()
{
scrollDown(scroll2, area2);
}
// Again, the same for `scrollUp`.
};
There are several mistakes in your code :
About the sender of the signal : There is not a QObject called "sender" but a method QObject * QObject::sender() const; which returns a pointer on the sender of the signal.
In the if conditions : you are casting a QPushButton** into a QPushButton ((QPushButton) &sender) and you dont compare that thing with your buttons up(2) and down(2).
In your connections between slots and signals : the scrollUp and scrollDown slots do not belong to the QPushButton class but to your MainWindow class.
Finally, you should write something like this :
connect(&up, SIGNAL(clicked()), this, SLOT(scrollUp()));
connect(&up2, SIGNAL(clicked()), this, SLOT(scrollUp()));
connect(&down, SIGNAL(clicked()), this, SLOT(scrollDown()));
connect(&down2, SIGNAL(clicked()), this, SLOT(scrollDown()));
void MainVindow::scrollDown() {
// [...]
QPushButton * senderButton = qobject_cast<QPushButton *>(this->sender());
// QPushButton * senderButton = (QPushButton *) this->sender(); works too
if (senderButton == &down) {
// [...]
}
if (senderButton == &down2) {
// [...]
}
// [...]
}
void MainVindow::scrollUp() {
// [...]
QPushButton * senderButton = qobject_cast<QPushButton *>(this->sender());
// QPushButton * senderButton = (QPushButton *) this->sender(); works too
if (senderButton == &up) {
// [...]
}
if (senderButton == &up2) {
// [...]
}
// [...]
}
First of all the slot can have no other arguments than the signal hands to it. Clicked has no arguments and there fore the slot can have no arguments.
I would think that the easiest way to check whether scrollArea 1 or 2 has focus and decide from that which one should move.
I also think that there is an error in your code. Shouldn't this:
if((QPushButton) &sender = down2)
{
area=scrollArea;
view=viewport;
}
Be this:
if((QPushButton) &sender = down2)
{
area=scrollArea2;
view=viewport2;
}
First of all, this is pseudo code. It won't compile, but it should contain the necessary information.
I believe this problem can be most elegantly solved using the QSignalMapper class. It allows parameterless signals from multiple senders to connect to one slot.
In the header, write something like this:
class QSignalMapper;
class MainWindow : public QMainWindow
{
public:
void init();
public slots:
void handleScrollButtons(int id);
private:
enum { ScrollUp1, ScrollDown1, ScrollUp2, ScrollDown2 } // just makes it more convenient to use
QSignalMapper *m_scrollbuttonhandler;
}
In the source file, write something like this
#include <QSignalMapper>
void MainWindow::init()
{
m_scrollbuttonhandler = new QSignalMapper(this);
m_scrollbuttonhandler->setMapping(scrollup1button, ScrollUp1);
m_scrollbuttonhandler->setMapping(scrolldown1button, ScrollDown1);
m_scrollbuttonhandler->setMapping(scrollup2button, ScrollUp2);
m_scrollbuttonhandler->setMapping(scrolldown2button, ScrollDown2);
connect(scrollup1button, SIGNAL(clicked(bool)), m_scrollbuttonhandler, SLOT(map()));
connect(scrolldown1button, SIGNAL(clicked(bool)), m_scrollbuttonhandler, SLOT(map()));
connect(scrollup2button, SIGNAL(clicked(bool)), m_scrollbuttonhandler, SLOT(map()));
connect(scrolldown2button, SIGNAL(clicked(bool)), m_scrollbuttonhandler, SLOT(map()));
connect(m_scrollbuttonhandler, SIGNAL(mapped(int)), this, SLOT(handleScrollButtons(int)));
}
void MainWindow::handleScrollButtons(int id)
{
switch (id)
{
case ScrollUp1:
// stuff to do for scrollup1button
case ScrollDown1:
// stuff to do for scrolldown1button
case ScrollUp2:
// stuff to do for scrollup2button
case ScrollDown2:
// stuff to do for scrolldown2button
}
}

Resources