Implementations of buttons in Qt / C++ - c++

Im looking to implement a sudoku gui in Qt. First things first im trying to generate a grid of QToolButtons, which when pressed will increment their value by one.
Here is my header for window.h
class Window : public QWidget
{
Q_OBJECT
public:
Window(QWidget *parent = nullptr);
private slots:
void digitClicked();
private:
Button *createButton(const QString &text, const char *member);
QString *readFileChar(const QString file_name, QString digit[] );
QGridLayout *previewLayout;
void setSudokuChar(const int digit, const char *member);
enum { NumDigitButtons = 81 };
Button *digitButtons[NumDigitButtons];
QString digit[NumDigitButtons];
protected:
void paintEvent(QPaintEvent *event) override;
void mouseReleaseEvent(QMouseEvent * event) override;
};
And the corresponding source file window.cpp
Window::Window(QWidget *parent) : QWidget(parent) //constrcutor
{
//button creation
QString* current_digit = readFileChar("/home/pi/Documents/ELEC1204/P6/sudoku.txt", digit);
for(int i = 0; i < NumDigitButtons; i++){
digitButtons[i] = createButton(*(current_digit++), SLOT(digitClicked())); //initialize sudoku
}
// set form size
QGridLayout *mainLayout = new QGridLayout;
setMaximumSize(600,600);
mainLayout->setSizeConstraint(QLayout::SetFixedSize);
setWindowTitle(tr("button game"));
// place each digit button
for(int i = 1; i < NumDigitButtons; i++){
int row = (81 - i) / 9 ; // y position for button
int col = (i - 1) % 9 ; // x position for button
mainLayout->addWidget(digitButtons[i], row, col);
}
}
void Window::digitClicked()
{
Button *clickedButton = qobject_cast<Button*>(sender()); //clicked button = object button that was pressed
int val = ++(clickedButton->text().toInt()); //incrememt digit value of the button which was pressed
setSudokuChar(val, clickedButton); //updates sudoku with new value
}
QString* Window::readFileChar(const QString file_name, QString digit[]) //reads in file to initialize buttons
{
QFile file(file_name);
int i = 0;
if(file.open(QIODevice::ReadOnly | QIODevice::Text)){
QTextStream in(&file);
while(!in.atEnd()){
digit[i] = in.read(1); //read each character into an array of QStrings
i++ ;
}
}
else{
QTextStream(stdout) << "could not open file, program terminating" << endl;
exit(1);
}
return digit;
}
Button *Window::createButton(const QString &text, const char *member)
{
Button *button = new Button(text);
connect(button, SIGNAL(clicked()), this, member);
return button;
}
void setSudokuChar(const int digit, Button* clickedButton) //takes in a digit, and assigns its value to the char that was pass
{
}
Please note that the function to update the button's value when pressed 'setSudokuChar' is yet to be implemented, but that pretty irrelevant for now.
Here is the button class header button.h, it's only a small modification of the QToolButton class to aid in resizing.
class Button : public QToolButton
{
Q_OBJECT
public:
explicit Button(const QString &text, QWidget *parent = nullptr);
QSize sizeHint() const override;
};
And finally, here is the button.cpp source file
Button::Button(const QString &text, QWidget *parent) : QToolButton(parent)
{
setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Preferred);
setText(text);
}
QSize Button::sizeHint() const
{
QSize size = QToolButton::sizeHint();
size.rheight() += 20;
size.rwidth() = qMax(size.width(), size.height());
return size;
}
Hopefully thats not too much to digest, I'm still a beginner!
**My problem is ... ** when I run the code, a window is produced but its blank, which means the compilation is fine, but the program is not working as intended. Could anyone by chance spot what is going wrong? All that i do in the main function is create a window as follows :
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
Window window;
window.show();
return app.exec();
}
Any and all help is thoroughly appreciated.

Related

Qt C++ Drag QHeaderView between tables

