QListView with checkboxes for viewing of filesystem - qt

It is necessary to list of directories by given path in QListView whith icons and checkboxes, then transmit names of marked folders to the program. For list directories i use code:
#include <QtGui/QApplication>
#include <QFileSystemModel>
#include <QListView>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QFileSystemModel model;
QListView listView;
listView.setModel(&model);
listView.setRootIndex(model.setRootPath("C:\\Program Files"));
listView.show();
return a.exec();
}
How to add checkboxes and transmit it after pushing button?
Thanks.

There's nothing you can do that would fit in just a few lines. You can either derive from QFileSystemModel and add a checkbox column, or create a proxy model that will do the same.
Note that you can use built-in selection mechanism to Ctrl-click/⌘-click to expand the selection to multiple items:
//main.cpp
#include <QApplication>
#include <QFileSystemModel>
#include <QGridLayout>
#include <QListView>
#include <QPushButton>
#include <QMessageBox>
class Win : public QWidget
{
Q_OBJECT
QListView * view;
QPushButton * button;
public:
Win(QAbstractItemModel * model, const QModelIndex & idx) :
view(new QListView(this)), button(new QPushButton("List Selection", this))
{
QGridLayout * lay = new QGridLayout;
lay->addWidget(view, 0, 0, 1, 2);
lay->addWidget(button, 1, 0);
setLayout(lay);
view->setSelectionMode(QAbstractItemView::MultiSelection);
view->setModel(model);
view->setRootIndex(idx);
connect(button, SIGNAL(clicked()), SLOT(showSelection()));
}
public slots:
void showSelection() {
QString str;
foreach (QModelIndex i, view->selectionModel()->selectedIndexes()) {
str.append(i.data().toString());
str.append("\n");
}
QMessageBox::information(this, "Selected items", str);
}
};
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QFileSystemModel model;
Win v(&model, model.setRootPath("/"));
v.show();
return a.exec();
}
#include "main.moc"

Related

Qt widget does not receive keyPressEvent

My child widget does not get keyPressEvents, while if I put the same widget as top level window, it does. I try to set it get focus, but it has no effect on this. Code is below, showing what I try to get to work.
#include <QApplication>
#include <QKeyEvent>
#include <QLCDNumber>
#include <QLabel>
#include <QVBoxLayout>
class DigitSummer: public QLCDNumber {
Q_OBJECT
public:
DigitSummer(QWidget *parent = nullptr) : QLCDNumber(parent) {
}
protected:
void keyPressEvent(QKeyEvent *event) override {
display(intValue() + event->text().toInt());
}
};
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
#if 1 // this version does not work, number does not increase
QWidget widget;
widget.setLayout(new QVBoxLayout());
widget.layout()->addWidget(new QLabel("Press digits!"));
DigitSummer summer; // in stack: must be after widget to avoid child delete
widget.layout()->addWidget(&summer);
widget.setFocusProxy(&summer); // I notice no effect!
widget.show();
#else // this version works, number grows with keypresseas
DigitSummer summer;
summer.show();
#endif
return a.exec();
}
#include "main.moc"
And for completenes, .pro file for the same:
QT += core gui widgets
TARGET = QtMCVE
TEMPLATE = app
DEFINES += QT_DEPRECATED_WARNINGS
CONFIG += c++11
QMAKE_CXXFLAGS += -Wall -Wextra
SOURCES += main.cpp
How to fix the widget to receive key events?
This related question suggests installing event filter, but I don't want to do that, there must be a self-contained way to fix the widget itself.
I think you need to set the focus policy for the widget before it will accept keyboard input. In your ctor try...
setFocusPolicy(Qt::StrongFocus);
Having said that, I'm really not sure why the behaviour would differ for top-level and non-top-level widgets.
Working version of the question code:
#include <QApplication>
#include <QKeyEvent>
#include <QLCDNumber>
#include <QLabel>
#include <QVBoxLayout>
class DigitSummer: public QLCDNumber {
Q_OBJECT
public:
DigitSummer(QWidget *parent = nullptr) : QLCDNumber(parent) {
setFocusPolicy(Qt::StrongFocus);
}
protected:
void keyPressEvent(QKeyEvent *event) override {
display(intValue() + event->text().toInt());
}
};
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QWidget widget;
widget.setLayout(new QVBoxLayout());
widget.layout()->addWidget(new QLabel("Press digits!"));
widget.layout()->addWidget(new DigitSummer);
widget.show();
return a.exec();
}
#include "main.moc"

How to redefine a node expanding in a QTreeWidget?

