QTreeView no show when placed inside QDockWidget - c++

I want to show a file system using QTreeView on a QDockWidget. The tree will be dynamically changed, so I decided to use QTreeView instead of QTreeWidget.
Here is my code:
QFile file(":/default.txt");
file.open(QIODevice::ReadOnly);
TreeModel model(file.readAll());
file.close();
QTreeView w;
w.setModel(&model);
swatch1->setWidget(&w);
w.setEnabled(true);
addDockWidget(leftarea, swatch1);
swatch1 is of type QDockWidget. The above code is inside a function body of type (inherited from) MainWindow. The code runs smoothly, and the tree does not show up.
I also tried another way: putting QTreeView into a QVBoxLayout (using setWidget method), which in turn be put into a QDockWidget (using setLayout method). This 2nd code also runs smoothly, and the tree does not show up.
This code is copied from a working example on Qt Creator IDE, and I tested it working. The only difference is, in the original QTreeView example, the above code is placed inside the main() { ..... } function.
Does anyone has a working example, putting QTreeView into QDockWidget and working (the code actually shows the tree)? Thanks in advance.

I'm not quite sure what went wrong in the OP. However, I made a minimal complete sample to see whether there are pitfalls:
// standard C++ header:
#include <iostream>
#include <string>
// Qt header:
#include <QApplication>
#include <QDockWidget>
#include <QFileSystemModel>
#include <QMainWindow>
#include <QTreeView>
using namespace std;
int main(int argc, char **argv)
{
cout << QT_VERSION_STR << endl;
// main application
#undef qApp // undef macro qApp out of the way
QApplication qApp(argc, argv);
// setup GUI
QMainWindow qWin;
QDockWidget qDock;
qDock.setAllowedAreas(Qt::AllDockWidgetAreas);
QTreeView qTreeView;
QFileSystemModel qFSModel;
qTreeView.setModel(&qFSModel);
QString path = QDir::currentPath();
QModelIndex indexPath = qFSModel.index(path);
qTreeView.scrollTo(indexPath);
qDock.setWidget(&qTreeView);
qWin.addDockWidget(Qt::TopDockWidgetArea, &qDock);
qWin.show();
// run application
return qApp.exec();
}
Compiled and tested it with VS2013, Qt 5.6 on Windows 10 (64 bit):
As can be seen in the snapshot, the QTreeView is visible (docked and undocked). I checked that both re-act on mouse clicks - they did.
(I guess this is one of my most minimal Qt applications I ever wrote.)

Scheff,
Thank you very much for your answer. Sorry I may not be clear about what I am asking: the tree become visible when this code section is in the main() { ....} function:
QFile file(":/default.txt");
file.open(QIODevice::ReadOnly);
TreeModel model(file.readAll());
file.close();
QTreeView w;
w.setModel(&model);
w.show();
But the same code (almost same) does not working (program runs but the tree is not visible) when this section of code is in a class function inside MainWindow and QTreeView is added to a QDockWidget:
QFile file(":/default.txt");
file.open(QIODevice::ReadOnly);
TreeModel model(file.readAll());
file.close();
QTreeView w;
w.setModel(&model);
swatch1->setWidget(&w);
addDockWidget(leftarea, swatch1);
here, leftarea is a Qt:DockWidgetArea, and swatch1 is an object of type inherited from QDockWidget. when run this program, swatch (a QDockWidget) is visible, but not the tree. still struggling ...

The problem solved. The original code I wrote by itself is correct, but it is in an object method, and as soon as the execution leaves the object, the tree is destroyed.
So, it is a C++ variable scoping problem, not exactly a Qt problem. I have been using python for a while, and just switch back to C++.
Scheff, thank you for your posting confirmed to me that the Qt code is correct, and suggests to me that something else is wrong.

Related

Is it possible to add background image on QWidget without using QtCreator?