I want to copy the selected column of a QTableWidget to another one.
So I tried to make selected columns draggable by adding this code:
void makeDraggable(QTableWidget *table)
{
table->setDragEnabled(true);
table->setAcceptDrops(true);
table->setSelectionBehavior(QAbstractItemView::SelectColumns);
}
Result I got:
But I want to drag a whole column (horizontal and vertical headers) by clicking on headers only, not on cells, and copy its data to another table including the header text.
Dragging between different tables inside one application can be done with reimplementing custom QHeaderView and QTableWidget. In my example I generate text with indecies of table and column for drag event. Custom header:
#include <QHeaderView>
class ITableManager;
class DraggableHeaderView : public QHeaderView
{
Q_OBJECT
public:
explicit DraggableHeaderView(Qt::Orientation orientation, QWidget *parent = 0);
int tag() const;
void setTag(const int tag);
void setTableManager(ITableManager* manager);
protected:
void mouseMoveEvent(QMouseEvent *e);
void dragEnterEvent(QDragEnterEvent *event);
void dragMoveEvent(QDragMoveEvent *event);
void dropEvent(QDropEvent *event);
signals:
public slots:
private:
int m_tag; //internal index of table
ITableManager *m_tableManager; //manager will convert table index into pointer
};
Custom header cpp
#include <QMouseEvent>
#include <QDrag>
#include <QMimeData>
#include <QDebug>
#include <QTableWidget>
#include <ITableManager.h>
DraggableHeaderView::DraggableHeaderView(Qt::Orientation orientation, QWidget *parent) :
QHeaderView(orientation, parent)
{
m_tag = 0;
m_tableManager = 0;
setAcceptDrops(true);
}
void DraggableHeaderView::mouseMoveEvent(QMouseEvent *e)
{
if (e->buttons() & Qt::LeftButton)
{
int index = logicalIndexAt(e->pos());
QDrag *drag = new QDrag(this);
QMimeData *mimeData = new QMimeData;
//custom drag text with indecies inside
QString mimeTxt = "MoveHeader;Table:" + QString::number(m_tag) +
";Index:" + QString::number(index);
mimeData->setText(mimeTxt);
drag->setMimeData(mimeData);
Qt::DropAction dropAction = drag->exec();
}
}
int DraggableHeaderView::tag() const
{
return m_tag;
}
void DraggableHeaderView::setTag(const int tag)
{
m_tag = tag;
}
void DraggableHeaderView::dragEnterEvent(QDragEnterEvent *event)
{
if (!m_tableManager)
{
event->ignore();
return;
}
QString dragText = event->mimeData()->text();
int index = dragText.indexOf("MoveHeader;");
if (index == 0)
{
event->accept();
}
else
{
event->ignore();
}
}
void DraggableHeaderView::dropEvent(QDropEvent *event)
{
if (!m_tableManager)
{
event->ignore();
return;
}
QStringList dragText = event->mimeData()->text().split(';');
if (dragText.count() < 3 || dragText.at(0) != "MoveHeader")
{
event->ignore();
return;
}
int tableIndex = dragText.at(1).mid(6).toInt();//6 - length 'Table:'
QTableWidget* tableSrc = m_tableManager->getTableFromIndex(tableIndex);
if (!tableSrc)
{
event->ignore();
return;
}
//dst table as parent for header view
QTableWidget *tableDst = qobject_cast<QTableWidget*> (this->parentWidget());
if (!tableDst)
{
event->ignore();
return;
}
//move column: modify for your needs
//now moves only items text
int columnIndex = logicalIndexAt(event->pos());
int srcColumnIndex = dragText.at(2).mid(6).toInt(); //6 - length of 'Index:'
tableDst->insertColumn(columnIndex);
for (int iRow = 0; iRow < tableDst->rowCount() && iRow < tableSrc->rowCount(); ++iRow)
{
if (tableSrc->item(iRow, srcColumnIndex))
{
tableDst->setItem(iRow, columnIndex,
new QTableWidgetItem(tableSrc->item(iRow, srcColumnIndex)->text()));
}
else
{
tableDst->setItem(iRow, columnIndex, new QTableWidgetItem());
}
}
tableSrc->removeColumn(srcColumnIndex);
}
void DraggableHeaderView::setTableManager(ITableManager *manager)
{
m_tableManager = manager;
}
Now create custom QTableWidget with DraggableHeaderView inside
class CustomTableWidget : public QTableWidget
{
Q_OBJECT
public:
explicit CustomTableWidget(QWidget *parent = 0);
void setTag(const int tag);
void setTableManager(ITableManager* manager);
};
CustomTableWidget::CustomTableWidget(QWidget *parent) :
QTableWidget(parent)
{
DraggableHeaderView *headerView = new DraggableHeaderView(Qt::Horizontal, this);
setHorizontalHeader(headerView);
setAcceptDrops(true);
}
void CustomTableWidget::setTag(const int tag)
{
DraggableHeaderView *header = qobject_cast<DraggableHeaderView*> (horizontalHeader());
if (header)
{
header->setTag(tag);
}
}
void CustomTableWidget::setTableManager(ITableManager *manager)
{
DraggableHeaderView *header = qobject_cast<DraggableHeaderView*> (horizontalHeader());
if (header)
{
header->setTableManager(manager);
}
}
For converting table index to pointer I use ITableManager
class ITableManager
{
public:
virtual QTableWidget* getTableFromIndex(const int index) = 0;
};
And implement it in QMainWindow
class MainWindow : public QMainWindow, ITableManager
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
QTableWidget* getTableFromIndex(const int index);
}
QTableWidget * MainWindow::getTableFromIndex(const int index)
{
switch (index)
{
case 1:
return ui->tableWidget;
case 2:
return ui->tableWidget_2;
default:
return nullptr;
}
}
Dont forget setup tags (indecies) and table manager for tables (in main window constructor)
ui->tableWidget->setTag(1);
ui->tableWidget_2->setTag(2);
ui->tableWidget->setTableManager(this);
ui->tableWidget_2->setTableManager(this);
EDIT: If you want change custom pixmap for dragging just set QDrag::setPixmap
void DraggableHeaderView::mouseMoveEvent(QMouseEvent *e)
{
if (e->buttons() & Qt::LeftButton)
{
int index = logicalIndexAt(e->pos());
QDrag *drag = new QDrag(this);
QMimeData *mimeData = new QMimeData;
QString mimeTxt = "MoveHeader;Table:" + QString::number(m_tag) +
";Index:" + QString::number(index);
mimeData->setText(mimeTxt);
drag->setMimeData(mimeData);
drag->setPixmap(pixmapForDrag(index));
Qt::DropAction dropAction = drag->exec();
}
}
And method for taking pixmap of column can be like this
QPixmap DraggableHeaderView::pixmapForDrag(const int columnIndex) const
{
QTableWidget *table = qobject_cast<QTableWidget*> (this->parentWidget());
if (!table)
{
return QPixmap();
}
//image for first 5 row
int height = table->horizontalHeader()->height();
for (int iRow = 0; iRow < 5 && iRow < table->rowCount(); ++iRow)
{
height += table->rowHeight(iRow);
}
//clip maximum size
if (height > 200)
{
height = 200;
}
QRect rect(table->columnViewportPosition(columnIndex) + table->verticalHeader()->width(),
table->rowViewportPosition(0),
table->columnWidth(columnIndex),
height);
QPixmap pixmap(rect.size());
table->render(&pixmap, QPoint(), QRegion(rect));
return pixmap;
}

