i am doing Qt project about displaying many texts. in detail, after 1st text display, it will close then display next file. My problem here was that just the last file displayed. all link resource paths are correct. Please help me fix me. Thanks in advance
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QFile>
#include <QTextStream>
#include <QMessageBox>
#include <QString>
#include <QStackedWidget>
#include <QTextBrowser>
#include <QStringList>
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
QStringList L;
L << ":/sample.txt" << ":/idp.txt";
foreach (QString str, L){
QFile file(str);
if (!file.open(QIODevice::ReadOnly))
QMessageBox::information(0,"error file path", file.errorString());
QString name = file.fileName();
QStringList parts = name.split("/");
QString lastBit = parts.at(parts.size()-1);
statusBar()->showMessage(lastBit);
QTextStream out(&file);
QString txt = out.readAll();
QStackedWidget *temp = new QStackedWidget();
QTextBrowser *textbrs = new QTextBrowser();
textbrs->setText(txt);
temp->addWidget(textbrs);
setCentralWidget(temp);
file.close();
}
}
MainWindow::~MainWindow()
{
delete ui;
}
Something like this:
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QFile>
#include <QTextStream>
#include <QMessageBox>
#include <QString>
#include <QStackedWidget>
#include <QTextBrowser>
#include <QStringList>
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
L << ":/sample.txt" << ":/idp.txt"; //Class member of Type QStringList
textbrs = new QTextBrowser(); //Class member of Type QTextBrowser*
ui->centralWidget->layout()->addWidget(textbrs);
timer = new QTimer(); //Class member of Type QTimer*
timer->setInterval(5000);
connect(timer,SIGNAL(timeout()),this,SLOT(slotFileAction()));
timer->start();
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::slotFileAction()
{
static int count = 0;
if(count >= L.size())
timer->stop();
QString str = L.at(count);
count++;
QFile file(str);
if (!file.open(QIODevice::ReadOnly))
QMessageBox::information(0,"error file path", file.errorString());
QString name = file.fileName();
QStringList parts = name.split("/");
QString lastBit = parts.at(parts.size()-1);
statusBar()->showMessage(lastBit);
QTextStream out(&file);
QString txt = out.readAll();
textbrs->setText(txt);
file.close();
}
Each time you will replace the old QStackedWidget by
setCentralWidget(temp);
The example to use QStackedWidget in Qt help document is following:
QWidget *firstPageWidget = new QWidget;
QWidget *secondPageWidget = new QWidget;
QWidget *thirdPageWidget = new QWidget;
QStackedWidget *stackedWidget = new QStackedWidget;
stackedWidget->addWidget(firstPageWidget);
stackedWidget->addWidget(secondPageWidget);
stackedWidget->addWidget(thirdPageWidget);
QVBoxLayout *layout = new QVBoxLayout;
layout->addWidget(stackedWidget);
setLayout(layout);
So, you should add multiple QTextBrowsers in QStackedWidget by addWidget() and use setCentralWiget() just once.
Hope helpful.
Related
In the program, I am trying to create a image player using QT. When I click a button in the UI, the program will create a image slideshow with a 2s pause. I tried to use the QTimer to such things, but failed to do so. Hence, I want to ask how to achieve my purpose by using QTimer.
Let me describe the flow of my program. When the user click a button in the main window, the sub-window showpic will be opened and then start showing each image for a pause of 2s in its qgraphsview. The images filepath are stored in the "QStringlist filenames".
mainwindow.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <QFileSystemModel>
#include "showpic.h"
#include <QBasicTimer>
#include <QTimer>
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
void display(const QString & , ShowPic* );
private slots:
void tick();
void on_pushButton_clicked();
private:
Ui::MainWindow *ui;
QFileSystemModel *model;
QString filesPath;
ShowPic *showpic;
QStringList filenames;
QStringList::const_iterator m_imageIt;
QTimer m_timer;
};
#endif // MAINWINDOW_H
showpic.h
#ifndef SHOWPIC_H
#define SHOWPIC_H
#include <QWidget>
namespace Ui {
class ShowPic;
}
class ShowPic : public QWidget
{
Q_OBJECT
public:
explicit ShowPic(QWidget *parent = 0);
~ShowPic();
private:
Ui::ShowPic *ui;
public:
void addPixmap(const QPixmap &pixmap);
};
#endif // SHOWPIC_H
main.cpp
#include "mainwindow.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MainWindow w;
w.show();
return a.exec();
}
mainwindow.cpp
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include<QFileDialog>
#include<QFileSystemModel>
#include<QStringList>
#include <QTreeView>
#include <QGraphicsScene>
#include <QTime>
#include <QThread>
#include <QDebug>
#include <iostream>
#include <QTimer>
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
filenames.append("C:\\test\\image.jpg");
filenames.append("C:\\test\\apple.jpg");
filenames.append("C:\\test\\orange.jpg");
filenames.append("C:\\test\\lemon.jpg");
filenames.append("C:\\test\\grape.jpg");
m_imageIt = filenames.begin();
m_timer.setInterval(5000);
connect(&m_timer, SIGNAL(timeout()), this, SLOT(tick()));
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::display(const QString & filename, ShowPic* showpic) {
showpic->addPixmap(filename);
}
void MainWindow::tick(){
showpic = new ShowPic();
showpic->show();
display(*m_imageIt, showpic);
m_imageIt ++;
}
/*
void timerEvent(QTimerEvent * ev) {
if (ev->timerId() == m_timer.timerId()) tick();
}*/
void MainWindow::on_pushButton_clicked()
{
/*showpic = new ShowPic();
QPixmap pixmap("C:\\test\\image.jpg");
showpic->addPixmap(pixmap);
showpic->show();*/
m_timer.start();
}
showpic.cpp
#include "showpic.h"
#include "ui_showpic.h"
#include <QThread>
ShowPic::ShowPic(QWidget *parent) :
QWidget(parent),
ui(new Ui::ShowPic)
{
ui->setupUi(this);
ui->graphicsView->setScene(new QGraphicsScene);
}
ShowPic::~ShowPic()
{
delete ui;
}
void ShowPic::addPixmap(const QPixmap &pixmap){
ui->graphicsView->scene()->addPixmap(pixmap);
}
The compiling message error:
The error has nothing to do with the timer, it is because you forgot to declare display(), tick(), and timerEvent() as part of the MainWindow:: class, so they cannot access MainWindow members.
The timer should be even easier to use than your code. First I recommend you use a QTimer instead of QBasicTimer. Then you can simply connect to its timeout() signal.
mainwindow.h
#include <QTimer>
QTimer m_timer;
mainwindow.cpp
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
...
m_imageIt = filenames.begin();
m_timer.setInterval(5000);
connect(&m_timer, SIGNAL(timeout()), this, SLOT(tick()));
}
void MainWindow::on_pushButton_clicked()
{
m_timer.start();
}
You do not need timerEvent() function at all.
I have the following code;
QStringListModel *model = new QStringListModel();
QStringList list;
ui.listViewResults->setEditTriggers(QAbstractItemView::NoEditTriggers);
ui.listViewResults->setViewMode(QListView::ListMode);
list << "A";
list << "B";
list << "C";
model->setStringList(list);
QModelIndex vIndex = model->index(0, 0);
QMap<int, QVariant> vMap = model->itemData(vIndex);
vMap.insert(Qt::BackgroundRole, QVariant(QBrush(Qt::red)));
model->setItemData(vIndex, vMap);
ui.listViewResults->setModel(model);
Yet, the color does not seem to change, any ideas? Thanks!
Use QStandartItemModel and QStandartItem if you need different background for each item. Or you can even make your own model/item subclassing QAbstractItemModel
Example of using QStandartItemModel and QStandartItem
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QStringListModel>
#include <QStandardItemModel>
#include <QListView>
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
QStandardItemModel *model = new QStandardItemModel();
QList<QStandardItem *> list;
ui->listView->setEditTriggers(QAbstractItemView::NoEditTriggers);
ui->listView->setViewMode(QListView::ListMode);
list << new QStandardItem("A");
list << new QStandardItem("B");
list << new QStandardItem("C");
model->appendColumn(list);
QModelIndex vIndex = model->index(0, 0);
QMap<int, QVariant> vMap = model->itemData(vIndex);
vMap.insert(Qt::BackgroundRole, QVariant(QBrush(Qt::red)));
model->setItemData(vIndex, vMap);
ui->listView->setModel(model);
}
MainWindow::~MainWindow()
{
delete ui;
}
I observed that through task mgr, the memory increases in steps of 4kB and 8kB, though not necessarily in this order.
Possible duplicate: Windows Task Manager shows process memory keeps growing even though there are no memory leaks
I am not sure whether this's occurring because I did not release the QTimer object, timer2. Please advise me how to stop this memory increase, and whether my guess of why it's occurring, is correct.
mainwindow.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <QtCore>
#include <QDebug>
#include <QDateTime>
#include <QFileInfo>
#include <QString>
#include <opencv/cv.h>
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#define TIMER2_VALUE 3000
#define UPDATED_IMAGE_STORAGE_PATH "E:\\QT1\\timeStampDateMod2\\TimeStampDateMod2\\updatedRefImg.JPG"
#define UPDATED_IMAGE_BACKUP_PATH "E:\\QT1\\timeStampDateMod2\\TimeStampDateMod2\\backUp\\updatedRefImg[%1].JPG"
using namespace std;
using namespace cv;
typedef struct
{
QDateTime dateTimeMod1;
QDateTime dateTimeMod2;
}tTimeMods;
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
QTimer *timer2;
tTimeMods findTimeModifiedStruct();
QDateTime findTimeModified();
void compareTimeMods(tTimeMods timeTypeFunction, QDateTime dateTimeMod2);
QString appendWithImageName(tTimeMods timeTypeFunction);
void shiftToRepository(QString pathString);
void updatedImgToRepository(QString pathString);
public slots:
void timerSlot2();
private:
Ui::MainWindow *ui;
};
#endif // MAINWINDOW_H
main.cpp
#include "mainwindow.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MainWindow w;
w.show();
return a.exec();
}
mainwindow.cpp
#include "mainwindow.h"
#include "ui_mainwindow.h"
tTimeMods timeTypeFunction, timeTypeMain;
QDateTime dateTimeMod2;
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
timeTypeMain = findTimeModifiedStruct();
timer2 = new QTimer(this);
connect(timer2, SIGNAL(timeout()), this, SLOT(timerSlot2()));
timer2->start(TIMER2_VALUE);
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::timerSlot2()
{
dateTimeMod2 = findTimeModified();
compareTimeMods(timeTypeMain, dateTimeMod2);
//delete timer2;
}
//tTimeMods findTimeModifiedStruct()
tTimeMods MainWindow::findTimeModifiedStruct()
{
QString myFileName = UPDATED_IMAGE_STORAGE_PATH;
QFileInfo info(myFileName);
/*find last date modified*/
timeTypeFunction.dateTimeMod1 = info.lastModified();
timeTypeFunction.dateTimeMod2 = info.lastModified();
qDebug()<< "dateTimeMod1: " << timeTypeFunction.dateTimeMod1.toString() << endl << "dateTimeMod2: "<< timeTypeFunction.dateTimeMod2.toString();
return(timeTypeFunction);
}
QDateTime MainWindow::findTimeModified()
{
QString myFileName = UPDATED_IMAGE_STORAGE_PATH;
QFileInfo info(myFileName);
QDateTime dateTimeMod2 = info.lastModified();
qDebug()<< "dateTimeMod2: "<< dateTimeMod2.toString();
return(dateTimeMod2);
}
void MainWindow::compareTimeMods(tTimeMods timeTypeFunction, QDateTime dateTimeMod2)
{
if(dateTimeMod2 >= timeTypeFunction.dateTimeMod1)
{
timeTypeFunction.dateTimeMod1 = dateTimeMod2;
QString pathString = appendWithImageName(timeTypeFunction);
shiftToRepository(pathString);
}
}
QString MainWindow::appendWithImageName(tTimeMods timeTypeFunction)
{
/*appending just the timeMod with the path & image name*/
QString path = QString(UPDATED_IMAGE_BACKUP_PATH).arg(timeTypeFunction.dateTimeMod1.toString());
qDebug()<< "path: " << path;
return path;
}
void MainWindow::shiftToRepository(QString pathString)
{
updatedImgToRepository(pathString);
}
void MainWindow::updatedImgToRepository(QString pathString)
{
pathString.replace(":","-");
pathString.replace(1,1,":");
qDebug()<<"pathString now: "<<pathString;
/*convert QString into char* */
QByteArray pathByteArray = pathString.toLocal8Bit();
const char *path = pathByteArray.data();
IplImage *InputImg = cvCreateImage(cvSize(640,480),IPL_DEPTH_8U,3);
InputImg = cvLoadImage(UPDATED_IMAGE_STORAGE_PATH ,CV_LOAD_IMAGE_UNCHANGED);
/*save the image*/
cvSaveImage(path,InputImg);
cvReleaseImage(&InputImg);
}
I'm not familiar with OpenCV, but it seems that these two lines cause you memory leak:
IplImage *InputImg = cvCreateImage(cvSize(640,480),IPL_DEPTH_8U,3);
InputImg = cvLoadImage(UPDATED_IMAGE_STORAGE_PATH ,CV_LOAD_IMAGE_UNCHANGED);
In the first line you are creating an object, but in the second you are assigning another object to the pointer without releasing the previous one, so the previous one gets leaked.
Is creating an image even needed, while you are going to load it?
#include <QtCore>
#include <QtGui>
#include <QLabel>
#include <QScrollArea>
#include <QScrollBar>
#include <QFileDialog>
#include"QDebug"
#include<math.h>
#include<QApplication>
QScrollArea* scrollarea = new QScrollArea;
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
ui->label->setBackgroundRole(QPalette::Base);
ui->label->setSizePolicy(QSizePolicy::Ignored, QSizePolicy::Ignored);
ui->label->setScaledContents(true);
scrollarea->setBackgroundRole(QPalette::Dark);
scrollarea->setWidget(ui->label);
setCentralWidget(scrollarea);
QImage img("D:\\picture.jpg");
ui->label->setPixmap(QPixmap::fromImage(img));
}
MainWindow::~MainWindow()
{
delete ui;
}
i am newbie in Qtcreator.
i try to add scroll bar to label. but when i run, it occurs an error:
QWidget: Must construct a QApplication before a QPaintDevice
how should i do to fix this
QScrollArea* scrollarea = new QScrollArea;
You are constructing a global QScrollArea before QApplication is created. Make it a member variable of MainWindow.
I want to download the url entered in the line edit widget.
I am not able to get it working , can some one please give me a short code snippet which can put the values of the file to a QString ?
void imdb::on_imdbGetButton_clicked()
{
Qstring link1 = ui->lineEdit2->text();
// QString link1 is the url to be downloaded.
}
I have added , the required header files..
Thanks..
I guess you're trying to download a file via http. Here's what you could do:
In you *.pro file add QT += network
Create an instance of QNetworkAccessManager class;
Supply your file URL to via QNetworkRequest object: manager->get(QNetworkRequest("file_url"));
Connect to the finished signal of the QNetworkAccessManager
In the finished signal handler read the content of the QNetworkReply and save it to the local file.
Below is a small example. Download will start in the button click of the MainForm class:
mainwindow.h:
#include <QMainWindow>
#include <QNetworkAccessManager>
#include <QDebug>
#include <QUrl>
#include <QNetworkReply>
#include <QNetworkRequest>
#include <QFile>
#include <QFileInfo>
#include <QPushButton>
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
private:
Ui::MainWindow *ui;
QNetworkAccessManager* _manager;
private slots:
void on_pushButton_clicked();
void downloadFinished(QNetworkReply *reply);
};
mainwindow.cpp:
#include "mainwindow.h"
#include "ui_mainwindow.h"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
QPushButton* button = new QPushButton("Download", this);
button->setGeometry(20, 20, 80, 30);
connect(button, SIGNAL(clicked()), SLOT(on_pushButton_clicked()));
_manager = new QNetworkAccessManager(this);
connect(_manager, SIGNAL(finished(QNetworkReply*)), SLOT(downloadFinished(QNetworkReply*)));
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::on_pushButton_clicked()
{
QUrl url("http://pics.mtii.com/ClassPictures2011/MIA/E110227-PMIA3-JEAN/thumbnails/P2270448%20copy.jpg");
_manager->get(QNetworkRequest(url));
}
void MainWindow::downloadFinished(QNetworkReply *reply)
{
QUrl url = reply->url();
if (reply->error())
{
qDebug() << "Download of " << url.toEncoded().constData()
<< " failed: " << reply->errorString();
}
else
{
QString path = url.path();
QString fileName = QFileInfo(path).fileName();
if (fileName.isEmpty()) fileName = "download";
QFile file(fileName);
if (file.open(QIODevice::WriteOnly))
{
file.write(reply->readAll());
file.close();
}
qDebug() << "Download of " << url.toEncoded().constData()
<< " succeded saved to: " << fileName;
}
}
hope this helps, regards