I have a list of textfiles in a treeview (with QFileSystemModel). If a textfile is selected and a print button is pressed. It should show a print dialog and the file should be printed out. I thought (after reading documentations and examples) it should look like this:
void berichtenhistorie::on_printButton_released()
{
QModelIndex index = ui->treeView->currentIndex();
QFileSystemModel *model = (QFileSystemModel*)ui->treeView->model();
QString path = model->filePath(index);
QString name = model->fileName(index);
QString dir = path;
dir.remove(dir.size() - name.size(), name.size());
QFile file(path);
if(file.open(QIODevice::WriteOnly | QIODevice::Text))
{
file.close();
if(file.rename(QString("%1geprint %2").arg(dir, name)))
qDebug() << "renamed";
}
//all above works correctly
QPrinter printer(QPrinter::HighResolution);
printer.setPageSize(QPrinter::A4);
printer.setOrientation(QPrinter::Portrait);
printer.setPageMargins (15,15,15,15,QPrinter::Millimeter);
printer.setFullPage(false);
printer.setOutputFileName(path);
printer.setOutputFormat(QPrinter::NativeFormat);
QPainter painter(&printer);
painter.end();
}
The renaming part (so above all the printing stuff) works as it should, no errors or anything. But I get abunch of errors at the printing error. I thought it was because of the libraries, because im using Qt5.
#include <QDirModel>
#include <QDebug>
#include <QMessageBox>
#include <QtPrintSupport/QPrintDialog>
#include <QtPrintSupport/QPrinter>
#include <QPainter>
#include <QFile>
Here are the errors:
Apparently you are using Qt5, where printing functionality has been placed in separate add on (in Qt4 it is part of QtGui module), see documentation. So you have to add to pro file this line:
QT += printsupport
This will fix your build error, but your code doesn't print yet. You have to use painter.
If you are planing to support Qt4 it should be like this
greaterThan(QT_MAJOR_VERSION, 4) {
QT += printsupport
}
Related
In my program, my users can copy a string of text from anywhere and paste it into my program. I use the simple QApplication::clipboard()->text(); function and everything works as expected. However, several of my users are having problems when trying to copy and paste on Windows 8.1
Here is how I access the clipboard text from my paste function:
QString clipboard = QApplication::clipboard()->text();
//check if the clipboard is empty
if(QApplication::clipboard()->text().isEmpty())
return;
//do something with clipboard
But if the text was copied from Notepad or Chrome, the text is ALWAYS empty. Windows 7 users have not had any problems. Not ALL Windows 8 users have this issue, it's only a handful but the issue it consistent. When copied from some other random places or within my program itself, the clipboard works fine.
I've tried using mimeData. When using the function formats(), only plain text is an available format, but the text is always empty.
The text being copied from Notepad/Chrome shows up fine in clipboard viewers and stuff and can be pasted elsewhere in other programs.
Copying and pasting is a very important feature in my program and its frustrating that my users can't copy and paste from Notepad or Chrome.
Any ideas? Thanks for your time. :)
EDIT: I tried using the "windows" style technique. There was no change. Here is my current, still unworking code:
QString clipboard = QApplication::clipboard()->text();
//check if the clipboard is empty
if(clipboard.isEmpty())
{
//might not actually be empty. Check using the other technique
if (IsClipboardFormatAvailable(CF_TEXT) && OpenClipboard(NULL))
{
HGLOBAL hGlobal = GetClipboardData(CF_TEXT) ;//hGlobal is NULL
if (hGlobal != NULL)//This never gets called because it is NULL
{
LPTSTR lpszData = (LPTSTR) GlobalLock(hGlobal) ;
if (lpszData != NULL)
{
clipboard.fromLocal8Bit((const char *)lpszData);
GlobalUnlock(hGlobal) ;
}
}
CloseClipboard() ;
}
if(clipboard.isEmpty())
return;
}
The copied text shows up fine in a clipboard viewer, but my program can't get to it no matter what:
How come GetClipboardData() isn't picking anything up? Again, the copied text CAN be pasted in any other program I've tried... just not mine. But if copied from somewhere else, it works no problem.
EDIT: With this version, When the user copies text and text gets to clipboard, a function copies the text this time to an internal text file not directly to your program, using QFile. Another function copies the text from the internal text file to your program. By this way, i think your program wouldn't have to directly deal with text in the clipboard
clipboard.h
#ifndef CLIPBOARD_H
#define CLIPBOARD_H
#include <QDialog>
#include <QClipboard>
#include <QLabel>
#include <QHBoxLayout>
#include <QTextEdit>
#include <QPushButton>
#include <QFile>
#include <QTextStream>
class ClipBoard : public QDialog {
Q_OBJECT
public:
explicit ClipBoard(QWidget *parent = 0);
~ClipBoard();
private slots:
//the functions that will copy and paste text from the text file
void copyToTextFile();
void paste();
private:
QPushButton *button;
QTextEdit *edit;
QString textFromClipBoard;
QClipboard *clipBoardText;
QString clipboard;
};
#endif // CLIPBOARD_H
clipboard.cpp
#include "clipboard.h"
#include "ui_clipboard.h"
ClipBoard::ClipBoard(QWidget *parent) : QDialog(parent) {
button = new QPushButton("&Paste Copied Text");
edit = new QTextEdit;
/*when user copies text and text gets to clipboard, the text is copied
from clipboard to a text file then copied from the text file to the
program*/
connect(button, SIGNAL(clicked()), this, SLOT(copyToNotepad()));
connect(button, SIGNAL(clicked()), this, SLOT(paste()));
QVBoxLayout *layout = new QVBoxLayout;
layout->addWidget(button);
layout->addWidget(edit);
setLayout(layout);
}
/*This function copies text from the clipboard to an internal text file
created by the program*/
void ClipBoard::copyToTextFile() {
clipboard = QApplication::clipboard()->text();
QFile output("out.txt");
if (output.open(QIODevice::ReadWrite | QFile::Truncate |
QIODevice::Text)) {
QTextStream out(&output);
out << clipboard;
}
}
/*This function then copies the text from the internal text file and pastes
it to the text edit. So the program doesn't have to deal directly with the
clipboard*/
void ClipBoard::paste() {
QFile input("out.txt");
if (input.exists()) {
if (input.open(QIODevice::ReadOnly | QIODevice::Text)) {
QTextStream in(&input);
clipboard = in.readAll();
}
}
edit->setText(clipboard);
}
ClipBoard::~ClipBoard() {
}
main.cpp
#include "clipboard.h"
#include <QApplication>
int main(int argc, char *argv[]) {
QApplication a(argc, argv);
ClipBoard w;
w.show();
return a.exec();
}
Look through and compare with your part of the code to see if there's something you did wrong. But as to how you claim it works on some Windows 8.1 systems and don't on others baffles me.
I had similar issue,
the solution for me is sleep.
void MainWindow::on_clipboard_change(){
QThread::msleep(1); //without this line I get allways empty clipboard
QString text = QGuiApplication::clipboard()->text();
qDebug() << "clipboard change event triggered ( " << text << " )";
}
I am developing a system and for the GUI I preferred to use QT plug in for VisStudio 2012. I used a file browser once the browse button is pressed everything works fine and I select my file. Right after the process with my file is completed, another file browser pops up... Can you help me? Here is the code:
#include "istorm__v3.h"
#include <QFileDialog>
#include <QMessageBox>
#include "ui_istorm__v3.h"
#include "iStormParser.h"
using namespace std;
iStormParser * isp;
iSTORM__v3::iSTORM__v3(QWidget *parent)
: QMainWindow(parent)
{
isp=new iStormParser();
ui.setupUi(this);
//ui.pushButton->setAutoDefault(false);
connect(ui.pushButton, SIGNAL(ui.pushButton.clicked()), this, SLOT(ui.on_pushButton_clicked()));
}
iSTORM__v3::~iSTORM__v3()
{
}
void iSTORM__v3::on_pushButton_clicked()
{
QString filename = QFileDialog::getOpenFileName(this,
tr("Choose File"),
"D:\\Desktop\\iSTORM__v3\\iSTORM__v3\\",
"C Files (*.c);;H Files (*.h)");
string tmp=filename.toUtf8().constData();
unsigned found = tmp.find_last_of("/\\");
tmp=tmp.substr(found+1);
string data=isp->run("\\testFiles\\"+tmp);
ui.textEdit->setText( QString::fromStdString(data));
return;
}
This issue would probably happen if you either connect the slot to the corresponding signal twice, or you emit the same signal again in your slot invokation, or at least "quickly" somewhere after having the slot quit that would bring this user experience.
I looked at some examples and decided to implement one of them. It compiles and doesn't crash when ran, however It doesn't create the pdf, it throws some error (which I do not understand). The question is where there error is and how can it be removed?
The project code:
#-------------------------------------------------
#
# Project created by QtCreator 2013-06-08T10:07:11
#
#-------------------------------------------------
QT += core
QT -= gui
QT += printsupport
TARGET = PDFPrintMaybe
CONFIG += console
CONFIG -= app_bundle
TEMPLATE = app
SOURCES += main.cpp
And the source itself:
#include <QTextDocument>
#include <QPrinter>
#include <QApplication>
int main( int argc, char **argv )
{
QApplication app( argc, argv );
QTextDocument doc;
doc.setHtml( "<p>A QTextDocument can be used to present formatted text "
"in a nice way.</p>"
"<p align=center>It can be <b>formatted</b> "
"<font size=+2>in</font> <i>different</i> ways.</p>"
"<p>The text can be really long and contain many "
"paragraphs. It is properly wrapped and such...</p>" );
QPrinter printer;
printer.setOutputFileName("C:\\Users\\SameTime\\Desktop");
printer.setOutputFormat(QPrinter::PdfFormat);
doc.print(&printer);
printer.newPage();
return 0;
}
And finally, the error itself:
QPainter:: begin(): Returned false
"C:\\Users\\SameTime\\Desktop"
probably refers to the existing folder, not a file name.
You should specify your pdf file name instead, like
"C:\\Users\\SameTime\\Desktop\\1.pdf"
And make sure that path to the file exists and accessible.
Otherwise, sustem would not be able to crate pdf and print (i.e. paint on the pdf canvas)
I have the code below. I am using Qt_5_0_2_MSVC2012_64bit-Release. I am not able to read the file. I get the debug error message of "Cannot open file for reading".There is some problem for me with resource files. Any idea how I can fix it? Thanks!
#include <QCoreApplication>
#include <QFile>
#include <QString>
#include <QDebug>
#include <QTextStream>
#include <QResource>
#include <QIODevice>
void Read(QString Filename){
QFile mFile(Filename);
if(!mFile.open(QFile::ReadOnly | QFile::Text)){
qDebug() << "could not open file for read";
return;
}
QTextStream in(&mFile);
QString mText = in.readAll();
qDebug() << mText;
mFile.close();
}
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
Read(":/MyFiles/myfile.txt");
return a.exec();
}
I had same problem. The Error string was "Unknown error". Solution was to add INCLUDEPATH += . from #gatto's answer and run commands from menu:
1. Build -> Clean all
2. Build -> Run qmake
3. Build -> Rebuild All
test.pro:
TEMPLATE = app
TARGET = test
INCLUDEPATH += .
# Input
SOURCES += main.cpp
RESOURCES += test.qrc
test.qrc:
<!DOCTYPE RCC><RCC version="1.0">
<qresource>
<file>MyFiles/myfile.txt</file>
</qresource>
</RCC>
main.cpp is from your question. Works fine.
That said, if you still have the problem, you should post minimal Qt project (including .pro and .qrc files), that has the error.
I have tried to write some code to print a pdf file using Qt but somehow it's not working.
If anybody has any idea to solve this problem, please provide your tips.
void ChartViewer::onprintBtnClicked(){
String filename = QFileDialog::getOpenFileName(this,"Open File",QString(),"Pdf File(*.pdf)");
qDebug()<<"Print file name is "<<filename;
if(!filename.isEmpty()) {
if(QFileInfo(filename).suffix().isEmpty())
filename.append(".pdf");
QPrinter printer(QPrinter::HighResolution);
printer.setOutputFormat(QPrinter::PdfFormat);
printer.setOutputFileName(filename);
QPrintDialog*dlg = new QPrintDialog(&printer,this);
if(textedit->textCursor().hasSelection())
dlg->addEnabledOption(QAbstractPrintDialog::PrintSelection);
dlg->setWindowTitle(tr("Print Document"));
if(dlg->exec() == QDialog::Accepted) {
textedit->print(&printer);
}
delete dlg;
}
}
I didn't understand your question, but now I get it. You want to print PDF file using Qt, you don't want to print into PDF, right?
Qt does not have support for loading and display PDF.
For PDF support in Qt you need external library poppler. Check this article.
Poppler allows you to render PDF files into QImage and you can easily print QImage
like this.
Here is how do you print text into PDF file.
I tried to edit your code so that I can test it a bit and it works for me, can you check?
Maybe try to check if QPrinter::isValid() returns true in your environment.
#include <QtGui>
#include <QtCore>
int main(int argc, char **argv) {
QApplication app(argc, argv);
QTextEdit parent;
parent.setText("We are the world!");
parent.show();
QString filename = QFileDialog::getOpenFileName(&parent,"Open File",QString(),"Pdf File(*.pdf)");
qDebug()<<"Print file name is "<<filename;
if(!filename.isEmpty()) {
if(QFileInfo(filename).suffix().isEmpty()) {
filename.append(".pdf");
}
QPrinter printer(QPrinter::HighResolution);
printer.setOutputFormat(QPrinter::PdfFormat);
printer.setOutputFileName(filename);
QPrintDialog*dlg = new QPrintDialog(&printer,&parent);
dlg->setWindowTitle(QObject::tr("Print Document"));
if(dlg->exec() == QDialog::Accepted) {
parent.print(&printer);
}
delete dlg;
}
return app.exec();
}