How to print output data created by QDebug in a widget?

I'm new to programming. Would like to know how to print the output data from the code below (C++) using the Qt. I need an answer to appear in the QTextEdit window.
for (int x=0; x<10; x++);
Here's how you might capture the qDebug messages in a QAbstractItemModel or QTextDocument. Both of those classes are models, their associated views are QListView (or any other view), and QTextEdit (preferably QPlainTextEdit or QTextBrowser), respectively.
// https://github.com/KubaO/stackoverflown/tree/master/questions/qdebug-window-output-52061269
#include <QtWidgets>
struct LogToModelData {
bool installed;
QtMessageHandler previous = {};
QList<QPointer<QObject>> models;
};
Q_GLOBAL_STATIC(LogToModelData, logToModelData)
void logToModelHandler(QtMsgType type, const QMessageLogContext &context,
const QString &msg) {
for (auto m : qAsConst(logToModelData->models)) {
if (auto model = qobject_cast<QAbstractItemModel *>(m)) {
auto row = model->rowCount();
model->insertRow(row);
model->setData(model->index(row, 0), msg);
} else if (auto doc = qobject_cast<QTextDocument *>(m)) {
QTextCursor cur(doc);
cur.movePosition(QTextCursor::End);
if (cur.position() != 0) cur.insertBlock();
cur.insertText(msg);
}
}
if (logToModelData->previous) logToModelData->previous(type, context, msg);
}
void logToModel(QObject *model) {
logToModelData->models.append(QPointer<QObject>(model));
if (!logToModelData->installed) {
logToModelData->previous = qInstallMessageHandler(logToModelHandler);
logToModelData->installed = true;
}
}
void rescrollToBottom(QAbstractScrollArea *view) {
static const char kViewAtBottom[] = "viewAtBottom";
auto *scrollBar = view->verticalScrollBar();
Q_ASSERT(scrollBar);
auto rescroller = [scrollBar]() mutable {
if (scrollBar->property(kViewAtBottom).isNull())
scrollBar->setProperty(kViewAtBottom, true);
auto const atBottom = scrollBar->property(kViewAtBottom).toBool();
if (atBottom) scrollBar->setValue(scrollBar->maximum());
};
QObject::connect(scrollBar, &QAbstractSlider::rangeChanged, view, rescroller,
Qt::QueuedConnection);
QObject::connect(scrollBar, &QAbstractSlider::valueChanged, view, [scrollBar] {
auto const atBottom = scrollBar->value() == scrollBar->maximum();
scrollBar->setProperty(kViewAtBottom, atBottom);
});
}
int main(int argc, char *argv[]) {
QApplication app{argc, argv};
QWidget ui;
QVBoxLayout layout{&ui};
QListView view;
QTextBrowser browser;
layout.addWidget(new QLabel(QLatin1String(view.metaObject()->className())));
layout.addWidget(&view);
layout.addWidget(new QLabel(QLatin1String(browser.metaObject()->className())));
layout.addWidget(&browser);
QStringListModel model;
view.setModel(&model);
logToModel(view.model());
logToModel(browser.document());
rescrollToBottom(&view);
rescrollToBottom(&browser);
QTimer timer;
QObject::connect(&timer, &QTimer::timeout, [] {
static int n;
qDebug() << "Tick" << ++n;
});
timer.start(500);
ui.show();
return app.exec();
}
Also note that the separate declaration of the loop induction variable i is a very much obsolete C-ism - the last time you had to write code like that was two decades ago.