The way I understand the qtreeview.cpp the expand method in the QTreeView is responsible for expanding nodes. For example it is used in the expandOrCollapseItemAtPos method. I try to redefine a node expansion in the QTreeWidget:
#include <QApplication>
#include <QWidget>
#include <QTreeWidget>
#include <QMessageBox>
class MyTree : public QTreeWidget
{
public:
MyTree(QWidget *parent) : QTreeWidget(parent) {}
expandItem(const QTreeWidgetItem *item) {
QMessageBox msg;
msg.setText("EXPAND ITEM!!");
msg.exec();
QTreeWidget::expandItem(item);
}
expand(const QModelIndex &index) {
QMessageBox msg;
msg.setText("EXPAND!!");
msg.exec();
QTreeWidget::expand(index);
}
};
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QWidget *mainWidget = new QWidget();
mainWidget->resize(200,100);
MyTree *myTree = new MyTree(mainWidget);
myTree->resize(200,100);
QTreeWidgetItem *node, *leaf;
node = new QTreeWidgetItem(myTree);
node->setText(0,"node");
leaf = new QTreeWidgetItem(node);
leaf->setText(0,"leaf");
mainWidget->show();
return a.exec();
}
But there is no any message box when I expand a node. I tried to comment QTreeWidget::expandItem(item); and QTreeWidget::expand(index); but expanding is still working.
How do I redefine a node expanding in a QTreeWidget?
QTreeWidget::expand and QTreeWidget::expandItem are non-virtual methods. So redefinition is not useful. I will use slot-signal mechanism with QTreeWidget::expanded/collapsed signals.
connect(this, SIGNAL(expanded(QModelIndex)), this, SLOT(myExpand(QModelIndex)));
This should solve your problem -
connect(QTreeWidgetObject, SIGNAL(itemExpanded(QTreeWidgetItem*)), SLOT(slotItemExpanded(QTreeWidgetItem*)));

accessing a ui.label from main.cpp in QT

i am trying to take a feedback data which is published from arduino and subscribed to my GUI created in QT.
Now i have main.cpp and mainwindow.cpp.
main.cpp
#include <QtGui>
#include <ros/ros.h>
#include <QApplication>
#include "../include/abc/main_window.hpp"
#include "std_msgs/String.h"
#include <std_msgs/UInt16.h>
#include <QMainWindow>
#include <std_msgs/Float32.h>
void chatterCallback(const std_msgs::UInt16 &fb_msg){
ROS_INFO("Feedback: [%f]", fb_msg.data);
ui.label_6->setText(QString("%1").arg(fb_msg.data));
}
int main(int argc, char **argv) {
ros::init(argc, argv, "talker");
ros::NodeHandle n;
ros::Subscriber sub = n.subscribe("feedback",1000, chatterCallback);
ros::spinOnce();
QApplication app(argc, argv);
abc::MainWindow w(argc,argv);
w.show();
w.setWindowTitle("GUI for Controlling Servo Motor");
app.connect(&app, SIGNAL(lastWindowClosed()), &app, SLOT(quit()));
int result = app.exec();
return result;}
mainwindow.cpp
namespace abc {
using namespace Qt;
QSerialPort *serial;
MainWindow::MainWindow(int argc, char** argv, QWidget *parent)
: QMainWindow(parent)
, qnode(argc,argv)
{
ui.setupUi(this);
}
MainWindow::~MainWindow() {}
void MainWindow::on_horizontalSlider_valueChanged(int value)
{
ui.label_5->setText(QString("%1").arg(value));
msg.data = ui.label_5->text().toUInt();
ROS_INFO("%d", msg.data);
chatter_pub.publish(msg);
ros::spinOnce();
}
main_window.hpp
#ifndef abc_MAIN_WINDOW_H
#define abc_MAIN_WINDOW_H
#include <QtGui/QMainWindow>
#include "ui_main_window.h"
#include "qnode.hpp"
#include <QtSerialPort/QSerialPort>
#include <ros/ros.h>
#include "std_msgs/UInt16.h"
namespace abc {
class MainWindow : public QMainWindow {
Q_OBJECT
public:
MainWindow(int argc, char** argv, QWidget *parent = 0);
~MainWindow();
public Q_SLOTS:
private:
Ui::MainWindowDesign ui;
ros::NodeHandle n;
ros::Publisher chatter_pub = n.advertise <std_msgs::UInt16> ("chatter", 1000);
QSerialPort *arduino;
QNode qnode;
};
} // namespace abc
#endif // abc_MAIN_WINDOW_H
Now when i run this code, it shows me that UI is not declared in main.cpp.
I wanted to display the data from feedback to label_6 (TextBox). The data is only available in main.cpp, any suggestions are highly appreciable.
Thanks in advance.
You will have to pass the fb_msg.data as an argument to the MainWindow constructor. Then you can set the UI element in the MainWindow thread.
Alternatively once you create the MainWindow instance in your main, you can emit a signal which you catch and process in the MainWindow thread.
You cannot modify the UI elements from a different thread.

Qt Widget temporarily fullscreen

Consider a QWidget, normally a child in some Layout.
Supposed I want to make it fullScreen for a while, then have it return to it's old spot.
QWidget::setFullScreen() requires that the widget needs to be an independent window - any ideas how to work it out?
The simplest way I can see is to reparent to 0. Something like this:
#include <QApplication>
#include <QPushButton>
class MyButton : public QPushButton
{
public:
MyButton(QWidget* parent) : QPushButton(parent) {}
void mousePressEvent(QMouseEvent*) {
this->setParent(0);
this->showMaximized();
this->show();
}
};
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QWidget mainWidget;
MyButton button(&mainWidget);
mainWidget.show();
return a.exec();
}
I have modified the previous example. The previous example never goes back to normal screen.
Just copy paste the code and it will run.
#include <QApplication>
#include <QPushButton>
class MyButton : public QPushButton
{
public:
MyButton(QWidget* parent) : QPushButton(parent) {
m_pParent = parent;
maxMode = false;
}
QWidget * m_pParent;
bool maxMode;
Qt::WindowFlags m_enOrigWindowFlags;
QSize m_pSize;
void mousePressEvent(QMouseEvent*) {
if (maxMode== false)
{
m_enOrigWindowFlags = this->windowFlags();
m_pSize = this->size();
this->setParent(0);
this->setWindowFlags( Qt::FramelessWindowHint|Qt::WindowStaysOnTopHint);
this->showMaximized();
maxMode = true;
}
else
{
this->setParent(m_pParent);
this ->resize(m_pSize);
this->overrideWindowFlags(m_enOrigWindowFlags);
this->show();
maxMode = false;
}
}
};
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QWidget mainWidget;
MyButton button(&mainWidget);
mainWidget.show();
return a.exec();
}