Having trouble adding background image on the widget, even though I referenced the recent codes online.
This is my current code for main.cpp:
#include <QApplication>
#include <QWidget>
int main (int argc, char **argv){
QApplication app (argc,argv);
QWidget *w=new QWidget();
w->setStyleSheet("background-image: url(:/cover.jpg);");
w->setWindowTitle("Test");
w->show();
return app.exec();
}
After executing the code, how come the widget remains blank? Thanks in advance!
QtCreator is an IDE designed by Qt. It's just an interface.
I checked your implementation and I don't see anything wrong. It also work well on my pc. Can you check your image url or try with another image ?
Btw, if you're on linux, try removing : character after url ;
w->setStyleSheet("background-image: url(/cover.jpg);");
EDİT:
If jpg is in the same directory with your application, it should be ;
w->setStyleSheet("background-image: url(./cover.jpg);");
You can give a full path to avoid this kind of errors.
"Is it possible to add background image on QWidget without using QtCreator?"
Yes, of course it is.
QtCreator is just an IDE. You don't need to use it at all to write code using the Qt library.
Just as you can use it to write code that does not use Qt at all.

How does one split a QT(C++) UI into multiple widget subclasses and get it to display the same as all in the same class?

I'm learning QT (I already know C++ very well) and trying to get a UI to display well but I do not want to use the QT Designer that comes with QT Creator. I have the following class:
#include "MainPanel.h"
#include<QVBoxLayout>
MainPanel::MainPanel(QWidget *parent)
: QWidget(parent)
{
QLayout *lo = new QVBoxLayout(this);
mList = new QListWidget(this);
mList->addItem("Testing");
setLayout(lo);
lo->addWidget(mList);
lo->setSpacing(5);
}
The Main window class has a bunch of extra protected functions but the initControls method just does this:
void MainWindow::initControls()
{
QHBoxLayout *loMain = new QHBoxLayout(this);
loMain->addWidget(new MainPanel(this));
setLayout(loMain);
}
When I put all the code from MainPanel into MainWindow::initControls() or even in the constructor(either way), it works - shows a list widget with a single item "Testing". With the code in MainPanel though, it shows up as a very small rectangle that wouldn't fit the word "Testing" nor is there any semblance of text in there even partially.
I have tried to override sizeHint() in and move the code to create and return the list widget to a method getList() so I can access it from sizeHint too but that did nothing - I still get a small rectangle.
What am I doing wrong and what do I need to do or include to get the widget to paint properly? I have more controls I want to add to this UI (a button panel below the list widget and a detail panel on the right 2/3 of the window) but until I can get this to display, I can't possibly proceed with the rest.
I also want to do this entirely with code - not using the designer as I have vision issues and found it to be difficult to place things correctly on the form.
Someone please help - documentation and tutorials other than the documentation on QT's website is helpful if it points me to the right direction. I have already looked on QT's docs site under QWidget, QListWidget, QLayout, and QH(and V)BoxLayouts but see nothing and many of the tutorials talk about the designer.
Before someone tries to scold about creating a SSME or whatever small program - I have given you the smallest one that displays the issue - I know that putting the code all into the main window fixes it but one should never have everything in one class.
Okay, too unclear, what's happening there, we should have requested for more of your code =)
Here is the smallest possible sample, demonstrating what you should have been trying to achieve:
mainwindow.cpp:
#include "mainwindow.h"
#include "mainpanel.h"
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
{
MainPanel* p = new MainPanel(this);
setCentralWidget(p);
}
mainpanel.h:
#include "mainpanel.h"
#include <QListWidget>
#include <QLayout>
MainPanel::MainPanel(QWidget *parent)
: QWidget(parent)
{
QLayout *lo = new QVBoxLayout(this);
QListWidget* mList = new QListWidget(this);
mList->addItem("Testing");
setLayout(lo);
lo->addWidget(mList);
lo->setSpacing(5);
}
main.cpp:
#include <QApplication>
#include "mainwindow.h"
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
MainWindow w;
w.resize(400, 500);
w.show();
return app.exec();
}
Seemingly, you've tried to set a layout on QMainWindow, but it already has a built-in layout, it is exactly the case when setCentralWidget should work, leave manual layout creation for QWidget & QDialog subclasses.
The code above works fine, try it and refactor the way you want.
#MasterAler is correct that the root cause of your issue is setting a layout MainWindow. The reason for using a MainWindow is to support standard VBoxLayout of menubar, central widget, and status bar. So it makes no sense to set your own layout for a QMainWindow.
Since we didn't have your entire code, I didn't assume MainWindow was a QMainWindow. I got your code to work by making MainWindow a QDialog. This may be more of what you were originally looking for, where you want to put a widget of your own making into any container. Following is in Python (I find Python a faster prototyping environment than C++), but you can easily read it and see how to host your MainPanel is any widget (not just a MainWindow):
import sys
from PySide2.QtWidgets import QApplication, QWidget, QListWidget, QDialog, QVBoxLayout, QHBoxLayout
class MainPanel(QWidget):
def __init__(self, parent):
QWidget.__init__(self, parent)
lo = QVBoxLayout(self)
lo.setSpacing(5)
self.setLayout(lo)
mList = QListWidget(self)
mList.addItem("Testing")
lo.addWidget(mList)
class MainWindow(QDialog):
def __init__(self, parent):
QDialog.__init__(self, parent)
loMain = QHBoxLayout(self)
loMain.addWidget(MainPanel(self))
self.setLayout(loMain)
if __name__ == "__main__":
app = QApplication(sys.argv)
# Show the form
window = MainWindow(None)
window.exec_()