Qt assign lines from textfile to qlabels

What works so far: opening a textfile via QFileDialog and showing the contents of the textfile in a Qlabel(showfile).
I too have a for-loop that counts how many \n are in the textfile.
Now what I want is that line after line in the textfile is assigned to a new Qlabel meaning each Qlabel contains one line of the textfile and place it dynamically on runtime.
Maybe you can help since I´m a little stuck here.
Here´s my qwidget class where the labels should be placed:
class mywidget:public QWidget //class for displaying everything
{
Q_OBJECT
private:
QGridLayout *area;
QLabel *showfile; //shows input from textfile
QLabel *processname,*status; //captionlabel
QFont *pfont,*sfont; //fontoption for processname&status
QLabel **processes; //2D array to dynamically create QLabels for each entry in file
public:
mywidget(QWidget *parent = Q_NULLPTR, Qt::WindowFlags flags = 0):QWidget(parent,flags)
{
this->area = new QGridLayout(this);
this->showfile = new QLabel(tr("Test"),this);
this->pfont = new QFont();
this->pfont->setPixelSize(20);
this->sfont = new QFont();
this->sfont->setPixelSize(20);
this->processname = new QLabel(tr("Process_Name:"),this);
this->processname->setFont(*pfont);
this->status = new QLabel(tr("Status:"),this);
this->status->setFont(*sfont);
this->area->addWidget(this->processname,0,0,Qt::AlignHCenter);
this->area->addWidget(this->status,0,1,Qt::AlignHCenter);
this->area->addWidget(this->showfile,1,0,Qt::AlignHCenter);
this->area->setSpacing(10);
}
~mywidget()
{
delete this->area;
delete this->showfile;
delete this->pfont;
delete this->sfont;
delete this->processname;
delete this->status;
}
friend class mywindow;
};
And here is my open-method from QMainwindow class:
void mywindow::oeffnen()
{
this->openfilename = QFileDialog::getOpenFileName //open textfile dialog
(this,
tr("Datei öffnen"),
QDir::homePath(),
"Textdateien (*.txt *.docx *.doc);;" "Alle Dateien (*.*)"
);
if(!this->openfilename.isEmpty())
{
this->file = new QFile(this->openfilename);
this->file->open(QIODevice::ReadOnly);
this->stream = new QTextStream(this->file);
this->fileread = this->stream->readAll();
for(int z = 0;z<this->fileread.length();++z) //check entries in string by counting \n
{
this->eintraege = this->fileread.count(QRegExp("\n"));
}
//this->s_eintraege = QString::number(this->eintraege); //converting to string for displaying
this->central->showfile->setText(this->fileread); //assign filecontent to label
if(!this->file->isReadable())
{
QMessageBox::information(this,
tr("Fehler"),
tr("Konnte Datei %1 nicht laden!").arg(this->openfilename)
);
}
else
{
QMessageBox::information(this,
tr("OK"),
tr("Konnte Datei %1 laden!").arg(this->openfilename)
);
}
this->file->close();
}
}
You can add a new QLabel into a layout for each new line you read from a file. You can store the labels in a container like QVector so you can access their text later on. Here is an example:
#include <QApplication>
#include <QWidget>
#include <QLabel>
#include <QFile>
#include <QLayout>
#include <QTextStream>
#include <QDebug>
class DisplayWidget : public QWidget
{
Q_OBJECT
public:
DisplayWidget(QWidget *parent = 0) : QWidget(parent)
{
labelLayout = new QVBoxLayout;
setLayout(labelLayout);
resize(200, 200);
}
void addLabel(const QString &text)
{
QLabel *label = new QLabel(text);
label_vector.append(label);
labelLayout->addWidget(label);
}
void readFile(const QString &filename)
{
QFile file(filename);
if(!file.open(QIODevice::ReadOnly | QIODevice::Text))
return;
QTextStream ts(&file);
while(!ts.atEnd())
{
QString line = ts.readLine();
if(!line.isEmpty())
addLabel(line);
}
}
QString getLabelText(int index)
{
if(label_vector.size() > index)
return label_vector[index]->text();
return QString();
}
private:
QVBoxLayout *labelLayout;
QVector<QLabel*> label_vector;
};
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
DisplayWidget w;
w.readFile("somefile.txt");
w.show();
qDebug() << w.getLabelText(3);
return a.exec();
}
#include "main.moc"

