I'm new in Qt. I have got Class TicTacToeWidget which stores QList with QPushButton.
int m_size is initialized with 3 and works fine and i see 3x3 board, but when i try to change m_size in main.cpp to other value nothing happends. I can't find out why it doesn't work.
#ifndef TICTACTOEWIDGET_H
#define TICTACTOEWIDGET_H
#include <QWidget>
class QPushButton;
class TicTacToeWidget : public QWidget
{
Q_OBJECT
public:
TicTacToeWidget(QWidget *parent = 0);
~TicTacToeWidget();
int size()const;
void resizeBoard(int m);
private:
QList<QPushButton *> m_board;
int m_size;
void setupBoard(int m);
void clearBoard();
};
#endif // TICTACTOEWIDGET_H
And implementation
#include "tictactoewidget.h"
#include <QMessageBox>
#include <QGridLayout>
#include <QPushButton>
#include <QDebug>
TicTacToeWidget::TicTacToeWidget(QWidget *parent)
: QWidget(parent),m_size(3)
{
setupBoard(3);
}
TicTacToeWidget::~TicTacToeWidget()
{
}
int TicTacToeWidget::size() const
{
return m_size;
}
void TicTacToeWidget::resizeBoard(int m)
{
setupBoard(m);
}
void TicTacToeWidget::setupBoard(int m)
{
QGridLayout *gridLayout= new QGridLayout;
m_size=m;
m_board.clear();
for(int i=0;i<m_size;i++)
{
for(int j=0;j<m_size;j++)
{
QPushButton *button= new QPushButton;
button->setSizePolicy(QSizePolicy::Minimum,QSizePolicy::Minimum);
button->setText(" ");
gridLayout->addWidget(button,i,j);
}
}
setLayout(gridLayout);
}
void TicTacToeWidget::clearBoard()
{
for(auto &it:m_board)
{
this->layout()->removeWidget(it);
}
m_board.clear();
}
And main
#include "tictactoewidget.h"
#include <QApplication>
using namespace std;
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
TicTacToeWidget w;
w.resizeBoard(5);
w.show();
return a.exec();
}
http://doc.qt.io/qt-4.8/qwidget.html#setLayout
If there already is a layout manager installed on this widget, QWidget won't let you install another. You must first delete the existing layout manager
Related
Using QTCreator, I created the design of a GUI Application. I want to read the input entered by the user from lineEdit and when pushButton is clicked, it should print the factorial of that entered number on the same page. I've read some tutorials but don't understand how to code this using qtc++.
A minimal example is like that:
mainwindow.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QWidget>
#include <QLineEdit>
#include <QPushButton>
#include <QHBoxLayout>
class MainWindow : public QWidget
{
Q_OBJECT
public:
MainWindow(QWidget *parent = nullptr);
~MainWindow();
private slots:
void hClicked();
void hTextEdit(const QString& data);
private:
QString m_linedata;
QPushButton button;
QLineEdit lineEdit;
QHBoxLayout layout;
};
#endif // MAINWINDOW_H
mainwindow.cpp
#include "mainwindow.h"
#include <iostream>
MainWindow::MainWindow(QWidget *parent)
: QWidget(parent)
{
layout.addWidget(&lineEdit);
layout.addWidget(&button);
this->setLayout(&layout);
connect(&lineEdit, &QLineEdit::textChanged, this, &MainWindow::hTextEdit);
connect(&button, &QPushButton::clicked, this , &MainWindow::hClicked);
}
MainWindow::~MainWindow()
{
}
static unsigned factorial(unsigned n)
{
unsigned result = 1;
for (unsigned i=1; i <= n; i++) {
result *= i;
}
return result;
}
void MainWindow::hClicked()
{
if (m_linedata.size() > 0) {
bool res ;
int toint = m_linedata.toInt(&res);
if (res) {
unsigned fact_result = factorial(toint);
lineEdit.clear();
lineEdit.setText(QString::number(fact_result)); }
}
}
void MainWindow::hTextEdit(const QString &data)
{
m_linedata = data;
}
and main.cpp
#include "mainwindow.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MainWindow w;
w.show();
return a.exec();
}
Just do anything you like with the data passed to the auxillary buffer.
I tried to make tictactoe game using Qt and Qgraphicsview but when I draw x on board using Graphicstextitem in mousePressEvent , X does not appear. how fix that ?
I think the problem is that scene of textitem Different from scene of main file but I do not know how fix that.
main.cpp:
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
Game *gm = new Game;
Game *rect1=new Game;
gm->scenc->setSceneRect(0,0,800,600);
rect1->setRect(160,100,150,150);
gm->scenc->addItem(rect1);
gm->view->setScene(gm->scenc);
gm->view->show();
return a.exec();
}
in game.cpp:
#include <game.h>
Game::Game()
{
scenc= new QGraphicsScene;
view = new QGraphicsView;
text= new QGraphicsTextItem;
}
void Game::mousePressEvent(QGraphicsSceneMouseEvent *event)
{
if (event->buttons() == Qt::LeftButton )
{
text->setPlainText("X");
text->setFont(QFont("Tahoma",24));
text->setPos((160+160+120)/2,140);
scenc->addItem(text);
}
}
in game.h :
class Game : public QObject , public QGraphicsRectItem
{
Q_OBJECT
public:
Game();
QGraphicsScene *scenc;
QGraphicsView *view;
QGraphicsTextItem *text;
void mousePressEvent(QGraphicsSceneMouseEvent *event);
};
The following example illustrates how to do it the right way. Firstly, you have to notice, that Game::mousePressEvent doesn't override any virtual function. It's a good habit to use the override keyword and to drop the virtual keyword in order to be sure, that a virtual function is overwritten.
Game is not derived from QGraphicsScene and has therefore no mousePressEvent member.
Try the following example app.
MyScene.h
#pragma once
#include <QWidget>
#include <QDebug>
#include <QHBoxLayout>
#include <QGraphicsScene>
#include <QGraphicsView>
#include <QGraphicsTextItem>
#include <QGraphicsSceneMouseEvent>
class MyScene : public QGraphicsScene {
Q_OBJECT
public:
MyScene(QWidget* parent = nullptr) : QGraphicsScene(parent) {
setSceneRect(0, 0, 800, 600);
}
void mouseDoubleClickEvent(QGraphicsSceneMouseEvent* mouseEvent) override {
if (mouseEvent->buttons() == Qt::LeftButton)
{
auto text = new QGraphicsTextItem;
addItem(text);
text->setPlainText("X");
text->setPos(mouseEvent->scenePos());
}
}
private:
QGraphicsView* mView;
QGraphicsTextItem* mText;
};
main.cpp
#include <QApplication>
#include <QGraphicsScene>
#include <QGraphicsView>
#include <QGraphicsTextItem>
#include "MyScene.h"
int main(int argc, char* argv[])
{
QApplication a(argc, argv);
auto scene = new MyScene;
auto view = new QGraphicsView;
view->setScene(scene);
view->show();
return a.exec();
}
I'm trying to create a program that accepts images through drag and drop and shows those images on my UI, then I want to rename them and save them.
I got the drag and drop to work, but I have some issues with my Image placement and I can't seem to find where I'm making my mistake.
In the image you see my UI during runtime, in the top left you can see a part of the image I dragged into the green zone(this is my drag and drop zone that accepts images). The position I actually want it to be in should be the red square. The green zone is a Dynamic created object called Imagehandler that I created to handle the drag and drop of the images. The Red square is my own class that inherits from QLabel, I called it myiconclass. This class should hold the actual image data.
I think my mistake has to do with the layouts, but I can't see it.
Could I get some help with this please?
Imagehandler.h
#ifndef IMAGEHANDLER_H
#define IMAGEHANDLER_H
#include <QObject>
#include <QWidget>
#include <QLabel>
#include <QDrag>
#include <QDragEnterEvent>
#include <QMimeData>
#include <QList>
#include <QDebug>
//this class is designed to help me take in the images with drag and drop
class ImageHandler : public QWidget
{
Q_OBJECT
public:
explicit ImageHandler(QWidget *parent = nullptr);
QList<QImage> getImageListMemory() const;
void setImageListMemory(const QList<QImage> &value);
QList<QUrl> getUrlsMemory() const;
void setUrlsMemory(const QList<QUrl> &value);
private:
//QWidget Icon;
QLabel Icon;
QList <QImage> imageListMemory;
QList <QUrl> urlsMemory;
protected:
void dragEnterEvent(QDragEnterEvent * event);
void dragLeaveEvent(QDragLeaveEvent * event);
void dragMoveEvent(QDragMoveEvent * event);
void dropEvent(QDropEvent * event);
signals:
void transferImageSignal(QList <QImage>);
public slots:
};
#endif // IMAGEHANDLER_H
mainwindow.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <QImageReader>
#include <QList>
#include <QWidget>
#include <QLabel>
#include <myiconclass.h>
#include <imagehandler.h>
#include <QGridLayout>
#include <QDebug>
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
QList<QImage> getImageListMemory() const;
void setImageListMemory(const QList<QImage> &value);
private:
Ui::MainWindow *ui;
QLabel Icon;
QList <QImage> imageListMemory;
QList <QUrl> urlsMemory;
QList<QWidget *> labelList;
ImageHandler * ImageHandlerMemory;
QGridLayout * grid2;
QList <MyIconClass *> memory;
signals:
public slots:
void setIconSlot(QList <QImage>);
};
#endif // MAINWINDOW_H
myiconclass.h
#ifndef MYICONCLASS_H
#define MYICONCLASS_H
#include <QWidget>
#include <QLabel>
//this class is based on a Qlabel and is only made so it can help me with the actual images, gives me more members if I need it
class MyIconClass : public QLabel
{
Q_OBJECT
public:
explicit MyIconClass(QWidget *parent = nullptr);
int getMyNumber() const;
void setMyNumber(int value);
private:
int myNumber;
signals:
public slots:
};
#endif // MYICONCLASS_H
imagehandler.cpp
#include "imagehandler.h"
ImageHandler::ImageHandler(QWidget *parent) : QWidget(parent)
{
setAcceptDrops(true);
}
QList<QImage> ImageHandler::getImageListMemory() const
{
return imageListMemory;
}
void ImageHandler::setImageListMemory(const QList<QImage> &value)
{
imageListMemory = value;
}
QList<QUrl> ImageHandler::getUrlsMemory() const
{
return urlsMemory;
}
void ImageHandler::setUrlsMemory(const QList<QUrl> &value)
{
urlsMemory = value;
}
void ImageHandler::dragEnterEvent(QDragEnterEvent * event)
{
event->accept();
}
void ImageHandler::dragLeaveEvent(QDragLeaveEvent * event)
{
event->accept();
}
void ImageHandler::dragMoveEvent(QDragMoveEvent * event)
{
event->accept();
}
void ImageHandler::dropEvent(QDropEvent * event)
{
QList <QImage> imageList2;
QList <QUrl> urls;
QList <QUrl>::iterator i;
urls = event->mimeData()->urls();
//imageList.append(event->mimeData()->imageData());
foreach (const QUrl &url, event->mimeData()->urls())
{
QString fileName = url.toLocalFile();
qDebug() << "Dropped file:" << fileName;
qDebug()<<url.toString();
QImage img;
if(img.load(fileName))
{
imageList2.append(img);
}
}
emit transferImageSignal(imageList2);
this->setUrlsMemory(urls);
this->setImageListMemory(imageList2);
}
mainwindow.cpp
#include "mainwindow.h"
#include "ui_mainwindow.h"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
ImageHandler * handler = new ImageHandler(this);
handler->show();
QGridLayout *grid = new QGridLayout;
grid->addWidget(handler, 0, 0);
ui->groupBoxIcon->setLayout(grid);
ImageHandlerMemory = handler;
//connect(handler,SIGNAL(handler->transferImageSignal(QList <QUrl>)),this,SLOT(setIconSlot(QList <QUrl>)));
connect(handler,SIGNAL(transferImageSignal(QList<QImage>)),this,SLOT(setIconSlot(QList<QImage>)));
}
MainWindow::~MainWindow()
{
delete ui;
}
QList<QImage> MainWindow::getImageListMemory() const
{
return imageListMemory;
}
void MainWindow::setImageListMemory(const QList<QImage> &value)
{
imageListMemory = value;
}
void MainWindow::setIconSlot(QList<QImage> images)
{
printf("succes!");
this->setImageListMemory(images); //save the images to memory
QGridLayout *grid = new QGridLayout; //create the grid layout I want my images to be in
// create counters to remember the row and column in the grid
int counterRow =0;
int counterColumn =0;
int counter3 =0;
int counterImages = 0;
//iterate over each image in the list
QList <QImage>::iterator x;
for(x = imageListMemory.begin(); x != imageListMemory.end(); x++)
{
MyIconClass * myLabel = new MyIconClass(this); //create an object of my own class (which is a Qlabel with an int member)
QPixmap pixmap(QPixmap::fromImage(*x)); //create a pixmap from the image in the iteration
myLabel->setPixmap(pixmap); //set the pixmap on my label object
myLabel->show();
memory.append(myLabel); //add it to the memory so I can recal it
counterImages++;
}
while(counter3 < images.count())
{
grid2->addWidget(memory.value(counter3), counterRow, counterColumn);
counterColumn++;
counter3++;
if(counterColumn >= 5)
{
counterRow++;
counterColumn =0;
}
}
if(ImageHandlerMemory->layout() == 0)
{
ImageHandlerMemory->setLayout(grid2);
}
}
myiconclass.cpp
#include "myiconclass.h"
MyIconClass::MyIconClass(QWidget *parent) : QLabel(parent)
{
}
int MyIconClass::getMyNumber() const
{
return myNumber;
}
void MyIconClass::setMyNumber(int value)
{
myNumber = value;
}
As Benjamin T said I had to change this:
MyIconClass * myLabel = new MyIconClass(this);
into this:
MyIconClass * myLabel = new MyIconClass(ImageHandlerMemory);
Thanks Benjamin!
PS, I also had to add this line in my mainwindow constructor:
grid2 = new QGridLayout;
I have created a simple calculator in Qt , however I am trying to add a button to do me a factorial but its not working
can someone help me with it ?
I already have a method factorial implemented
#include "mainwindow.h"
#include <QtCore/QCoreApplication>
QString value="",total="";
double fNum,sNum;
bool addBool=false, substractBool=false, multiplyBool=false, divideBool=false,Factorbool=false;
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent)
{
label=new QLabel("0",this);
label->setGeometry(QRect(QPoint(75,25),QSize(50,200)));
clear_button=new QPushButton("C",this);
clear_button->setGeometry(QRect(QPoint(50,300),QSize(50,50)));
connect(clear_button,SIGNAL(released()),this,SLOT(clear()));
equals_button=new QPushButton("=",this);
equals_button->setGeometry(QRect(QPoint(100,300),QSize(50,50)));
connect(equals_button,SIGNAL(released()),this,SLOT(equals()));
add_button=new QPushButton("+",this);
add_button->setGeometry(QRect(QPoint(200,150),QSize(50,50)));
connect(add_button,SIGNAL(released()),this,SLOT(add()));
Factor_button =new QPushButton("n!",this);
Factor_button->setGeometry(QRect(QPoint(250,150),QSize(50,50)));
connect(Factor_button ,SIGNAL(released()),this,SLOT(add()));
substract_button=new QPushButton("-",this);
substract_button->setGeometry(QRect(QPoint(200,200),QSize(50,50)));
connect(substract_button,SIGNAL(released()),this,SLOT(substract()));
multiply_button=new QPushButton("X",this);
multiply_button->setGeometry(QRect(QPoint(200,250),QSize(50,50)));
connect(multiply_button,SIGNAL(released()),this,SLOT(multiply()));
divide_button=new QPushButton("/",this);
divide_button->setGeometry(QRect(QPoint(200,300),QSize(50,50)));
connect(divide_button,SIGNAL(released()),this,SLOT(divide()));
for(int i=0;i<10;i++){
QString digit=QString::number(i);
buttons[i]=new QPushButton(digit,this);
connect(buttons[i],SIGNAL(released()),this,SLOT(buttonPushed()));
}
setGeo();
}
void MainWindow::setGeo()
{
for(int i=0;i<1;i++)
{
buttons[i]->setGeometry(QRect(QPoint(50,300),QSize(50,50)));
}
for(int i=0;i<4;i++)
{
buttons[i]->setGeometry(QRect(QPoint(50*i,250),QSize(50,50)));
}
for(int i=4;i<7;i++)
{
buttons[i]->setGeometry(QRect(QPoint(50*(i-3),200),QSize(50,50)));
}
for(int i=7;i<10;i++)
{
buttons[i]->setGeometry(QRect(QPoint(50*(i-6),150),QSize(50,50)));
}
}
void MainWindow::buttonPushed()
{
QPushButton *button=(QPushButton *)sender();
emit numberEnitted(button->text()[0].digitValue());
value+=QString::number(button->text()[0].digitValue());
label->setText(value);
}
void MainWindow::clear(){
value="";
label->setText(value);
}
void MainWindow::add(){
fNum=value.toDouble();
value="";
label->setText(value);
addBool=true;
}
int factorial( int n)
{
if (n == 0)
return 1;
return n * factorial(n - 1);
}
void MainWindow::equals(){
sNum=value.toDouble();
if(addBool){
total=QString::number(fNum+sNum);
label->setText(total);
}
if(substractBool){
total=QString::number(fNum-sNum);
label->setText(total);
}
if(multiplyBool){
total=QString::number(fNum*sNum);
label->setText(total);
}
if(divideBool){
total=QString::number(fNum/sNum);
label->setText(total);
}
if(Factorbool)
{
total=QString::number(factorial(fNum));
label->setText(total);
}
}
void MainWindow::substract(){
fNum=value.toDouble();
value="";
label->setText(value);
substractBool=true;
}
void MainWindow::multiply(){
fNum=value.toDouble();
value="";
label->setText(value);
multiplyBool=true;
}
void MainWindow::divide(){
fNum=value.toDouble();
value="";
label->setText(value);
divideBool=true;
}
void MainWindow::Factor(){
fNum=value.toDouble();
value="";
label->setText(value);
Factorbool=true;
}
MainWindow::~MainWindow()
{
}
The Main
#include "mainwindow.h"
#include <QApplication>
#include <QDesktopWidget>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MainWindow w;
w.showMaximized();
w.setFixedSize(300,400);
w.move(QApplication::desktop()->screen()->rect().center()-w.rect().center());
w.show();
return a.exec();
}
The .h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <QPushButton>
#include <QLabel>
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
signals:
void numberEnitted(int number);
private slots:
void clear();
void add();
void equals();
void substract();
void multiply();
void divide();
void Factor();
void buttonPushed();
void setGeo();
private:
QLabel *label;
QPushButton *clear_button;
QPushButton *add_button;
QPushButton *equals_button;
QPushButton *substract_button;
QPushButton *multiply_button;
QPushButton *Factor_button;
QPushButton *divide_button;
QPushButton *zero_button;
QPushButton *buttons[10];
};
#endif
I am awaiting your help :)
The signal that is fired when you press the Factor_button is not connected to the correct slot.
This line
connect(Factor_button, SIGNAL(released()), this, SLOT(add()));
should be
connect(Factor_button, SIGNAL(released()), this, SLOT(Factor()));
This question already has an answer here:
Qt/C++ Convert QString to Decimal
(1 answer)
Closed 8 years ago.
I am trying to make a program that takes 3 user inputs and a calculate button that puts them all into an equation and prints out the answer. The problem I am having right now is that the inputs seem to not be able to convert to numbers and I can't figure out why.
Error reads on line (int numN0 = QString::number(N0);):
error: no matching function for call to 'QString::number(QString&)'
Here's my code:
Header
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
private slots:
void on_NtButton_clicked();
void on_N0Button_clicked();
void on_kButton_clicked();
void on_tButton_clicked();
void on_quitButton_clicked();
void on_pushButton_5_clicked();
void on_equation_linkActivated(const QString &link);
private:
Ui::MainWindow *ui;
int N;
int N0;
int k;
int t;
};
Main.cpp
#include "mainwindow.h"
#include <QApplication>
#include <QPushButton>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
/*QPushButton *button = new QPushButton("Quit the program!");
QObject::connect(button, SIGNAL(clicked()), &app, SLOT(quit()));
button->show();
*/
MainWindow w;
w.show();
return a.exec();
}
mainwindow.cpp
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QtCore>
#include <QtGui>
#include <QMessageBox>
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::on_N0Button_clicked()
{
QString N0 = ui->lineEdit_2->text();
int numN0 = QString::number(N0);
if (numN0 < 1000){
QMessageBox::information(this,"Error","Can't be over 1000");
}
if (ui->lineEdit_2->text() > 0)
{
QMessageBox::information(this,"Error","Can't be under 0");
}
}
void MainWindow::on_kButton_clicked()
{
int k = ui->lineEdit_3->text();
if (QString::number(k) > 1)
{
QMessageBox::information(this,"Error","Can't be over 1");
}
if (ui->lineEdit_3->text() < 0)
{
QMessageBox::information(this,"Error","Can't be under 0");
}
}
void MainWindow::on_tButton_clicked()
{
QString t = ui->lineEdit_4->text();
}
void MainWindow::on_pushButton_5_clicked()
{
for (int x = 0; x < t; x++)
{
int ans = N*x == N0*10^(k*x);
ui->equation->setText(QString::number(ans));
}
}
You should use:
QString N0 = ui->lineEdit_2->text();
int numN0 = N0.toInt();
QString::number(N0) takes int and return QString, but you need conversion to int. Also you can use bool ok if you want to know is conversion was successful.
For example:
QString str = "FF";
bool ok;
int hex = str.toInt(&ok, 16); // hex == 255, ok == true
int dec = str.toInt(&ok, 10); // dec == 0, ok == false
Information