QT HTML5 with Menu Bar like real program

I'm working on an QT HTML5 application and I was wondering how i could add an top menu just like normal program ( with the default file, tools, help... options ).
I think that I've to change something in the html5applicationviewer.cpp, but I've got 0 knowledge of that ( I'm learning this... )
Even if you could point me a little bit in the right direction, I'm grateful. I've searched around, but found absolutely nothing about this topic ( but maybe i didn't search right... )
If you need more info, please ask.
Simplest way to add normal "desktop"-style menus to a Qt app is to use QMainWindow which has good support for menus.
Here's something to get you started. First I created the default HTML5 Qt application with Qt Creator (SDK version 5.2.1). Then I edited the main.cpp and added some lines. Result is below, original lines without comment and all added lines with comment.
#include <QApplication>
#include <QMainWindow> // added
#include <QMenuBar> // added
#include <QMenu> // added
#include <QAction> // added
#include "html5applicationviewer.h"
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
QMainWindow w; // important, viewer is in stack so w must be before it!
Html5ApplicationViewer viewer;
w.setCentralWidget(&viewer); // set viewer as the central widget
QMenu *fileMenu = w.menuBar()->addMenu("&File"); // create file menu
QAction *exitAction = fileMenu->addAction("&Exit"); // create exit action
QObject::connect(exitAction, SIGNAL(triggered()), qApp, SLOT(quit())); // make the action do something
viewer.setOrientation(Html5ApplicationViewer::ScreenOrientationAuto);
//viewer.showExpanded(); // will be shown by main window
viewer.loadFile(QLatin1String("html/index.html"));
w.show(); // show main window
return app.exec();
}

First time using Qt: How to display an image?

Noob: How to display an image
I am very new to this, just starting actually. I need to figure out how to display an image on screen.
First I tried:
Source code:
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QGraphicsScene scene;
QGraphicsView view(&scene);
QPixmap qp = QPixmap("../images/tank2.bmp");
if(qp.isNull())
{
printf("Yes its null\n");
}
else
{
QGraphicsPixmapItem item(QPixmap("../images/tank2.bmp"));
scene.addItem(&item);
}
view.show();
return a.exec();
}
from:
Qt jpg image display
it compiles and runs but doesn't show an image. returns 0, etc.
Then I just sorta messed around from there. I'm also curious about something: In Qt editor they show a file structure that doesn't exist on the disk. They have files "Headers", "Sources", and Resources whereas on the systems its just a folder "projectname" with all the files in one folder. Is this just for visual clarity?
The version of QtCreator I'm using is 2.4.1 running Qt 4.7.4 64 bit.
My eventual goal is to make a widget where a picture is a clickable icon where you select that pic and can place it on a larger screen like a tile.
Another Question: Why does Qt have things like "QString" and "QChar"? Is there something wrong with the normal c++ libraries?
If you just want to display a simple image then make a Qlabel the central widget and call setPixmap() passing it your image path
"Another Question: Why does Qt have things like "QString" and "QChar"?
Is there something wrong with the normal c++ libraries?"
Yes there is lots wrong with the normal libraries - at least for std::string.
When Qt was started there wasn't very good cross platform STL support and the standard libraries were very bad at Unicode and support for translations. QString doesthis very well - although I think a combination of modern STL and boost can probably do everything QString can do.
Almost all of the Qt types are automatically reference counted so you can pretty much ignore memory management for them AND pass them around freely. There are also some tricks Qt can do because the extra MOC compile pass means it has Java-like introspection that standard C++ doesn't.
But in general you are free to use standard C++ types (Qt: Qt classes vs. standard C++)
Tested like this, it works. Don't forget to create qrc file.
#include <QtGui/QApplication>
#include <QGraphicsScene>
#include <QGraphicsView>
#include <QGraphicsPixmapItem>
#include "mainwindow.h"
#include <stdio.h>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QGraphicsScene scene;
QGraphicsView view(&scene);
QPixmap qp = QPixmap(":/images/123.bmp");
if(qp.isNull())
{
printf("Yes its null\n");
}
else
{
printf("HAHA");
QGraphicsPixmapItem *item = new QGraphicsPixmapItem(QPixmap(":/images/123.bmp"));
scene.addItem(item);
}
view.show();
return a.exec();
}
Here are qrc file:
<RCC>
<qresource prefix="/">
<file>images/123.bmp</file>
</qresource>
</RCC>
And .pro file
QT += core gui
TARGET = testimage
TEMPLATE = app
SOURCES += main.cpp
RESOURCES += 123.qrc
I think your problem is here:
{
QGraphicsPixmapItem item(QPixmap("../images/tank2.bmp"));
scene.addItem(&item);
}
item goes out of scope before you'll actually use it.
I'm also pretty sure you meant that to use the QPixmap that you loaded earlier at the top-level scope.
Generally speaking, you want to limit your questions on SO to a single question... but to address your last question: QChar and QString allow the Qt libs to make several assumptions about strings. The most obvious of which is that QStrings have a standardized encoding.

