How can I delete a value from a cell in a QTableView?
I created a QTableView but if I press the cancel button of the keyboard on the selected cell nothing happens.
If I want to delete that value I have to double-click the cell and press cancel but I want to delete the value without the double-click, just selecting the cell and press Canc.
Is keyEvent->key() useful?
#Chernobyl
MAINWINDOW.H
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <QKeyEvent>
#include <QTableView>
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0) ;
~MainWindow();
QTableView *griglia;
protected:
bool eventFilter(QObject *obj, QEvent *event);
private:
Ui::MainWindow *ui;
};
#endif // MAINWINDOW_H
MAINWINDOW.CPP
#include "mainwindow.h"
#include "ui_mainwindow.h"
MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent),ui(new Ui::MainWindow)
{
ui->setupUi(this);
qApp->installEventFilter(this);
}
bool MainWindow::eventFilter(QObject *obj, QEvent *event)
{
if(obj == griglia && event->type() == QEvent::KeyPress)
{
QKeyEvent *keyEvent = static_cast<QKeyEvent *>(event);
if(keyEvent->key() == Qt::Key_Cancel)
{
QModelIndex in =griglia->currentIndex();
griglia->model()->setData(in," ");
}
}
return QObject::eventFilter(obj, event);
}
MainWindow::~MainWindow()
{
delete ui;
}
MAIN.CPP
#include "mainwindow.h"
#include "itemdelegate.h"
#include "mymodel.h"
#include <QApplication>
#include <QtGui>
#include <QtCore>
#include <QtWidgets>
#include <QFile>
#include <QString>
#include <QTextStream>
#include <QIdentityProxyModel>
#include <QRegExpValidator>
#define GRIGLIA_RX "^[F0-9]|1[0-9]|2[0-4]$"
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QFile styleFile( "style.qss" );
styleFile.open( QFile::ReadOnly );
QString style( styleFile.readAll() );
a.setStyleSheet( style );
QWidget *mainWindow = new QWidget;
QStandardItemModel *model = new QStandardItemModel(48,33);
QTableView *griglia = new QTableView;
griglia->setModel(model);
QPushButton *calcola = new QPushButton;
calcola->setText("CALCOLA");
QVBoxLayout *layout = new QVBoxLayout;
layout->addWidget(griglia);
layout->addWidget(calcola);
mainWindow->setLayout(layout);
ItemDelegate *itDelegate = new ItemDelegate;
griglia->setItemDelegate(itDelegate);
mainWindow->showMaximized();
return a.exec();
}
I added QDebug line but if I press Canc no message appears
Use next event filter as in my example or reimplement keyPressEvent:
bool MainWindow::eventFilter(QObject *obj, QEvent *event)
{
if(obj == ui->tableView && event->type() == QEvent::KeyPress)
{
QKeyEvent *keyEvent = static_cast<QKeyEvent *>(event);
if(keyEvent->key() == Qt::Key_Shift)
{
qDebug() << "works";
QModelIndex in = ui->tableView->currentIndex();
ui->tableView->model()->setData(in,"");
//ui->tableView->model()->setData(ui->tableView->currentIndex(),""); //or just this
}
}
return QObject::eventFilter(obj, event);
}
To use eventFilter you should also:
protected:
bool eventFilter(QObject *obj, QEvent *event);//in header
and
qApp->installEventFilter(this);//in constructor
You can use Qt::Key_Shift or Qt::Key_Cancel or something else.
EDIT
MAINWINDOW.H
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <QKeyEvent>
#include <QTableView>
#include "itemdelegate.h"
#include "mymodel.h"
#include <QApplication>
#include <QtGui>
#include <QtCore>
#include <QtWidgets>
#include <QFile>
#include <QString>
#include <QTextStream>
#include <QIdentityProxyModel>
#include <QRegExpValidator>
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0) ;
~MainWindow();
QTableView *griglia;
protected:
bool eventFilter(QObject *obj, QEvent *event);
private:
Ui::MainWindow *ui;
};
#endif // MAINWINDOW_H
MAINWINDOW.CPP
#include "mainwindow.h"
#include "ui_mainwindow.h"
MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent),ui(new Ui::MainWindow)
{
ui->setupUi(this);
QWidget *mainWindow = new QWidget;
QStandardItemModel *model = new QStandardItemModel(48,33);
griglia = new QTableView;
griglia->setModel(model);
QPushButton *calcola = new QPushButton;
calcola->setText("CALCOLA");
QVBoxLayout *layout = new QVBoxLayout;
layout->addWidget(griglia);
layout->addWidget(calcola);
mainWindow->setLayout(layout);
ItemDelegate *itDelegate = new ItemDelegate;
griglia->setItemDelegate(itDelegate);
this->setCentralWidget(mainWindow);
qApp->installEventFilter(this);
}
bool MainWindow::eventFilter(QObject *obj, QEvent *event)
{
if(obj == griglia && event->type() == QEvent::KeyPress)
{
QKeyEvent *keyEvent = static_cast<QKeyEvent *>(event);
if(keyEvent->key() == Qt::Key_Cancel)
{
QModelIndex in =griglia->currentIndex();
griglia->model()->setData(in," ");
}
}
return QObject::eventFilter(obj, event);
}
MainWindow::~MainWindow()
{
delete ui;
}
MAIN.CPP
#include "mainwindow.h"
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QFile styleFile( "style.qss" );
styleFile.open( QFile::ReadOnly );
QString style( styleFile.readAll() );
a.setStyleSheet( style );
MainWindow my;
my.showMaximized();
return a.exec();
}
Now you should see "works" and cell should be cleared, another code optimization do by yourself.
Addition for multiple selection:
if(obj == ui->tableView && event->type() == QEvent::KeyPress)
{
QKeyEvent *keyEvent = static_cast<QKeyEvent *>(event);
if(keyEvent->key() == Qt::Key_Shift)
{
qDebug() << "Up";
//ui->tableView->model()->setData(ui->tableView->currentIndex(),"");
QList<QModelIndex> index = ui->tableView->selectionModel()->selectedIndexes();
for(int i = 0; i < index.size(); i++)
ui->tableView->model()->setData(index.at(i),"");
}
}
Related
I have a scene with a 12*4 grid with blocks of QGraphicsItems ,when i right click on the blocks I have a contexmenu that
can add icons inside the blocks my proplem is that
I can't fingure out how can I make those icons draggable to the other blocks inside the graphic scene ,I know there is the "Draggable Icons Example" but how can I implement that code to a graphic scene.
this is the mainwindow.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <QGraphicsPathItem>
class QGraphicsSceneMouseEvent;
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
bool eventFilter(QObject *, QEvent *);
~MainWindow();
private slots:
void showContextMenu(const QPoint&);
void addPixBlock();
private:
Ui::MainWindow *ui;
QGraphicsScene *scene;
QGraphicsItem *itemAt(const QPointF&);
int x;
int y;
QMenu *Menu;
QMenu *Submenu;
QAction *Picture;
QGraphicsPixmapItem* pix;
};
#endif // MAINWINDOW_H
the mainwindow.cpp
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "block.h"
#include <QGraphicsScene>
#include <QGraphicsSceneMouseEvent>
#include <QDebug>
#include <QPainter>
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
scene = new QGraphicsScene(this) ;
for(int row=-4;row<8;++row)
for(int column=0;column<4;++column)
{
Block *b = new Block;
scene->addItem(b);
b->setPos(row* 95,column*85);
}
ui->graphicsView->setScene(scene);
scene->installEventFilter(this);
}
MainWindow::~MainWindow()
{
delete ui;
}
QGraphicsItem* MainWindow::itemAt(const QPointF &pos)
{
QList<QGraphicsItem*> items = scene->items(QRectF(pos - QPointF(1,1),
QSize(3,3)));
foreach(QGraphicsItem *item, items)
if (item->type() > QGraphicsItem::UserType)
return item;
return 0;
}
bool MainWindow::eventFilter(QObject *o, QEvent *e)
{
QGraphicsSceneMouseEvent *me = (QGraphicsSceneMouseEvent*) e;
switch ((int) e->type()){
case QEvent::GraphicsSceneMousePress:{
switch ((int) me->button()){
case Qt::RightButton:{
QGraphicsItem *item = itemAt(me->scenePos());
if (item && item->type() == Block::Type){
x=item->scenePos().x();
y=item->scenePos().y();
showContextMenu(item->scenePos().toPoint());
}
break;
}
}
break;
}
}
return QObject::eventFilter(o, e);
}
void MainWindow::showContextMenu(const QPoint &pos)
{
Menu= new QMenu("Menu");
Submenu=Menu->addMenu(QIcon(":/img/pix.png"),"Pix");
Picture =Submenu->addAction(QIcon(":/img/pix.png"),"Pix");
connect(Picture, SIGNAL(triggered()), this, SLOT(addPixBlock()));
Menu->exec(QCursor::pos());
}
void MainWindow::addPixBlock()
{
QPixmap pixmap(":/img/pix.png");
pix = scene->addPixmap(pixmap.scaled(70,50));
pix->setPos(x,y);
}
the block.h
#ifndef BLOCK_H
#define BLOCK_H
#include <QGraphicsPathItem>
class QGraphicsSceneMouseEvent;
class Block : public QGraphicsPathItem
{
public:
enum { Type = QGraphicsItem::UserType + 3 };
int type() const { return Type; }
Block(QGraphicsItem *parent = 0);
void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget
*widget);
bool eventFilter(QObject *, QEvent *);
};
#endif // BLOCK_H
the Block.cpp
#include "block.h"
#include <QPainter>
#include <QtWidgets>
class QGraphicsSceneMouseEvent;
Block::Block(QGraphicsItem *parent)
: QGraphicsPathItem(parent)
{
QPainterPath p;
//<->,|,<->,|,roundness
p.addRoundedRect(0,0,80,50, 5, 5);
setPath(p);
setAcceptDrops(true);
setAcceptedMouseButtons(Qt::LeftButton);
}
void Block::paint(QPainter *painter, const QStyleOptionGraphicsItem *option,
QWidget *widget)
{
Q_UNUSED(option)
Q_UNUSED(widget)
painter->setPen(QPen(QColor(67, 141, 220)));
painter->setBrush(QColor(67, 141, 220,100));
painter->drawPath(path());
}
First of all if you want to place a QGraphicsPixmapItem on top of another item, a better option is to set it as your parentItem.
On the other hand we can use an event filter but a better option in this case is to implement a custom QGraphicsScene, and when pressing with the left key it allows to drag the item, for that we use QDrag and we pass the data of the item, then we overwrite the event dropEvent where we will obtain the item and establish a new parent.
graphicsscene.h
#ifndef GRAPHICSSCENE_H
#define GRAPHICSSCENE_H
#include <QGraphicsScene>
class QMenu;
class QAction;
class GraphicsScene : public QGraphicsScene
{
public:
using QGraphicsScene::QGraphicsScene;
protected:
void mousePressEvent(QGraphicsSceneMouseEvent *event) override;
void dropEvent(QGraphicsSceneDragDropEvent *event) override;
private:
QGraphicsPixmapItem *findPixmapItem(QGraphicsItem *item);
void createDrag(const QPointF &pos, QWidget *widget, QGraphicsItem *item);
void showContextMenu(const QPointF &pos);
void addPixBlock(QGraphicsItem *item);
QMenu *menu;
QMenu *submenu;
QAction *picture;
QGraphicsPixmapItem *pix;
};
#endif // GRAPHICSSCENE_H
graphicsscene.cpp
#include "graphicsscene.h"
#include <QDrag>
#include <QGraphicsItem>
#include <QGraphicsSceneMouseEvent>
#include <QMenu>
#include <QMimeData>
#include <QWidget>
void GraphicsScene::mousePressEvent(QGraphicsSceneMouseEvent *event)
{
auto its = items(QRectF(event->scenePos() - QPointF(1,1), QSize(3,3)));
auto val = std::find_if(its.constBegin(), its.constEnd(), [](auto const& it){
return it->type() > QGraphicsItem::UserType;
});
if(val == its.constEnd())
return;
if(event->button() == Qt::RightButton){
showContextMenu(event->scenePos());
}
else{
createDrag(event->scenePos(), event->widget(), *val);
}
}
void GraphicsScene::dropEvent(QGraphicsSceneDragDropEvent *event)
{
QByteArray byteArray = event->mimeData()->data("Item");
QGraphicsPixmapItem * item = *reinterpret_cast<QGraphicsPixmapItem**>(byteArray.data());
QGraphicsItem *item_parent = itemAt(event->scenePos(), QTransform());
item->setParentItem(item_parent);
}
QGraphicsPixmapItem *GraphicsScene::findPixmapItem(QGraphicsItem *item){
auto chs = item->childItems();
auto val = std::find_if(chs.constBegin(), chs.constEnd(), [](auto const& it){
return static_cast<QGraphicsPixmapItem *>(it) != Q_NULLPTR;
});
return val == chs.constEnd() ? Q_NULLPTR : static_cast<QGraphicsPixmapItem *>(*val);
}
void GraphicsScene::createDrag(const QPointF &pos, QWidget *widget, QGraphicsItem *item){
QGraphicsPixmapItem *pix = findPixmapItem(item);
if(pix == Q_NULLPTR)
return;
QByteArray byteArray(reinterpret_cast<char*>(&pix),sizeof(QGraphicsPixmapItem*));
QDrag *drag = new QDrag(widget);
QMimeData * mimeData = new QMimeData;
mimeData->setData("Item",byteArray);
drag->setMimeData(mimeData);
drag->setHotSpot(pos.toPoint()-pix->scenePos().toPoint());
drag->setPixmap(pix->pixmap());
drag->start();
}
void GraphicsScene::showContextMenu(const QPointF &pos)
{
QGraphicsItem *item = itemAt(pos, QTransform());
menu= new QMenu("Menu");
submenu = menu->addMenu(QIcon(":/img/pix.png"),"Pix");
picture = submenu->addAction(QIcon(":/img/pix.png"),"Pix");
connect(picture, &QAction::triggered, [item, this](){
addPixBlock(item);
});
menu->exec(QCursor::pos());
}
void GraphicsScene::addPixBlock(QGraphicsItem *item)
{
if(findPixmapItem(item))
return;
QPixmap pixmap(":/img/pix.png");
pix = addPixmap(pixmap.scaled(70,50));
if(pix->parentItem() != item)
pix->setParentItem(item);
}
Then we establish that new scene and add the Blocks.
The complete example can be found in the following link
I have created a class for making a sidebar just like in Qt Creator (one to the left). I am having no idea now to make it look exactly like the one in Qt creator as mine looks ugly!
The sidebar.h:
#ifndef _SIDEBAR_H_
#define _SIDEBAR_H_
#include <QVector>
#include <QString>
#include <QWidget>
#include <QLabel>
#include <QVBoxLayout>
#include <QPixmap>
#include <iostream>
class SideBar : public QWidget
{
public:
SideBar(QWidget *parent=nullptr);
void addIcon(const char *name);
void addIcon(QString &name);
private:
QVBoxLayout *_layout;
};
#endif // SIDEBAR_H
The sidebar.cpp
#include "sidebar.h"
#include <QPushButton>
#include <QIcon>
SideBar::SideBar(QWidget *parent) : QWidget(parent)
{
_layout = new QVBoxLayout(this);
setLayout(_layout);
}
void SideBar::addIcon(const char *name)
{
QString str(name);
addIcon(str);
}
void SideBar::addIcon(QString &file)
{
QPushButton *button = new QPushButton(this);
QPixmap pixmap(file);
QIcon buttonIcon(pixmap);
button->setIcon(buttonIcon);
// button->setIconSize(pixmap.rect().size());
_layout->addWidget(button);
}
This is one i want:
And this is one i got:
A possible solution is to use QAction to handle the clicks and icons, overwriting the methods paintEvent, mousePressEvent, mouseMoveEvent, leaveEvent, changing the colors regarding the state in which the widget is.
sidebar.h
#ifndef SIDEBAR_H
#define SIDEBAR_H
#include <QAction>
#include <QWidget>
class SideBar : public QWidget
{
Q_OBJECT
public:
explicit SideBar(QWidget *parent = nullptr);
void addAction(QAction *action);
QAction *addAction(const QString &text, const QIcon &icon = QIcon());
QSize minimumSizeHint() const;
signals:
public slots:
protected:
void paintEvent(QPaintEvent *event);
void mousePressEvent(QMouseEvent *event);
void mouseMoveEvent(QMouseEvent *event);
void leaveEvent(QEvent * event);
QAction *actionAt(const QPoint &at);
private:
QList<QAction *> mActions;
QAction *mCheckedAction;
QAction *mOverAction;
};
#endif // SIDEBAR_H
sidebar.cpp
#include "sidebar.h"
#include <QPaintEvent>
#include <QPainter>
#include <QDebug>
#include <QEvent>
#define action_height 90
SideBar::SideBar(QWidget *parent) :
QWidget(parent), mCheckedAction(NULL), mOverAction(NULL)
{
setMouseTracking(true);
}
void SideBar::paintEvent(QPaintEvent *event)
{
QPainter p(this);
QFont fontText(p.font());
fontText.setFamily("Helvetica Neue");
p.setFont(fontText);
int action_y = 0;
p.fillRect(rect(), QColor(100, 100, 100));
for(auto action: mActions)
{
QRect actionRect(0, action_y, event->rect().width(), action_height);
if(action->isChecked())
{
p.fillRect(actionRect, QColor(35, 35, 35));
}
if(action == mOverAction){
p.fillRect(actionRect, QColor(150, 150, 150));
}
p.setPen(QColor(255, 255, 255));
QSize size = p.fontMetrics().size(Qt::TextSingleLine, action->text());
QRect actionTextRect(QPoint(actionRect.width()/2 - size.width()/2, actionRect.bottom()-size.height()-5), size);
p.drawText(actionTextRect, Qt::AlignCenter, action->text());
QRect actionIconRect(0, action_y + 10, actionRect.width(), actionRect.height()-2*actionTextRect.height()-10);
QIcon actionIcon(action->icon());
actionIcon.paint(&p, actionIconRect);
action_y += actionRect.height();
}
}
QSize SideBar::minimumSizeHint() const
{
return action_height*QSize(1, mActions.size());
}
void SideBar::addAction(QAction *action)
{
mActions.push_back(action);
action->setCheckable(true);
update();
}
QAction *SideBar::addAction(const QString &text, const QIcon &icon)
{
QAction *action = new QAction(icon, text, this);
action->setCheckable(true);
mActions.push_back(action);
update();
return action;
}
void SideBar::mousePressEvent(QMouseEvent *event)
{
QAction* tempAction = actionAt(event->pos());
if(tempAction == NULL || tempAction->isChecked())
return;
qDebug()<<"clicked";
if(mCheckedAction)
mCheckedAction->setChecked(false);
if(mOverAction == tempAction)
mOverAction = NULL;
mCheckedAction = tempAction;
tempAction->setChecked(true);
update();
QWidget::mousePressEvent(event);
}
void SideBar::mouseMoveEvent(QMouseEvent *event)
{
QAction* tempAction = actionAt(event->pos());
if(tempAction == NULL){
mOverAction = NULL;
update();
return;
}
if(tempAction->isChecked() || mOverAction == tempAction)
return;
mOverAction = tempAction;
update();
QWidget::mouseMoveEvent(event);
}
void SideBar::leaveEvent(QEvent * event)
{
mOverAction = NULL;
update();
QWidget::leaveEvent(event);
}
QAction* SideBar::actionAt(const QPoint &at)
{
int action_y = 0;
for(auto action: mActions)
{
QRect actionRect(0, action_y, rect().width(), action_height);
if(actionRect.contains(at))
return action;
action_y += actionRect.height();
}
return NULL;
}
#undef action_height
The sample code is here.
Screenshots:
I would like to get mouse position inside my QListWidget. The tracking is fine when mouse hovers over all other QWidgets - QMainWindow, QPushButton, CentralWidget, etc., except QListWidget.
c++ file: test_1.cpp
#include "test_1.h"
#include "ui_test_1.h"
test_1::test_1(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::test_1)
{
ui->setupUi(this);
this->setMouseTracking(true);
ui->centralWidget->setMouseTracking(true);
ui->listWidget->setMouseTracking(true);
ui->pushButton->setMouseTracking(true);
ui->listWidget->addItem("aaa");
ui->listWidget->addItem("bbb");
ui->listWidget->addItem("ccc");
ui->listWidget->addItem("ddd");
ui->listWidget->addItem("eee");
}
void test_1::mouseMoveEvent(QMouseEvent *event)
{
qDebug() << event->pos();
}
test_1::~test_1()
{
delete ui;
}
Header file: test_1.h
#ifndef TEST_1_H
#define TEST_1_H
#include <QMainWindow>
#include <QDebug>
#include <QMouseEvent>
namespace Ui {
class test_1;
}
class test_1 : public QMainWindow
{
Q_OBJECT
public:
explicit test_1(QWidget *parent = 0);
~test_1();
private:
Ui::test_1 *ui;
void mouseMoveEvent(QMouseEvent*);
};
#endif // TEST_1_H
Main: main.cpp
#include "test_1.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
test_1 w;
w.show();
return a.exec();
}
Output:
QPoint(359,141)
QPoint(358,141)
QPoint(357,140)
QPoint(356,140)
QPoint(355,140)
QPoint(354,139)
QPoint(353,139)
QPoint(352,139)
QPoint(351,139)
void test_2::mouseMoveEvent(QMouseEvent *event)
{
QPoint p = event->pos();
QRect widgetRect = ui->listWidget->rect();
if(widgetRect.contains(p))
{
qDebug() << "Inside";
ui->listWidget->grabMouse();
}
else
{
qDebug() << "Outside";
ui->listWidget->releaseMouse();
}
}
The right way of solving this is inheriting QListWidget and implementing void mouseMoveEvent(QMouseEvent *event)
But you have also another option, like installing an event filter on your QListWidget.
Add this in your contructor:
ui->listWidget->viewport()->installEventFilter(this);
And implement the event filter:
bool MainWindow::eventFilter(QObject *obj, QEvent *event)
{
if(event->type() == QEvent::MouseButtonPress)
{
qDebug() << Q_FUNC_INFO << "QEvent::MouseButtonPress";
}
if(event->type() == QEvent::MouseMove)
{
qDebug() << Q_FUNC_INFO << " pos: " << this->mapFromGlobal(QCursor::pos());
}
return false;
}
The key event listener or the function repaint() are not working, I've tried calling paintEvent(QPaintEvent *) directly but it didn't work either, thanks to further answers.
Here's the code:
window.h
#ifndef WINDOW_H
#define WINDOW_H
#include <QWidget>
#include <QPainter>
#include <QPaintEvent>
#include <QRectF>
namespace Ui {
class Window;
}
class Window : public QWidget
{
Q_OBJECT
public:
explicit Window(QWidget *parent = 0);
~Window();
void paintEvent(QPaintEvent *);
void keyPressEvent(QKeyEvent * );
private:
Ui::Window *ui;
QRectF player;
QPainter * painter = new QPainter(this);
};
#endif // WINDOW_H
window.cpp
#include "window.h"
#include "ui_window.h"
Window::Window(QWidget *parent) :
QWidget(parent),
ui(new Ui::Window)
{
ui->setupUi(this);
player.setX(0);
player.setY(0);
player.setWidth(50);
player.setHeight(50);
}
Window::~Window()
{
delete ui;
}
void Window::paintEvent(QPaintEvent *)
{
QPainter painter(this);
painter.setPen(QPen(Qt::black, 3, Qt::DashDotLine, Qt::RoundCap));
painter.setBrush(QBrush(Qt::blue));
painter.setRenderHint(QPainter::Antialiasing, true);
painter.drawEllipse(player.x(), player.y(), player.width(), player.height());
}
void Window::keyPressEvent(QKeyEvent * event)
{
if(event->type() == Qt::Key_W)
player.setY(player.y() - 1);
if(event->type() == Qt::Key_S)
player.setY(player.y() + 1);
if(event->type() == Qt::Key_A)
player.setX(player.x() - 1);
if(event->type() == Qt::Key_D)
player.setX(player.x() + 1);
repaint();
}
main.cpp
#include "window.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
Window w;
w.show();
return a.exec();
}
In Window::keyPressEvent, replace event->type() with event->key() everywhere.
Also, take a look at the compiler output. I think it should have warned you about comparing QEvent::Type with Qt::Key objects.
After close MessageBox the focus self does not return to the window. I tried so:
QMessageBox msgBox;
msgBox.setText("Ok");
msgBox.exec();
this->setFocus();
How to return focus to the main window (this)?
//dialog.h
#ifndef DIALOG_H
#define DIALOG_H
#include <QDialog>
namespace Ui {
class Dialog;
}
class Dialog : public QDialog
{
Q_OBJECT
public:
explicit Dialog(QWidget *parent = 0);
void loadFile();
~Dialog();
private slots:
void on_buttonLoad2_clicked();
private:
Ui::Dialog *ui;
};
#endif // DIALOG_H
//dialog.cpp
//
#include "dialog.h"
#include "ui_dialog.h"
#include <QDebug>
#include <QXmlStreamReader>
#include <QNetworkAccessManager>
#include <QNetworkReply>
#include <QEvent>
#include <QDomDocument>
#include <QDomElement>
#include <QFile>
#include <QMessageBox>
#include <QMediaPlayer>
#include <QListWidgetItem>
Dialog::Dialog(QWidget *parent) :
QDialog(parent),
ui(new Ui::Dialog)
{
this->setFocusPolicy(Qt::StrongFocus);
ui->setupUi(this);
}
void Dialog::loadFile()
{
QString urlForXML = "http://apifree.forvo.com/key//format/xml/action/word-pronunciations/word/";
urlForXML += ui->textHttp->toPlainText() + "/language/de";
QNetworkAccessManager m_NetworkMngr;
QNetworkReply *reply = m_NetworkMngr.get(QNetworkRequest(urlForXML));
QEventLoop loop;
connect(reply, SIGNAL(finished()),&loop, SLOT(quit()));
loop.exec();
QXmlStreamReader xmlReader;
xmlReader.addData(reply->readAll());
QString pathmp3Url;
while(!xmlReader.atEnd()) // пока не конец потока...
{
xmlReader.readNextStartElement(); // читаем следующий открывающий элемент (тег)
if (xmlReader.name() == "pathmp3") // если имя элемента "pathmp3"
{
pathmp3Url = xmlReader.readElementText();
break;
}
}
delete reply;
if(pathmp3Url.count())
{
QNetworkAccessManager m_NetworkMngr2;
QNetworkReply *reply2 = m_NetworkMngr2.get(QNetworkRequest(pathmp3Url));
QEventLoop loop2;
connect(reply2, SIGNAL(finished()), &loop2, SLOT(quit()));
loop2.exec();
QString qstring_mp3file = "/users/derkode/documents/forvoclient-mp3/" + ui->textHttp->toPlainText() + ".mp3";
QFile mp3_file(qstring_mp3file);
mp3_file.open(QIODevice::WriteOnly);
mp3_file.write(reply2->readAll());
QMediaPlayer *player = new QMediaPlayer;
player->setMedia(QUrl::fromLocalFile(qstring_mp3file));
player->setVolume(50);
player->play();
mp3_file.close();
delete reply2;
}
else
{
QMessageBox *msgBox = new QMessageBox(this);
msgBox->setText("Ok");
msgBox->exec();
this->setFocus();
}
}
Dialog::~Dialog()
{
delete ui;
}
void Dialog::on_buttonLoad2_clicked()
{
loadFile();
}
this->parent()->setFocus(); after msgBox->exec() (near end of your code)