I want to design a program including a pushButton and a lineEdit object in Qt with C++ that when the pushButton is clicked, it creates a label on the program and then sets its text to the written text in the lineEdit.
As you see inside void MainWindow::on_pushButton_clicked() function in the code below, I defined in my code to create an object of QLabel type and show the written text in the lineEdit but when I build and run my program, I don't see anything and it looks like the function didn't create the label. What's wrong with my code and what should I do?
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QLabel>
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::on_pushButton_clicked()
{
QLabel *label = new QLabel("Name: ", this);
label->setGeometry(10, 10, 150, 15);
label->setText(ui->lineEdit->text());
}
By the way, I'm new to Qt and that's why I accept other issues in my code. Thanks for helping.
I wish to use some of the icons in fontawesome (http://fontawesome.io/icons) in my Qt Application, I have extracted the fontawesome-webfont.ttf file into usr/share/fonts.I tried searching online but could n't find any such examples.This is a sample code I have written for extracting an image out of a Resource(not what is required) and also accessing some Qfonts that were existent in Qfont library itself.( i.e courier new in the example below).
#include "MainWindow.h"
#include "ui_MainWindow.h"
#include <QPixmap>
#include <QLabel>
#include <QHBoxLayout>
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
centralWidget = new QWidget(this);
gridLayout = new QGridLayout( centralWidget );
mylabel = new QLabel();
mylabel2= new QLabel();
font = new QFont("courier");
addresspic = new QPixmap(":/new/prefix1/address.png");
*addresspic=addresspic->scaled(50,50,Qt::KeepAspectRatio, Qt::FastTransformation);
mylabel->setPixmap(*addresspic);
mylabel2->setTextFormat(Qt::RichText);
mylabel2->setGeometry(QRect(QPoint(100,100),QSize(150, 150)));
mylabel2->setText(" ADDRESS ICON ");
gridLayout->addWidget(mylabel2);
gridLayout->addWidget(mylabel);
font->setItalic(true);
font->setPixelSize(20);
mylabel2->setFont(*font);
// gridLayout->setVerticalSpacing(1);
// gridLayout->setHorizontalSpacing(1);
this->setCentralWidget(centralWidget);
}
MainWindow::~MainWindow()
{
delete ui;
}
Thanks again
EDIT: The screenshot of error
EDIT 2: Trying G.M.'s method resulted in the following error : Any Idea why?
From https://github.com/dridk/QFontIcon download and add the qfonticon.h and qfonticon.cpp files to your project, then create the icons with the following code:
QFontIcon::addFont("/path/your/fonts/{your font}.ttf");
QIcon icon = QFontIcon::icon(0xf2b9);
{your widget}->setIcon(icon);
Example:
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QPushButton>
#include "qfonticon.h"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
QWidget *centralWidget;
QGridLayout *gridLayout;
centralWidget = new QWidget(this);
gridLayout = new QGridLayout( centralWidget );
QFontIcon::addFont("/usr/share/fonts/fontawesome-webfont.ttf");
for(int i = 0; i < 15; i++){
QIcon icon = QFontIcon::icon(0xf2b9+i);
QPushButton *b = new QPushButton();
b->setIcon(icon);
gridLayout->addWidget(b);
}
this->setCentralWidget(centralWidget);
}
MainWindow::~MainWindow()
{
delete ui;
}
More Information: https://github.com/dridk/QFontIcon
I tested it with Qt 5.7 and Qtcreator 4.2
Try loading the font explicitly with...
int fid = QFontDatabase::addApplicationFont("/usr/share/fonts/fontawesome-webfont.ttf");
You can then query the font family name(s) using...
QFontDatabase::applicationFontFamilies(fid);
In my case the above resulted in the single family name "FontAwesome". That being the case you should then be able to use the font with...
QFont f("FontAwesome");
Note: The above seems to work as far as it goes but specifying a point size for the font isn't working as expected. Not sure why as the ttf file appears to contain the requested glyph sizes.
Edit 1
The QFont as constructed above can be used like any other unicode font. So a QLabel could be created with...
QLabel label;
label.setFont(QFont("FontAwesome"));
label.setText("\uf0fe"); /* f0fe is the code point for fa-plus-square */
Note that the answer provided by #eyllanesc is probably a far better approach. I'm simply adding this edit for completeness sake.
The code below is based on this question.
But I still can't get it to work. From basic debugging I think there is something wrong with passing the filenames to the function. There is no reaction at all when I clicked on the "Print as PDF" button.
The main code is as below. If you would like to see further, feel free to ask them from me. Thanks.
Part of main.cpp
QApplication app(argc, argv);
//Get filename for all documents
QString filename = get_filename(Var_STR);
QString txt = txt_filename(filename);
QString csv = csv_filename(filename);
QString html = html_filename(filename);
//Print report in .txt, .csv and .html accordingly
heading(txt, csv, html, Var_STR, Var_INT[6], Var_INT[16], Var_INT[17]);
pp_prerinse(txt, csv, html, Var_INT[18], Var_INT[19], Var_INT[20], Var_INT[21], Var_INT[22], Var_INT[23], Var_INT[24], Var_INT[25], Var_INT[26], Var_REAL[11], Var_INT[30], Var_INT[31], Var_INT[32]);
pp_wash(txt, csv, html, Var_STR, Var_INT[33], Var_INT[34], Var_INT[35], Var_INT[36], Var_INT[37], Var_INT[38], Var_REAL[23], Var_INT[41], Var_INT[42], Var_INT[43], Var_REAL[28], Var_INT[47], Var_INT[48], Var_INT[49], Var_INT[50], Var_INT[51], Var_INT[52], Var_INT[53], Var_INT[54], Var_INT[55], Var_REAL[40]);
pp_rinse(txt, csv, html, Var_INT[59], Var_INT[60], Var_INT[61], Var_INT[62], Var_INT[63], Var_INT[64], Var_INT[65], Var_INT[66], Var_INT[67], Var_INT[68], Var_INT[69], Var_INT[70], Var_INT[71], Var_INT[72], Var_INT[73], Var_INT[74], Var_INT[75], Var_INT[76], Var_INT[77], Var_REAL[61]);
phase_prerinse(txt, csv, html, Var_STR, Var_REAL[64], Var_REAL[67], Var_REAL[70]);
wash(txt, csv, html, Var_STR, Var_REAL[73], Var_REAL[75], Var_REAL[77], Var_REAL[79], Var_REAL[81], Var_REAL[83], Var_REAL[85], Var_REAL[87], Var_REAL[89], Var_REAL[91], Var_REAL[94], Var_REAL[97]);
rinse(txt, csv, html, Var_INT[129], Var_STR);
basin_flush(txt, csv, html, Var_STR);
alarms_code(txt, csv, html, Var_REAL[100], Var_REAL[103], Var_REAL[106]);
tail(txt, csv, html);
//Report preview UI and convert .html to .pdf
QDir htmlpath = QFileInfo(html).absoluteDir();
MainWindow mainWindow((htmlpath.absolutePath())+"/"+html, filename);
mainWindow.setWindowTitle("Print Preview");
mainWindow.showMaximized();
return app.exec();
mainwindow.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QObject>
#include <QMainWindow>
#include <QWebView>
#include <QUrl>
#include <QPushButton>
#include <QString>
#include "windows.h"
#include <algorithm>
#include "qt_windows.h"
#include "qwindowdefs_win.h"
#include <ShellAPI.h>
namespace Ui
{
class MainWindow;
class QPrinter;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QString previewfile = "", QString file = "", QWidget *parent = 0);
virtual ~MainWindow();
public slots:
void buttonPrint(QString filepath);
void buttonCancel();
private:
QWebView *m_pWebView; //Preview of the report layout
QPushButton *m_button; //Print button
QPushButton *n_button; //Cancel button
QString printfile;
QString filepath;
};
#endif // MAINWINDOW_H
mainwindow.cpp
#include "stdafx.h"
#include "mainwindow.h"
#include <QPrinter>
#include <QTextDocument>
#include <QTextStream>
#include <QFile>
#include <QDir>
MainWindow::MainWindow(QString previewfile, QString file, QWidget *parent)
: QMainWindow(parent)
{
//Open html version of report
m_pWebView = new QWebView(this);
//Set position and size
m_pWebView->setGeometry(0, 0, 1000, 735);
m_pWebView->load(QUrl::fromLocalFile(previewfile));
//Create "print" button
m_button = new QPushButton("Print as PDF", this);
//Set location of button
m_button->setGeometry(QRect(QPoint(1100, 150), QSize(75, 23)));
//Print button action
connect(m_button, SIGNAL(clicked()), this, SLOT(buttonPrint(file)));
n_button = new QPushButton("Cancel", this);
n_button->setGeometry(QRect(QPoint(1100, 179), QSize(75, 23)));
connect(n_button, SIGNAL(clicked()), this, SLOT(buttonCancel()));
}
void MainWindow::buttonPrint(QString filepath)
{
QFile htmlfile(filepath+".html");
if(htmlfile.open(QIODevice::ReadOnly | QIODevice::Text))
{
QString htmlContent;
QTextStream in(&htmlfile);
htmlContent = in.readAll();
QTextDocument *document = new QTextDocument();
document->setHtml(htmlContent);
QPrinter printer(QPrinter::HighResolution);
printer.setOutputFormat(QPrinter::PdfFormat);
printer.setOutputFileName(filepath+".pdf");
document->print(&printer);
delete document;
buttonCancel();
}
}
void MainWindow::buttonCancel()
{
QApplication::quit();
}
MainWindow::~MainWindow()
{
}
I recommend you to porting from QTWebKit to QTWebEngine which use Chromium as native browser, faster and newst. Check for details:
http://doc.qt.io/qt-5/qtwebenginewidgets-qtwebkitportingguide.html
With 5.6, Qt WebKit and Qt Quick 1 will no longer be supported and are dropped from the release. Qt 5.7 integrates printsupport for browser so let's try to use Chromium:
First of all, include:
QT += webengine webenginewidgets printsupport
Now, try something like this:
// Create the webview
QWebEngineView *webView = new QWebEngineView(this);
webView->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
ui->centralWidget->layout()->addWidget(webView);
// Path to the HTML file
const QString filePath = QFileDialog::getOpenFileName(this, "Import HTML", ".", "HTML Files (*.html)");
// Check if the file exist
QFileInfo fileInfo(filePath);
if (!fileInfo.isFile()) {
qDebug() << "Warning, file not found!";
}
// Preview the HTML file
webView->load(QUrl::fromLocalFile(fileInfo.filePath()));
// How to print the page?
// Get the path to the pdf file
const QString pdfPath = QFileDialog::getSaveFileName(this, "Export to pdf", ".", "PDF Files (*.pdf)");
// Print the page in pdf format
webView->page()->printToPdf(pdfPath);
I have modified the Text Finder example which I got from a Qt Tutorial and made a Text Viewer. In this program, the user types in the address of the file and clicks the Search button. The program then displays the content of the text file. Below is my code.
text_finder.cpp:
#include "text_finder.h"
#include "ui_text_finder.h"
#include <QHBoxLayout>
#include <QFile>
#include <QTextStream>
#include <QFileDialog>
Text_Finder::Text_Finder(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::Text_Finder)
{
ui->setupUi(this);
}
Text_Finder::~Text_Finder()
{
delete ui;
}
void Text_Finder::loadFile(QFile file){ // I have to pass the file name as parameter.
QFile inputFile(file);
inputFile.open(QIODevice::ReadOnly);
QTextStream in(&inputFile);
QString line = in.readAll();
inputFile.close();
ui->read->setText(line);
QTextCursor cursor = ui->read->textCursor();
cursor.movePosition(QTextCursor::Start, QTextCursor::MoveAnchor, 1);
}
void Text_Finder::on_search_clicked()
{
// Code that gets the path from the text box.
loadFile();//Parameters not passed yet.
}
I have not yet entered the code which gets the name of the file from the address of the text box. I will have to pass the file to the loadFile() function which will enter the contents into the Text Edit in the center of the program. I want a solution to get the name of the file of which the user enters. For example, the user might enter, "/home/user/input.txt". The program should get the contents of that file and forward it to loadFile(). An solution with an explanation on how the various parts work is needed. I am using Qt Creator on Ubuntu 15.04 (Beta).
If i understand you correctly, the user types the full path or address of the file in the text box and you want to get just the name of the file out of the full path the user entered.
EDIT: I realized using 'QFileDialog' was the ideal way to get the file name. So this
is how i redesigned the whole code;
text_finder.h
#ifndef TEXT_FINDER_H
#define TEXT_FINDER_H
#include <QDialog>
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QPushButton>
#include <QLineEdit>
#include <QTextEdit>
#include <QFile>
#include <QTextStream>
#include <QFileDialog>
class Text_Finder : public QWidget{
Q_OBJECT
public:
Text_Finder(QWidget *parent = 0);
~Text_Finder();
public slots:
void on_search_clicked();
void open();
//void loadFile(QString const &filename);
private:
void loadFile(QString const &filename);
QLineEdit *txtFileName;
QTextEdit *txtFileContents;
QString fileName;
QPushButton *search;
QPushButton *openFile;
};
#endif
mainwindow.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
class MainWindow : public QMainWindow {
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
};
#endif // MAINWINDOW_H
text_finder.cpp
#include "text_finder.h"
Text_Finder::Text_Finder(QWidget *parent) : QWidget(parent) {
openFile = new QPushButton("Open File");
connect(openFile, SIGNAL(clicked()), this, SLOT(open()));
txtFileName = new QLineEdit;
search = new QPushButton("&Search");
txtFileContents = new QTextEdit;
QHBoxLayout *dialogAndViewLayout = new QHBoxLayout;
dialogAndViewLayout->addWidget(openFile);
dialogAndViewLayout->addWidget(txtFileName);
dialogAndViewLayout->addStretch();
dialogAndViewLayout->addWidget(search);
QVBoxLayout *layout = new QVBoxLayout;
layout->addLayout(dialogAndViewLayout);
layout->addWidget(txtFileContents);
connect(search, SIGNAL(clicked()), this, SLOT(on_search_clicked()));
setLayout(layout);
}
Text_Finder::~Text_Finder(){
delete txtFileName;
delete txtFileContents;
delete search;
delete openFile;
}
void Text_Finder::loadFile(QString const &filename){
QFile inputFile(filename);
inputFile.open(QIODevice::ReadWrite | QIODevice::Text);
QTextStream textStream(&inputFile);
QString contents = textStream.readAll();
inputFile.close();
txtFileContents->setPlainText(contents);
}
void Text_Finder::on_search_clicked() {
loadFile(fileName);
}
/*this slot opens a file dialog. After the file has been selected, it sets
the file to the text text edit box*/
void Text_Finder::open() {
fileName = QFileDialog::getOpenFileName(this, "Open text", "/home/",
"");
txtFileName->setText(fileName);
}
mainwindow.cpp
#include "mainwindow.h"
#include "text_finder.h"
MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent) {
Text_Finder *textFinder = new Text_Finder;
setCentralWidget(textFinder);
}
MainWindow::~MainWindow() {
}
Finally
main.cpp
#include "text_finder.h"
#include <QApplication>
int main(int argc, char **argv){
QApplication app(argc, argv);
Text_Finder *window = new Text_Finder;
window->show();
return app.exec();
}
Unless you're going to do some programmatic editing, you do not need to use QTextCursor at all.
I suggest you have a browse through the reference manual before trying to carry on since it's clear that you are not familiar with the bare-basics of the graphical widgets you're using.
If you're only reading in a file name and then displaying the contents in plain text format, this is all you need to do. (I'm assuming your filename is entered into a QLineEdit widget and ui->read is a QTextEdit widget)
void Text_Finder::loadFile(QString const &filename){ // I have to pass the file name as parameter.
QFile inputFile(filename);
inputFile.open(QIODevice::ReadOnly);
QTextStream in(&inputFile);
QString contents = in.readAll();
inputFile.close();
ui->read->setPlainText(contents);
}
void Text_Finder::on_search_clicked()
{
QString filename = ui->filename->text();
loadFile(filename);
}
EDIT:
I've created a fully-functional remake of your code, incorporating the changes I suggested. I have compiled and tested it and it is working as per your description.
Note: In the absence of your UI file, I've created the user interface manually.
text_finder.h
#ifndef TEXT_FINDER_H
#define TEXT_FINDER_H
#include <QMainWindow>
class QLineEdit;
class QTextEdit;
class Text_Finder : public QMainWindow{
Q_OBJECT
public:
Text_Finder(QWidget *parent = 0);
~Text_Finder();
public slots:
void on_search_clicked();
private:
void loadFile(QString const &filename);
QLineEdit *txtFileName;
QTextEdit *txtFileContents;
};
#endif // TEXT_FINDER_H
main.cpp
#include "text_finder.h"
#include <QApplication>
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QPushButton>
#include <QLineEdit>
#include <QTextEdit>
#include <QFile>
#include <QTextStream>
Text_Finder::Text_Finder(QWidget *parent) :
QMainWindow(parent)
{
QWidget *ui = new QWidget(this);
QHBoxLayout *hLayout = new QHBoxLayout;
txtFileName = new QLineEdit(this);
QPushButton *loadButton = new QPushButton("Load File", this);
connect(loadButton, &QPushButton::clicked, this, &Text_Finder::on_search_clicked);
hLayout->addWidget(txtFileName);
hLayout->addWidget(loadButton);
QVBoxLayout *vLayout = new QVBoxLayout(this);
vLayout->addLayout(hLayout);
txtFileContents = new QTextEdit(this);
vLayout->addWidget(txtFileContents);
ui->setLayout(vLayout);
setCentralWidget(ui);
}
Text_Finder::~Text_Finder(){
// It's not necessary to explicitly delete any widgets.
// QObject implements the Composite Pattern, which takes care of all this automatically
}
void Text_Finder::loadFile(QString const &filename){
QFile inputFile(filename);
inputFile.open(QIODevice::ReadOnly);
QTextStream in(&inputFile);
QString contents = in.readAll();
inputFile.close();
txtFileContents->setPlainText(contents);
}
void Text_Finder::on_search_clicked()
{
QString filename = txtFileName->text();
loadFile(filename);
}
int main(int argc, char **argv){
QApplication app(argc, argv);
Text_Finder w;
w.show();
return app.exec();
}
HINT for future questions: You will get better answers quicker if you include an SSCCE in your question. What I've included in this edit is a suitable example.
Basically, I want a simple pushButton with a colorful text which when pressed exits the application.
Why cant I press PushButton in this simple program. I am using QT 4.6 on Arch x86_64.
#include <QtGui/QApplication>
#include <QLabel>
#include <QPushButton>
#include<QtGui>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QMainWindow *Main=new QMainWindow;
QPushButton *button = new QPushButton(Main);
QLabel *label = new QLabel(Main);
label->setText("<h2><i>Hello</i> ""<font color=red>Qt!</font></h2>");
label->setVisible(true);
QObject::connect(button, SIGNAL(clicked()),label, SLOT(close()));
label->setAlignment(Qt::AlignCenter|Qt::AlignVCenter);
label->setWindowTitle("HelloWorld Test Program");
Main->show();
return a.exec();
}
Beside the use of a button class that will allow you to display rich text, you also need to make sure your connections are correct.
In your example, you're connecting the clicked signal of the button to the clear() slot of the label, which is non-sense.
To exit your app when the button is clicked, you need to close the main window. Here is the code to get the right connection :
QObject::connect(button, SIGNAL(clicked()),Main, SLOT(close()));
Changing this single line of code in your example is not enough, because your label is drawn on top of your button, so it's not possible to graphically click on it. You need to hide your label and put some text into your button :
button->setText("Hello");
label->setVisible(false);
Regarding the rich text feature in a QPushButton, AFAIK it is not possible to do it with a QPushButton.
UPDATE :
Here is a way to put some richtext on a QPushButton. It uses the solution described by my comment : painting a QTextDocument onto a pixmap and setting this pixmap as the button's icon.
#include <QtGui/QApplication>
#include <QLabel>
#include <QPushButton>
#include <QtGui>
#include <QTextDocument>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QMainWindow *Main=new QMainWindow;
QPushButton *button = new QPushButton(Main);
QTextDocument Text;
Text.setHtml("<h2><i>Hello</i> ""<font color=red>Qt!</font></h2>");
QPixmap pixmap(Text.size().width(), Text.size().height());
pixmap.fill( Qt::transparent );
QPainter painter( &pixmap );
Text.drawContents(&painter, pixmap.rect());
QIcon ButtonIcon(pixmap);
button->setIcon(ButtonIcon);
button->setIconSize(pixmap.rect().size());
QObject::connect(button, SIGNAL(clicked()),Main, SLOT(close()));
Main->show();
return a.exec();
}
Take a look here. Widget called QwwRichTextButton.
The QwwRichTextButton widget provides a button that can display rich text.