QScrollArea Custom Widget not Repainting Properly

I have a QScrollArea that contains my custom widget. When I change the data of the custom widget(which changes sizeHint() and the widget takes up more space) the end of each line and the last few lines are cut off. I've created a little program to replicate the issue.
widget.h
#ifndef WIDGET_H
#define WIDGET_H
#include <QWidget>
#include <QString>
class Widget : public QWidget
{
Q_OBJECT
public:
explicit Widget(QWidget *parent = 0);
void changeData(const QString &, const unsigned &, const unsigned &);
QSize sizeHint() const override;
protected:
void paintEvent(QPaintEvent *event) override;
private:
QString lines;
unsigned lineSize = 0, rowSize = 0;
};
#endif // WIDGET_H
main.cpp
#include "widget.h"
#include <QApplication>
#include <QtWidgets>
Widget::Widget(QWidget *parent) : QWidget(parent)
{
changeData("TESTING\nFUNCTIO\n1234567\nWORDS77\n", 7, 4);
update();
}
void Widget::changeData(const QString &l, const unsigned &lineSz, const unsigned &rowSz)
{
lines = l;
lineSize = lineSz;
rowSize = rowSz;
}
void Widget::paintEvent(QPaintEvent * /*event*/)
{
QPainter painter(this);
painter.setRenderHint(QPainter::Antialiasing);
QFont defaultFont = painter.font();
QPen defaultPen = painter.pen();
defaultFont.setLetterSpacing(QFont::AbsoluteSpacing, lineSize / 2 - 3);
// set pen and font
painter.setFont(defaultFont);
painter.setPen(defaultPen);
// starting point
QPoint prntPoint(5, 15);
for (QString::size_type ind = 0, row = 1; ind < lines.size(); ++ind)
{
if (lines[ind] != '\n') // if it's a letter
{
// print the letter and move the point to the right
painter.drawText(prntPoint, QString(lines[ind]));
prntPoint.setX(prntPoint.x() + 20);
}
else if (lines[ind] == '\n') // if the character is a newline
{
prntPoint.setX(5); // move point back to the very left
prntPoint.setY(row * 20 + 15); // move down
++row;
}
}
}
QSize Widget::sizeHint() const
{
return QSize(lineSize * 20, rowSize * 20);
}
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
Widget *w = new Widget;
QScrollArea area;
area.setWidget(w);
area.show();
//change string and other data variables
w->changeData("1234567890\nQWERTYU123\nLETTERS123\nWORDSSS123\n"
"TESTING123\nFUNCTIO123\nLETTERS123\nWORDSSS123\n", 10, 8);
return a.exec();
}
As you can see the data we set in the main function is cut off, only the first 7 characters and first 4 lines are printed, basically taking the first string we set in the constructor and taking a subset of this new string and printing it.
Removing QScrollArea fixes the issue but I need the scrolling capabilities for my application. Any help will be appreciated. Thank you