How to make QTextBrowser scale nicely within QVBoxLayout?

I'd like to display a list of short html snippets in a scrollable list. Thus i place a QVboxLayout into a QScrollArea and add multiple QTextBrowsers:
#include <QApplication>
#include <QScrollArea>
#include <QTextBrowser>
#include <QVBoxLayout>
int main(int argc, char *argv[]) {
QApplication app(argc, argv);
QScrollArea scrollArea;
scrollArea.setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
scrollArea.setWidgetResizable(true);
QWidget *scrollWidget = new QWidget;
QVBoxLayout *layout = new QVBoxLayout;
for(int i=0;i<6;i++) {
QString text = "some <b>text</b> ";
for(int j=0;j<i;j++) text += text;
QTextBrowser *browser = new QTextBrowser();
QTextDocument *doc = new QTextDocument(browser);
doc->setHtml(text);
browser->setDocument(doc);
layout->addWidget(browser);
}
scrollWidget->setLayout(layout);
scrollArea.setWidget(scrollWidget);
scrollArea.show();
return app.exec();
}
My problem: The boxes all have the same size. I want them to be as big as necessary, but not bigger. How can i make the textbrowsers to take only as much space as they really need?
Ok, i found a solution derived from http://www.qtcentre.org/threads/39839-QTextBrowser-height-adjusted-to-content. Is there a simpler/mor elegant solution?
#include <QApplication>
#include <QScrollArea>
#include <QTextBrowser>
#include <QVBoxLayout>
#include <QGroupBox>
#include <QDebug>
#include <QShowEvent>
#include <QResizeEvent>
class MyBrowser : public QTextBrowser {
private:
QTextDocument *doc;
public:
MyBrowser(const QString &text, QWidget *parent = 0) : QTextBrowser(parent) {
doc = new QTextDocument(this);
doc->setHtml(text);
setDocument(doc);
}
void adjust() {
QMargins margins = contentsMargins();
int width = size().width() -
margins.left() - margins.right() - doc->documentMargin()*2;
doc->setPageSize(QSizeF(width,-1));
int height = doc->size().height() + margins.top() + margins.bottom();
setMaximumHeight(height);
setMinimumHeight(height);
}
void showEvent(QShowEvent *) {
adjust();
}
void resizeEvent(QResizeEvent *) {
adjust();
}
};
int main(int argc, char *argv[]) {
QApplication app(argc, argv);
QScrollArea scrollArea;
scrollArea.setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
scrollArea.setWidgetResizable(true);
QWidget *scrollWidget = new QWidget;
QVBoxLayout *layout = new QVBoxLayout;
for(int i=0;i<6;i++) {
QString text = "some <b>text</b> ";
for(int j=0;j<i;j++) text += text;
MyBrowser *browser = new MyBrowser(text, scrollWidget);
layout->addWidget(browser, 0, 0);
}
scrollWidget->setLayout(layout);
scrollArea.setWidget(scrollWidget);
scrollArea.show();
return app.exec();
}
Instead of doing
layout->addWidget(browser);
You should do:
layout->addWidget(browser, 0, 0);
This will tell QT not to stretch the widget according to its layout.

Resources