Qt - What is meant by those lines of code

In the C++ GUI Programming with Qt 4 book, part of creating a dialog application, there was the following main.cpp file:
#include <QApplication>
#include <QDialog>
#include "ui_gotocelldialog.h"
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
Ui::GoToCellDialog ui;
QDialog *dialog = new QDialog;
ui.setupUi(dialog);
dialog->show();
return app.exec();
}
Can you just describe those lines of code?
Ui::GoToCellDialog ui;
QDialog *dialog = new QDialog;
ui.setupUi(dialog);
Thanks.
"ui_gotocelldialog.h" is a file generated automatically based on the file "gotocelldialog.ui" which contains the GUI for the dialog. Ui::GoToCellDialog::setupUi() must be called for the UI to be initialized.
Lets take a look:
Ui::GoToCellDialog ui;
This line creates an instance of GoToCellDialog. As already have been said, this class automatically generated from the gotocelldialog.ui file. The use-case is:
Open qt-designer and make the interface you want.
Save the file (in our case gotocelldialog.ui)
In your .cpp file write #include "ui_gotocelldialog.h"
Now you can use the interface you designed
PROFIT????
Next:
QDialog *dialog = new QDialog;
This line creates new instance of the QDialog class that represents simple modal window (commonly called as dialog). But your window would be empty after this line. You need to place the controls, do you? How you can do this? Lets see:
ui.setupUi(dialog);
This line uses the interface you designed in the qt-designer. It places this interface to the newly created dialog. So you can see all the controls in the window. Pretty easy as for me.
It sets up the ui described by an qt ui xml file hosted inside of a dialog window/qdialog.