Qt drag & drop button; drop not detecting

I'm creating a 2D game in QT and i'm trying to implement a drag & drop into my program.
For some reason the drop is not registered: qDebug should print a message on dropping but this doesn't happen.
#include "dialog.h"
#include "ui_dialog.h"
#include "world.h"
#include <vector>
Dialog::Dialog(QWidget *parent) : QDialog(parent), ui(new Ui::Dialog)
{
ui->setupUi(this);
scene = new QGraphicsScene(this);
ui->graphicsView->setScene(scene);
MySquare *item;
QGraphicsRectItem *enemyItem;
World *myWorld = new World();
std::vector<Tile*> tiles = myWorld->createWorld(":/texture.jpg");
int count = 0;
foreach (Tile *tile, tiles){
count++;
item = new MySquare(tile->getXPos()*4,tile->getYPos()*4,4,4);
item->setBrush(QColor(tile->getValue()*255,tile->getValue()*255,tile->getValue()*255));
item->setAcceptDrops(true);
scene->addItem(item);
}
player = new MySquare(10,20,10,10);
player->setAcceptDrops(true);
scene->addItem(player);
//drag & drop part
QPushButton *pushButton = new QPushButton("Click Me",this);
connect(pushButton,SIGNAL(pressed()),this,SLOT(makeDrag()));
setAcceptDrops(true);
}
void Dialog::makeDrag()
{
QDrag *dr = new QDrag(this);
// The data to be transferred by the drag and drop operation is contained in a QMimeData object
QMimeData *data = new QMimeData;
data->setText("This is a test");
// Assign ownership of the QMimeData object to the QDrag object.
dr->setMimeData(data);
// Start the drag and drop operation
dr->start();
}
mysquare.cpp
#include "mysquare.h"
MySquare::MySquare(int _x,int _y, int _w, int _h)
{
isPlayer=false;
Pressed=false;
setFlag(ItemIsMovable);
setFlag(ItemIsFocusable);
setAcceptDrops(true);
color=Qt::red;
color_pressed = Qt::green;
x = _x;
y = _y;
w = _w;
h = _h;
}
QRectF MySquare::boundingRect() const
{
return QRectF(x,y,w,h);
}
void MySquare::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
{
QRectF rec = boundingRect();
QBrush brush(color);
if (Pressed){
brush.setColor(color);
} else {
brush.setColor(color_pressed);
}
painter->fillRect(rec,brush);
painter->drawRect(rec);
}
void MySquare::mousePressEvent(QGraphicsSceneMouseEvent *event)
{
Pressed=true;
update();
QGraphicsItem::mousePressEvent(event);
qDebug() << "mouse Pressed";
}
void MySquare::mouseReleaseEvent(QGraphicsSceneMouseEvent *event)
{
Pressed=false;
update();
QGraphicsItem::mousePressEvent(event);
qDebug() << "mouse Released";
}
void MySquare::keyPressEvent(QKeyEvent *event){
int x = pos().x();
int y = pos().y();
//key handling
QGraphicsItem::keyPressEvent(event);
}
void MySquare::dropEvent(QDropEvent *event)
{
qDebug("dropEvent - square");
// Unpack dropped data and handle it the way you want
qDebug("Contents: %s", event->mimeData()->text().toLatin1().data());
}
void MySquare::dragMoveEvent(QDragMoveEvent *event){
qDebug("dragMoveEvent - square ");
event->accept();
}
void MySquare::dragEnterEvent(QDragEnterEvent *event){
event->setAccepted(true);
qDebug("dragEnterEvent - square");
event->acceptProposedAction();
}
void MySquare::setBrush(QColor _color){
color = _color;
color_pressed = _color;
update(); //repaint
}
edit; there is no problem with qDebug() i'm just using it to test them i'm inside the drag events..which i'm not
In your mouseReleaseEvent, you pass to QGraphicsItem::mousePressEvent instead of QGraphicsItem::mouseReleaseEvent
Edit: I don't know if this matters, but initialize the QGraphicsItem in your constructor
MySquare::MySquare(int _x,int _y, int _w, int _h) : QGraphicsItem()