The reference to the main window in QT - c++

I made in QT character creator that allows you to draw individual parts of clothing, but I would like to add an option to the user himself can choose the appearance, for example shoes available, so I created a new window for shoes and there I set the 6 buttons, which are simply images of these shoes and I would so the user can click on a button in the main window receives an interesting picture of him in qlabel, but not too much know how to connect. I would ask for help! I would be really very grateful!!! Sorry for my English, but I'm from Poland.
mainwindow.h
#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_przycisk_zamykania_clicked();
void on_przycisk_informacje_clicked();
void on_przycisk_powrotu_clicked();
void on_przycisk_graj_clicked();
void on_powrot_clicked();
void on_losuj7_clicked();
void on_losuj6_clicked();
void on_losuj5_clicked();
void on_losuj4_clicked();
void on_losuj3_clicked();
void on_losuj2_clicked();
void on_losuj1_clicked();
void on_wybierz7_clicked();
private:
Ui::MainWindow* ui;
};
#endif // MAINWINDOW_H
mainwindow.cpp
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "QPixmap"
#include "QPalette"
#include "buty.h"
#include "QObject"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
ui->opis->setTextFormat(Qt::RichText);
ui->opis->setTextInteractionFlags(Qt::TextBrowserInteraction);
ui->opis->setOpenExternalLinks(true);
ui->copyright->setTextFormat(Qt::RichText);
ui->copyright >setTextInteractionFlags(Qt::TextBrowserInteraction);
ui->copyright->setOpenExternalLinks(true);
QPalette *palette1 = new QPalette();
palette1->setColor(QPalette::Text,Qt::white);
ui->imie->setPalette(*palette1);
QPalette *palette2 = new QPalette();
palette2->setColor(QPalette::Text,Qt::white);
ui->nazwisko->setPalette(*palette2);
QPalette *palette3 = new QPalette();
palette3->setColor(QPalette::Text,Qt::white);
ui->wiek->setPalette(*palette3);
QPalette *palette4 = new QPalette();
palette4->setColor(QPalette::Text,Qt::white);
ui->info->setPalette(*palette4);
QPalette *palette5 = new QPalette();
palette5->setColor(QPalette::Text,Qt::white);
ui->ocena->setPalette(*palette5);
//Buty = new Buty(this);
//connect(Buty,SIGNAL(on_buty1_clicked()),this,SLOT(on_buty1_clicked));
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::on_przycisk_zamykania_clicked()
{
close();
}
void MainWindow::on_przycisk_informacje_clicked()
{
ui->stackedWidget->setCurrentIndex(1);
}
void MainWindow::on_przycisk_powrotu_clicked()
{
ui->stackedWidget->setCurrentIndex(0);
}
void MainWindow::on_przycisk_graj_clicked()
{
ui->stackedWidget->setCurrentIndex(2);
}
void MainWindow::on_powrot_clicked()
{
ui->stackedWidget->setCurrentIndex(0);
}
void MainWindow::on_losuj7_clicked()
{
ui->pytajnik7->setStyleSheet("background-color:#040f1e;");
int losowanie7;
srand (time(NULL));
losowanie7 = rand() % 6 + 1;
if (losowanie7 == 1)
{
QPixmap b1(":/pliki_buty/img/losowanie_img/buty_img/buty1_wynik.png");
ui->pytajnik7->setPixmap(b1);
}
if (losowanie7 == 2)
{
QPixmap b2(":/pliki_buty/img/losowanie_img/buty_img/buty2_wynik.png");
ui->pytajnik7->setPixmap(b2);
}
if (losowanie7 == 3)
{
QPixmap b3(":/pliki_buty/img/losowanie_img/buty_img/buty3_wynik.png");
ui->pytajnik7->setPixmap(b3);
}
if (losowanie7 == 4)
{
QPixmap b4(":/pliki_buty/img/losowanie_img/buty_img/buty4_wynik.png");
ui->pytajnik7->setPixmap(b4);
}
if (losowanie7 == 5)
{
QPixmap b5(":/pliki_buty/img/losowanie_img/buty_img/buty5_wynik.png");
ui->pytajnik7->setPixmap(b5);
}
if (losowanie7 == 6)
{
QPixmap b6(":/pliki_buty/img/losowanie_img/buty_img/buty6_wynik.png");
ui->pytajnik7->setPixmap(b6);
}
}
void MainWindow::on_losuj6_clicked()
{
ui->pytajnik6->setStyleSheet("background-color:#040f1e;");
int losowanie6;
srand (time(NULL));
losowanie6 = rand() % 6 + 1;
if (losowanie6 == 1)
{
QPixmap s1(":/pliki_spodnie/img/losowanie_img/spodnie_img/spodnie1_wynik.png");
ui->pytajnik6->setPixmap(s1);
}
if (losowanie6 == 2)
{
QPixmap s2(":/pliki_spodnie/img/losowanie_img/spodnie_img/spodnie2_wynik.png");
ui->pytajnik6->setPixmap(s2);
}
if (losowanie6 == 3)
{
QPixmap s3(":/pliki_spodnie/img/losowanie_img/spodnie_img/spodnie3_wynik.png");
ui->pytajnik6->setPixmap(s3);
}
if (losowanie6 == 4)
{
QPixmap s4(":/pliki_spodnie/img/losowanie_img/spodnie_img/spodnie4_wynik.png");
ui->pytajnik6->setPixmap(s4);
}
if (losowanie6 == 5)
{
QPixmap s5(":/pliki_spodnie/img/losowanie_img/spodnie_img/spodnie5_wynik.png");
ui->pytajnik6->setPixmap(s5);
}
if (losowanie6 == 6)
{
QPixmap s6(":/pliki_spodnie/img/losowanie_img/spodnie_img/spodnie6_wynik.png");
ui->pytajnik6->setPixmap(s6);
}
}
void MainWindow::on_losuj5_clicked()
{
ui->pytajnik5->setStyleSheet("background-color:#040f1e;");
int losowanie5;
srand (time(NULL));
losowanie5 = rand() % 6 + 1;
if (losowanie5 == 1)
{
QPixmap k1(":/pliki_korpus/img/losowanie_img/korpus_img/korpus1_wynik.png");
ui->pytajnik5->setPixmap(k1);
}
if (losowanie5 == 2)
{
QPixmap k2(":/pliki_korpus/img/losowanie_img/korpus_img/korpus2_wynik.png");
ui->pytajnik5->setPixmap(k2);
}
if (losowanie5 == 3)
{
QPixmap k3(":/pliki_korpus/img/losowanie_img/korpus_img/korpus3_wynik.png");
ui->pytajnik5->setPixmap(k3);
}
if (losowanie5 == 4)
{
QPixmap k4(":/pliki_korpus/img/losowanie_img/korpus_img/korpus4_wynik.png");
ui->pytajnik5->setPixmap(k4);
}
if (losowanie5 == 5)
{
QPixmap k5(":/pliki_korpus/img/losowanie_img/korpus_img/korpus5_wynik.png");
ui->pytajnik5->setPixmap(k5);
}
if (losowanie5 == 6)
{
QPixmap k6(":/pliki_korpus/img/losowanie_img/korpus_img/korpus6_wynik.png");
ui->pytajnik5->setPixmap(k6);
}
}
void MainWindow::on_losuj4_clicked()
{
ui->pytajnik4->setStyleSheet("background-color:#040f1e;");
int losowanie4;
srand (time(NULL));
losowanie4 = rand() % 6 + 1;
if (losowanie4 == 1)
{
QPixmap w1(":/pliki_wlosy/img/losowanie_img/wlosy_img/wlosy1_wynik.png");
ui->pytajnik4->setPixmap(w1);
}
if (losowanie4 == 2)
{
QPixmap w2(":/pliki_wlosy/img/losowanie_img/wlosy_img/wlosy2_wynik.png");
ui->pytajnik4->setPixmap(w2);
}
if (losowanie4 == 3)
{
QPixmap w3(":/pliki_wlosy/img/losowanie_img/wlosy_img/wlosy3_wynik.png");
ui->pytajnik4->setPixmap(w3);
}
if (losowanie4 == 4)
{
QPixmap w4(":/pliki_wlosy/img/losowanie_img/wlosy_img/wlosy4_wynik.png");
ui->pytajnik4->setPixmap(w4);
}
if (losowanie4 == 5)
{
QPixmap w5(":/pliki_wlosy/img/losowanie_img/wlosy_img/wlosy5_wynik.png");
ui->pytajnik4->setPixmap(w5);
}
if (losowanie4 == 6)
{
QPixmap w6(":/pliki_wlosy/img/losowanie_img/wlosy_img/wlosy6_wynik.png");
ui->pytajnik4->setPixmap(w6);
}
}
void MainWindow::on_losuj3_clicked()
{
ui->pytajnik3->setStyleSheet("background-color:#040f1e;");
int losowanie3;
srand (time(NULL));
losowanie3 = rand() % 6 + 1;
if (losowanie3 == 1)
{
QPixmap o1(":/pliki_oczy/img/losowanie_img/oczy_img/oczy1_wynik.png");
ui->pytajnik3->setPixmap(o1);
}
if (losowanie3 == 2)
{
QPixmap o2(":/pliki_oczy/img/losowanie_img/oczy_img/oczy2_wynik.png");
ui->pytajnik3->setPixmap(o2);
}
if (losowanie3 == 3)
{
QPixmap o3(":/pliki_oczy/img/losowanie_img/oczy_img/oczy3_wynik.png");
ui->pytajnik3->setPixmap(o3);
}
if (losowanie3 == 4)
{
QPixmap o4(":/pliki_oczy/img/losowanie_img/oczy_img/oczy4_wynik.png");
ui->pytajnik3->setPixmap(o4);
}
if (losowanie3 == 5)
{
QPixmap o5(":/pliki_oczy/img/losowanie_img/oczy_img/oczy5_wynik.png");
ui->pytajnik3->setPixmap(o5);
}
if (losowanie3 == 6)
{
QPixmap o6(":/pliki_oczy/img/losowanie_img/oczy_img/oczy6_wynik.png");
ui->pytajnik3->setPixmap(o6);
}
}
void MainWindow::on_losuj2_clicked()
{
ui->pytajnik2->setStyleSheet("background-color:#040f1e;");
int losowanie2;
srand (time(NULL));
losowanie2 = rand() % 6 + 1;
if (losowanie2 == 1)
{
QPixmap u1(":/pliki_usta/img/losowanie_img/usta_img/usta1_wynik.png");
ui->pytajnik2->setPixmap(u1);
}
if (losowanie2 == 2)
{
QPixmap u2(":/pliki_usta/img/losowanie_img/usta_img/usta2_wynik.png");
ui->pytajnik2->setPixmap(u2);
}
if (losowanie2 == 3)
{
QPixmap u3(":/pliki_usta/img/losowanie_img/usta_img/usta3_wynik.png");
ui->pytajnik2->setPixmap(u3);
}
if (losowanie2 == 4)
{
QPixmap u4(":/pliki_usta/img/losowanie_img/usta_img/usta4_wynik.png");
ui->pytajnik2->setPixmap(u4);
}
if (losowanie2 == 5)
{
QPixmap u5(":/pliki_usta/img/losowanie_img/usta_img/usta5_wynik.png");
ui->pytajnik2->setPixmap(u5);
}
if (losowanie2 == 6)
{
QPixmap u6(":/pliki_usta/img/losowanie_img/usta_img/usta6_wynik.png");
ui->pytajnik2->setPixmap(u6);
}
}
void MainWindow::on_losuj1_clicked()
{
ui->pytajnik1->setStyleSheet("background-color:#040f1e;");
int losowanie1;
srand (time(NULL));
losowanie1 = rand() % 6 + 1;
if (losowanie1 == 1)
{
QPixmap a1(":/pliki_akcesoria/img/losowanie_img/akcesoria_img/akcesoria1_wynik.png");
ui->pytajnik1->setPixmap(a1);
}
if (losowanie1 == 2)
{
QPixmap a2(":/pliki_akcesoria/img/losowanie_img/akcesoria_img/akcesoria2_wynik.png");
ui->pytajnik1->setPixmap(a2);
}
if (losowanie1 == 3)
{
QPixmap a3(":/pliki_akcesoria/img/losowanie_img/akcesoria_img/akcesoria3_wynik.png");
ui->pytajnik1->setPixmap(a3);
}
if (losowanie1 == 4)
{
QPixmap a4(":/pliki_akcesoria/img/losowanie_img/akcesoria_img/akcesoria4_wynik.png");
ui->pytajnik1->setPixmap(a4);
}
if (losowanie1 == 5)
{
QPixmap a5(":/pliki_akcesoria/img/losowanie_img/akcesoria_img/akcesoria5_wynik.png");
ui->pytajnik1->setPixmap(a5);
}
if (losowanie1 == 6)
{
QPixmap a6(":/pliki_akcesoria/img/losowanie_img/akcesoria_img/akcesoria6_wynik.png");
ui->pytajnik1->setPixmap(a6);
}
}
void MainWindow::on_wybierz7_clicked()
{
Buty buty;
buty.setModal(true);
buty.exec();
}
buty.h
#ifndef BUTY_H
#define BUTY_H
#include <QDialog>
#include "mainwindow.h"
#include "QObject"
namespace Ui {
class Buty;
}
class Buty : public QDialog
{
Q_OBJECT
public:
explicit Buty(QWidget *parent = 0);
~Buty();
private slots:
void on_wroc_do_gry_clicked();
public slots:
void on_buty1_clicked();
private:
Ui::Buty* ui;
};
#endif // BUTY_H
buty.cpp
#include "buty.h"
#include "ui_buty.h"
#include "mainwindow.h"
#include "QObject"
Buty::Buty(QWidget *parent) :
QDialog(parent),
ui(new Ui::Buty)
{
ui->setupUi(this);
//QDialog::connect(ui->buty1, SIGNAL(clicked()), QMainWindow, SLOT(pytajnik7()));
connect(ui->buty1, SIGNAL(clicked()), this, SLOT(pytajnik7()));
}
Buty::~Buty()
{
delete ui;
}
void Buty::on_wroc_do_gry_clicked()
{
close();
}
void Buty::on_buty1_clicked()
{
QPixmap b1(":/pliki_buty/img/losowanie_img/buty_img/buty1_wynik.png");
ui->pytajnik7->setPixmap(b1);
}

I interpret the question like:
How can I update the main window widget from other widget code in my
app?
Well, you need the pointer to QMainWindow which is usually the only main window in the widget-based app. You can either create a global pointer variable to QMainWindow or try to find it like that:
// TODO: make it template to resolve specific type?
QMainWindow* findMainWindow()
{
for(QWidget* pWidget : QApplication::topLevelWidgets())
{
QMainWindow pMainWnd = qobject_cast<QMainWindow*>(pWidget);
if (pMainWnd)
return pMainWnd;
}
return nullptr;
}
// UI receives an event that needs to pass the data to main window
void MyWidget::onItemsSelected(const QList<Item>& goods)
{
MyMainWindow* pMainWindow = qobject_cast<MyMainWindow*>(findMainWindow());
if (!pMainWindow)
{
qWarning() << "Cannot find this app main window!";
return;
}
// make it specific to your data
pMainWindow->updateGoodsView( goods );
}

To answer on the title
The reference to the main window in QT
in your code you need to pass you mainwindow to your child window in constructor and then use it via parent() or parentWidget().
So in your code:
void MainWindow::on_wybierz7_clicked()
{
Buty buty(this); //pay attention to this
buty.setModal(true);
buty.exec();
}
...
Buty::Buty(QWidget *parent) :
QDialog(parent),
ui(new Ui::Buty)
{
ui->setupUi(this);
connect(ui->buty1, SIGNAL(clicked()), parent(), SLOT(pytajnik7()));
}
But usually it is bad idea when child dialog "know" about parent slot. Better practice is to make connection in mainwindow code.
For this declare signal in child dialog, e.g. mySignal(). Then connect clicked() signal of the button to your new signal and then make final connection in mainwindow:
void MainWindow::on_wybierz7_clicked()
{
Buty buty(this); //pay attention to this
buty.setModal(true);
connect(&buty, SIGNAL(mySignal()), this, SLOT(pytajnik7()));
buty.exec();
}
...
class Buty : public QDialog
{
Q_OBJECT
...
signals:
void mySignal();
...
};
...
Buty::Buty(QWidget *parent) :
QDialog(parent),
ui(new Ui::Buty)
{
ui->setupUi(this);
connect(ui->buty1, SIGNAL(clicked()), this, SIGNAL(mySignal()));
}
Hope i understood your question correct.

Related

Subclass of QPlainText does not expand to fill the layout

I do not understand why the CodeEditor example from the Qt website does not appear to work as expected. Every time I run the code it displays it like this, really small and not expanding to take up all the available space. Does anyone have any idea why? I have even tried to set a fixed size, sizepolicy and minimum sizing. Not sure what I am missing here.
main.cpp:
#include "mainwindow.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MainWindow w;
w.show();
return a.exec();
}
mainwindow.cpp:
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QVBoxLayout>
#include <QLabel>
#include "codeeditor.h"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent)
{
// controls
auto *widget_main = new QWidget(this);
auto *lay_main = new QVBoxLayout(widget_main);
auto *label = new QLabel("Test");
auto *editor = new CodeEditor();
// layout
lay_main->addWidget(label);
lay_main->addWidget(editor);
lay_main->setContentsMargins(5, 5, 5, 5);
}
MainWindow::~MainWindow()
{
}
codeeditor.h:
#ifndef CODEEDITOR_H
#define CODEEDITOR_H
#include <QPlainTextEdit>
#include <QObject>
class QPaintEvent;
class QResizeEvent;
class QSize;
class QWidget;
class LineNumberArea;
// Main text editor
class CodeEditor : public QPlainTextEdit
{
Q_OBJECT
public:
CodeEditor(QWidget *parent = 0);
void lineNumberAreaPaintEvent(QPaintEvent *event);
int lineNumberAreaWidth();
protected:
void resizeEvent(QResizeEvent *event) override;
private slots:
void updateLineNumberAreaWidth(int newBlockCount);
void highlightCurrentLine();
void updateLineNumberArea(const QRect &, int);
private:
QWidget *lineNumberArea;
};
// Line number gutter
class LineNumberArea : public QWidget
{
public:
LineNumberArea(CodeEditor *editor) : QWidget(editor) {
codeEditor = editor;
}
QSize sizeHint() const override {
return QSize(codeEditor->lineNumberAreaWidth(), 0);
}
protected:
void paintEvent(QPaintEvent *event) override {
codeEditor->lineNumberAreaPaintEvent(event);
}
private:
CodeEditor *codeEditor;
};
#endif
codeeditor.cpp:
#include "codeeditor.h"
#include <QtWidgets>
#include <QFontMetrics>
CodeEditor::CodeEditor(QWidget *parent) : QPlainTextEdit(parent)
{
setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
lineNumberArea = new LineNumberArea(this);
connect(this, SIGNAL(blockCountChanged(int)), this, SLOT(updateLineNumberAreaWidth(int)));
connect(this, SIGNAL(updateRequest(QRect,int)), this, SLOT(updateLineNumberArea(QRect,int)));
connect(this, SIGNAL(cursorPositionChanged()), this, SLOT(highlightCurrentLine()));
updateLineNumberAreaWidth(0);
highlightCurrentLine();
setFixedSize(200, 200);
setMinimumSize(200,200);
}
int CodeEditor::lineNumberAreaWidth()
{
int digits = 1;
int max = qMax(1, blockCount());
while (max >= 10) {
max /= 10;
++digits;
}
//int space = 3 + fontMetrics().horizontalAdvance(QLatin1Char('9')) * digits;
int space = 3 + 12 * digits;
return space;
}
void CodeEditor::updateLineNumberAreaWidth(int /* newBlockCount */)
{
setViewportMargins(lineNumberAreaWidth(), 0, 0, 0);
}
void CodeEditor::updateLineNumberArea(const QRect &rect, int dy)
{
if (dy)
lineNumberArea->scroll(0, dy);
else
lineNumberArea->update(0, rect.y(), lineNumberArea->width(), rect.height());
if (rect.contains(viewport()->rect()))
updateLineNumberAreaWidth(0);
}
void CodeEditor::resizeEvent(QResizeEvent *e)
{
QPlainTextEdit::resizeEvent(e);
QRect cr = contentsRect();
lineNumberArea->setGeometry(QRect(cr.left(), cr.top(), lineNumberAreaWidth(), cr.height()));
}
void CodeEditor::highlightCurrentLine()
{
QList<QTextEdit::ExtraSelection> extraSelections;
if (!isReadOnly()) {
QTextEdit::ExtraSelection selection;
QColor lineColor = QColor(Qt::yellow).lighter(160);
selection.format.setBackground(lineColor);
selection.format.setProperty(QTextFormat::FullWidthSelection, true);
selection.cursor = textCursor();
selection.cursor.clearSelection();
extraSelections.append(selection);
}
setExtraSelections(extraSelections);
}
void CodeEditor::lineNumberAreaPaintEvent(QPaintEvent *event)
{
QPainter painter(lineNumberArea);
painter.fillRect(event->rect(), Qt::lightGray);
QTextBlock block = firstVisibleBlock();
int blockNumber = block.blockNumber();
int top = (int) blockBoundingGeometry(block).translated(contentOffset()).top();
int bottom = top + (int) blockBoundingRect(block).height();
while (block.isValid() && top <= event->rect().bottom()) {
if (block.isVisible() && bottom >= event->rect().top()) {
QString number = QString::number(blockNumber + 1);
painter.setPen(Qt::black);
painter.drawText(0, top, lineNumberArea->width(), fontMetrics().height(),
Qt::AlignRight, number);
}
block = block.next();
top = bottom;
bottom = top + (int) blockBoundingRect(block).height();
++blockNumber;
}
}
QMainWindow is a special widget since it has a preset layout
So you must set the main widget through setCentralWidget():
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
{
auto *widget_main = new QWidget;
auto *lay_main = new QVBoxLayout(widget_main);
auto *label = new QLabel("Test");
auto *editor = new CodeEditor();
setCentralWidget(widget_main); // <-- +++
// layout
lay_main->addWidget(label);
lay_main->addWidget(editor);
lay_main->setContentsMargins(5, 5, 5, 5);
}
On the other hand if you are going to use layouts then you should not set a fixed size to the widget, in your case remove setFixedSize(200, 200) on the other hand it is recommended that you make the connections with the new syntax:
CodeEditor::CodeEditor(QWidget *parent) : QPlainTextEdit(parent)
{
setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
lineNumberArea = new LineNumberArea(this);
connect(this, &QPlainTextEdit::blockCountChanged, this, &CodeEditor::updateLineNumberAreaWidth);
connect(this, &QPlainTextEdit::updateRequest, this, &CodeEditor::updateLineNumberArea);
connect(this, &QPlainTextEdit::cursorPositionChanged, this, &CodeEditor::highlightCurrentLine);
updateLineNumberAreaWidth(0);
highlightCurrentLine();
// setFixedSize(200, 200); <-- ---
setMinimumSize(200,200);
}

Transferring data from one form to another in Qt?

there was such problem. I have a main and auxiliary form. With the second form, I take two values: the index and the color. I'm transferring to the main form. I get the values ​​in the "setParametr" method. But I can not get them in the "paintEvent" method. QDebug show that the method "setParametr" got the values. When I check the values ​​in "on_pushButton_clicked()" values is 0. What could be the problem. Just started to study Qt
dialog.h
class Dialog : public QDialog
{
Q_OBJECT
public:
explicit Dialog(QWidget *parent = 0);
~Dialog();
void setcolor(int);
int getcolor();
void setindex(int);
int getindex();
private slots:
void ColorIndex();
void on_pushButton_clicked();
private:
Ui::Dialog *ui;
int squareColor;
int Index;
};
dialog.cpp
#include "ui_dialog.h"
#include "dialog.h"
#include "mainwindow.h"
#include "QDebug"
Dialog::Dialog(QWidget *parent) :
QDialog(parent),
ui(new Ui::Dialog)
{
ui->setupUi(this);
//connect(ui->pushButton,SIGNAL(clicked()),this,SLOT(ColorIndex()));
}
Dialog::~Dialog()
{
delete ui;
}
void Dialog::setcolor(int color)
{
squareColor = color;
}
int Dialog::getcolor()
{
return squareColor;
}
void Dialog::setindex(int index)
{
Index = index;
}
int Dialog::getindex()
{
return Index;
}
void Dialog::on_pushButton_clicked()
{
MainWindow *main = new MainWindow();
if(ui->radioButton->isChecked()){
setcolor(1);
}
if(ui->radioButton_2->isChecked()){
setcolor(2);
}
if(ui->radioButton_3->isChecked()){
setcolor(3);
}
if(ui->comboBox->currentIndex()==0)
{
setindex(1);
}
if(ui->comboBox->currentIndex()==1)
{
setindex(2);
}
if(ui->comboBox->currentIndex()==2)
{
setindex(3);
}
if(ui->comboBox->currentIndex()==3)
{
setindex(4);
}
qDebug() << QString::number(getcolor());
qDebug() << QString::number(getindex());
main->SetParametr(getindex(),getcolor());
}
mainwindow.h
#include <QWidget>
#include <QPainter>
#include <QPaintEvent>
#include <QPainterPath>
#include <QColor>
#include <QColorDialog>
#include <QPushButton>
#include <QMainWindow>
#include "dialog.h"
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
void setColor(int);
int getColor();
void setIndex(int);
int getIndex();
private:
Dialog *dial = new Dialog();
int fIndex;
int fColor;
private slots:
void on_actionMy_Dialog_triggered();
void paintEvent(QPaintEvent *event);
void on_pushButton_clicked();
signals:
void SetParametr(int index, int color);
private:
Ui::MainWindow *ui;
void onInit();
};
mainwindow.cpp
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "QDebug"
#include "dialog.h"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
fColor = 0;
fIndex =0;
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::SetParametr(int index, int color)
{
fIndex = index;
fColor = color;
qDebug() << QString::number(fColor) + "s";
qDebug() << QString::number(fIndex);
}
/*void MainWindow::setColor(int _color)
{
fColor = _color;
}
int MainWindow::getColor()
{
return fColor;
}
void MainWindow::setIndex(int _index)
{
fIndex = _index;
}
int MainWindow::getIndex()
{
return fIndex;
}
*/
void MainWindow::paintEvent(QPaintEvent *event)
{
QColor red1;
if(fColor==1){
red1 = Qt::red;
}
if(fColor == 2){
red1 = Qt::blue;
}
if(fColor == 3){
red1 = Qt::green;
}
int index1;
if(fIndex == 0)
{
index1 = 0;
}
if(fIndex == 1)
{
index1 = 1;
}
if(fIndex == 2)
{
index1 = 2;
}
if(fIndex == 3)
{
index1 = 3;
}
Q_UNUSED(event);
QPainter painter(this);
if(index1 == 0)
{
painter.setBrush(QBrush(red1, Qt::SolidPattern));
painter.drawEllipse(100, 50, 150, 150);
}
if(index1 == 1)
{
painter.setBrush(QBrush(red1, Qt::SolidPattern));
painter.drawRect(50, 50, 250, 150);
}
if(index1 == 2)
{
painter.setBrush(QBrush(red1, Qt::SolidPattern));
QPolygon polygon;
polygon<<QPoint(175,50)<<QPoint(50,200)<<QPoint(300,200);
painter.drawPolygon(polygon);
}
if(index1 == 3)
{
painter.setBrush(QBrush(red1, Qt::SolidPattern));
painter.drawRect(100, 50, 150, 150);
}
}
void MainWindow::on_actionMy_Dialog_triggered()
{
dial->show();
}
void MainWindow::on_pushButton_clicked()
{
qDebug() << QString::number(fColor);
qDebug() << QString::number(fIndex);
}

QDir is giving correct files, but shows inncorrect amount

In my Qt program, I basically choose a folder, view the contents, and then get the indexed list (0, 1, 2, 3, ........). It shows the correct files (left), but converts more than wanted. Here is and image of the error and code:
MainWindow.h:
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <QFileDialog>
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
void check();
void verify();
void update();
void makeList();
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
private slots:
void on_toolButton_clicked();
void on_pushButton_clicked();
void on_checkBoxDateOrdered_clicked()
{
check();
}
void on_checkBoxInverted_clicked()
{
check();
}
void on_lineEdit_textChanged(const QString &arg1);
void on_pushButtonClear_clicked();
void on_listWidget_currentTextChanged()
{
update();
}
void on_listWidget_2_currentTextChanged()
{
update();
}
private:
Ui::MainWindow *ui;
};
#endif // MAINWINDOW_H
MainWindow.cpp:
#include "mainwindow.h"
#include "ui_mainwindow.h"
QString path;
QStringList before;
QString suffix;
QDir folder;
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
ui->checkBoxDateOrdered->setEnabled(false);
ui->checkBoxInverted->setEnabled(false);
ui->pushButton->setEnabled(false);
ui->pushButtonClear->setEnabled(false);
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::check()
{
ui->listWidget->clear();
if (ui->checkBoxDateOrdered->isChecked() && !ui->checkBoxInverted->isChecked())
{
before = folder.entryList(QDir::Files, QDir::Time);
}
else if (ui->checkBoxInverted->isChecked() && !ui->checkBoxDateOrdered->isChecked())
{
before = folder.entryList(QDir::Files, QDir::Reversed);
}
else if (ui->checkBoxInverted->isChecked() && ui->checkBoxDateOrdered->isChecked())
{
before = folder.entryList(QDir::Files, QDir::Time | QDir::Reversed);
}
else
{
before = folder.entryList(QDir::Files);
}
ui->listWidget->addItems(before);
}
void MainWindow::verify()
{
if (ui->listWidget->count() == 0 && ui->listWidget_2->count() > 0)
{
ui->listWidget_2->clear();
}
else if (ui->listWidget->count() > 0 && ui->listWidget_2->count() == 0)
{
ui->listWidget->clear();
}
else if (ui->listWidget->count() > 0 && ui->listWidget->count() > 0)
{
ui->listWidget->clear();
ui->listWidget_2->clear();
}
}
void MainWindow::update()
{
if (ui->listWidget->count() == 0 && ui->listWidget_2->count() > 0)
{
ui->pushButtonClear->setEnabled(true);
}
else if (ui->listWidget->count() > 0 && ui->listWidget_2->count() == 0)
{
ui->pushButtonClear->setEnabled(true);
}
else if (ui->listWidget->count() > 0 && ui->listWidget->count() > 0)
{
ui->pushButtonClear->setEnabled(true);
}
else
{
ui->pushButtonClear->setEnabled(false);
}
}
void MainWindow::makeList()
{
ui->listWidget->clear();
ui->listWidget_2->clear();
ui->lineEdit->setText(path);
folder.setPath(path);
check();
QString temp = before.at(0);
QStringList pieces = temp.split(".");
suffix = pieces.value(pieces.length() - 1);
int amount = folder.count();
QStringList after;
for (int x = 0; x < amount; x++)
{
after << QString::number(x) + "." + suffix;
}
ui->listWidget_2->addItems(after);
}
void MainWindow::on_toolButton_clicked()
{
path = QFileDialog::getExistingDirectory(this, tr("Open Directory"), "/home", QFileDialog::ShowDirsOnly | QFileDialog::DontResolveSymlinks);
if (path != "")
{
makeList();
}
}
void MainWindow::on_pushButton_clicked()
{
for (int x = 0; x < before.count(); x++)
{
int i = x;
folder.rename(before.at(x), QString::number(i++) + "." + suffix);
}
}
void MainWindow::on_lineEdit_textChanged(const QString &arg1)
{
if (arg1 == "")
{
ui->checkBoxDateOrdered->setEnabled(false);
ui->checkBoxInverted->setEnabled(false);
ui->pushButton->setEnabled(false);
ui->pushButtonClear->setEnabled(false);
}
else if (arg1 != "")
{
ui->checkBoxDateOrdered->setEnabled(true);
ui->checkBoxInverted->setEnabled(true);
ui->pushButton->setEnabled(true);
ui->pushButtonClear->setEnabled(true);
}
}
void MainWindow::on_pushButtonClear_clicked()
{
ui->lineEdit->clear();
verify();
}
Main.cpp:
#include "mainwindow.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MainWindow w;
w.show();
return a.exec();
}
It looks like there are three non-files in the directory. You're interested only in files, but QDir::count reference states:
Returns the total number of directories and files in the directory
Equivalent to entryList().count().
Notice the arguments are defaulted, that's why count returns more. before contains the list of the files, so why not use its count/size/length?
int amount = before.size();

Qt - I can't select any QListWidget item. They are always auto selected from the top down

When I go to select A SINGLE item in my QListWidget, it just selects my item, and all of the ones above it. Also, I would like to know how to get a 'right-click context menu' that I can use when I right click the QListWidget. I'll leave an image and my source code. All help is greatly appreciated. Thank you!
MainWindow:
#include "mainwindow.h"
#include "ui_mainwindow.h"
QString path;
QStringList before;
QStringList suffixes;
QDir folder;
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
ui->checkBoxDateOrdered->setEnabled(false);
ui->checkBoxInverted->setEnabled(false);
ui->pushButton->setEnabled(false);
ui->pushButtonClear->setEnabled(false);
connect(ui->listWidget, SIGNAL(customContextMenuRequested(const QPoint &)), SLOT(showContextMenuForWidget(const QPoint &)));
ui->listWidget->setContextMenuPolicy(Qt::CustomContextMenu);
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::showContextMenuForWidget(const QPoint &pos)
{
QMenu contextMenu(tr("Context menu"), this);
contextMenu.addAction(new QAction(tr("Hello"), this));
contextMenu.exec(mapToGlobal(pos));
}
void MainWindow::check()
{
ui->listWidget->clear();
before.clear();
if (ui->checkBoxDateOrdered->isChecked() && !ui->checkBoxInverted->isChecked())
{
before = folder.entryList(QDir::Files, QDir::Time);
}
else if (ui->checkBoxInverted->isChecked() && !ui->checkBoxDateOrdered->isChecked())
{
before = folder.entryList(QDir::Files, QDir::Reversed);
}
else if (ui->checkBoxInverted->isChecked() && ui->checkBoxDateOrdered->isChecked())
{
before = folder.entryList(QDir::Files, QDir::Time | QDir::Reversed);
}
else
{
before = folder.entryList(QDir::Files);
}
ui->statusBar->clearMessage();
ui->statusBar->showMessage(QString::number(before.size()) + " file(s) found. ");
ui->listWidget->addItems(before);
suffixGet();
}
void MainWindow::verify()
{
before.clear();
check();
suffixes.clear();
suffixGet();
ui->listWidget->clear();
ui->listWidget_2->clear();
ui->statusBar->clearMessage();
}
void MainWindow::update()
{
before.clear();
check();
if (ui->listWidget->count() == 0 && ui->listWidget_2->count() > 0)
{
ui->pushButtonClear->setEnabled(true);
}
else if (ui->listWidget->count() > 0 && ui->listWidget_2->count() == 0)
{
ui->pushButtonClear->setEnabled(true);
}
else if (ui->listWidget->count() > 0 && ui->listWidget->count() > 0)
{
ui->pushButtonClear->setEnabled(true);
}
else
{
ui->pushButtonClear->setEnabled(false);
}
}
void MainWindow::makeList()
{
check();
suffixes.clear();
suffixGet();
ui->listWidget->clear();
ui->listWidget_2->clear();
ui->statusBar->clearMessage();
folder.setPath(path);
check();
ui->statusBar->showMessage(QString::number(before.size()) + " file(s) found. " + " Path: " + path);
}
void MainWindow::suffixGet()
{
ui->listWidget_2->clear();
QStringList temp;
QString suffix;
QString temp2;
QStringList after;
for (int x = 0; x < before.size(); x++)
{
temp2 = before.at(x);
temp = temp2.split(".");
suffix = "." + temp.value(temp.length() - 1);
suffixes << suffix;
after << QString::number(x) + suffix;
}
ui->listWidget_2->addItems(after);
}
void MainWindow::on_toolButton_clicked()
{
before.clear();
suffixes.clear();
suffixGet();
path.clear();
path = QFileDialog::getExistingDirectory(this, tr("Open Directory"), "/home", QFileDialog::ShowDirsOnly | QFileDialog::DontResolveSymlinks);
if (path != "")
{
makeList();
}
ui->lineEdit->setText(path);
}
void MainWindow::on_pushButton_clicked()
{
before.clear();
check();
suffixes.clear();
suffixGet();
for (int x = 0; x < before.size(); x++)
{
int i = x;
folder.rename(before.at(x), QString::number(i++) + suffixes.at(x));
}
}
void MainWindow::on_lineEdit_textChanged(const QString &arg1)
{
before.clear();
suffixes.clear();
suffixGet();
check();
ui->listWidget->clear();
ui->listWidget_2->clear();
if (arg1 == "")
{
ui->checkBoxDateOrdered->setEnabled(false);
ui->checkBoxInverted->setEnabled(false);
ui->pushButton->setEnabled(false);
ui->pushButtonClear->setEnabled(false);
ui->statusBar->clearMessage();
}
else if (arg1 != "")
{
if (QDir(arg1).exists())
{
ui->checkBoxDateOrdered->setEnabled(true);
ui->checkBoxInverted->setEnabled(true);
ui->pushButton->setEnabled(true);
ui->pushButtonClear->setEnabled(true);
path = arg1;
makeList();
}
else
{
ui->statusBar->showMessage("Invalid path!");
}
}
}
void MainWindow::on_pushButtonClear_clicked()
{
before.clear();
suffixes.clear();
suffixGet();
ui->lineEdit->clear();
verify();
}
Main.cpp:
#include "mainwindow.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MainWindow w;
w.show();
return a.exec();
}
MainWindow.h:
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <QFileDialog>
#include <QMenu>
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
void check();
void verify();
void update();
void makeList();
void suffixGet();
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
private slots:
void on_toolButton_clicked();
void on_pushButton_clicked();
void on_checkBoxDateOrdered_clicked()
{
check();
}
void on_checkBoxInverted_clicked()
{
check();
}
void on_lineEdit_textChanged(const QString &arg1);
void on_pushButtonClear_clicked();
void on_listWidget_currentTextChanged()
{
update();
}
void on_listWidget_2_currentTextChanged()
{
update();
}
public slots:
void showContextMenuForWidget(const QPoint &pos);
private:
Ui::MainWindow *ui;
};
#endif // MAINWINDOW_H

Adding Text in GraphicsView in Qt

I am implementing a code to add different entities on a button click.I am getting a problem to add Text in graphics view. Following is the code snippet that I am implementing. What needs to be done?
mainwindow.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <QPaintEvent>
#include <QGraphicsScene>
#include <QGraphicsView>
#include <QPainter>
#include "line.h"
#include "circle.h"
#include "ellipse.h"
#include "point.h"
#include "arc.h"
#include "text.h"
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
protected:
void wheelEvent(QWheelEvent* event);
private:
Ui::MainWindow *ui;
bool mFirstClick;
bool mPaintFlag;
int mStartX;
int mStartY;
int mEndX;
int mEndY;
QGraphicsScene *scene;
QPainter *painter;
point *item;
line *item1;
circle *item2;
ellipse *item3;
arc *item4;
private slots:
void drawPoint();
void drawLine();
void drawCircle();
void drawEllipse();
void drawArc();
void drawText();
void on_actionSave_triggered();
void on_actionOpen_triggered();
void on_actionQuit_2_triggered();
};
#endif // MAINWINDOW_H
mainwindow.cpp
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QMouseEvent>
#include<QFileDialog>
#include<QMessageBox>
#include<QTextEdit>
#include<QString>
#include <QDebug>
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent), ui(new Ui::MainWindow)
{
ui->setupUi(this);
setWindowTitle(tr("GD CAD"));
scene = new QGraphicsScene;
for(int x = 0; x <= ui->graphicsView->width(); x += 10){
scene->addLine(x,0,x,ui->graphicsView->height(),QPen(Qt::green));
}
for(int y = 0; y <= ui->graphicsView->height(); y += 10){
scene->addLine(0,y,ui->graphicsView->width(),y,QPen(Qt::green));
}
for(int x = 10; x <= ui->graphicsView->width(); x += 100){
scene->addLine(x,0,x,ui->graphicsView->height(),QPen(Qt::darkGreen));
}
for(int y = 10; y <= ui->graphicsView->height(); y += 100){
scene->addLine(0,y,ui->graphicsView->width(),y,QPen(Qt::darkGreen));
}
ui->graphicsView->setScene(scene);
connect(ui->pointButton, SIGNAL(clicked()), this, SLOT(drawPoint()));
connect(ui->lineButton, SIGNAL(clicked()), this, SLOT(drawLine()));
connect(ui->circleButton, SIGNAL(clicked()), this, SLOT(drawCircle()));
connect(ui->ellipseButton, SIGNAL(clicked()), this, SLOT(drawEllipse()));
connect(ui->arcButton, SIGNAL(clicked()),this, SLOT(drawArc()));
connect(ui->text,SIGNAL(clicked()),this,SLOT(drawText()));
connect(ui->actionPoints, SIGNAL(triggered()), this, SLOT(drawPoint()));
connect(ui->actionLine, SIGNAL(triggered()), this, SLOT(drawLine()));
connect(ui->actionCircle, SIGNAL(triggered()), this, SLOT(drawCircle()));
connect(ui->actionEllipse, SIGNAL(triggered()), this, SLOT(drawEllipse()));
}
void MainWindow::drawPoint(){
ui->graphicsView->setScene(scene);
item = new point;
scene->addItem(item);
qDebug() << "Point Created";
connect(item, SIGNAL(DrawFinished()), this, SLOT(drawPoint()));
}
void MainWindow::drawLine(){
ui->graphicsView->setScene(scene);
item1 = new line;
scene->addItem(item1);
qDebug() << "Line Created";
connect(item1, SIGNAL(DrawFinished()), this, SLOT(drawLine()));
}
void MainWindow::drawCircle(){
ui->graphicsView->setScene(scene);
item2 = new circle;
scene->addItem(item2);
qDebug() << "Circle Created";
connect(item2, SIGNAL(DrawFinished()), this, SLOT(drawCircle()));
}
void MainWindow::drawArc(){
ui->graphicsView->setScene(scene);
item4 = new arc;
scene->addItem(item4);
qDebug() << "Circle Created";
connect(item4, SIGNAL(DrawFinished()), this, SLOT(drawArc()));
}
void MainWindow::drawEllipse(){
ui->graphicsView->setScene(scene);
item3 = new ellipse;
scene->addItem(item3);
qDebug() << "Ellipse Created";
connect(item3, SIGNAL(DrawFinished()), this, SLOT(drawEllipse()));
}
void MainWindow::wheelEvent(QWheelEvent* event) {
ui->graphicsView->setTransformationAnchor(QGraphicsView::AnchorUnderMouse);
// Scale the view / do the zoom
double scaleFactor = 1.15;
if(event->delta() > 0) {
// Zoom in
ui->graphicsView->scale(scaleFactor, scaleFactor);
} else {
// Zooming out
ui->graphicsView->scale(1.0 / scaleFactor, 1.0 / scaleFactor);
}
}
void MainWindow::on_actionOpen_triggered()
{
QString filename=QFileDialog::getOpenFileName(
this,
tr("Open File"),
QString(),
tr("file Name(*.dwg|*.DWG|*.dxf)")
);
if (!filename.isEmpty()) {
QFile file(filename);
if (!file.open(QIODevice::ReadOnly)) {
QMessageBox::critical(this,
tr("Error"), tr("Could not open file"));
return;
}
}
}
void MainWindow::on_actionSave_triggered()
{
QString filename=QFileDialog::getSaveFileName(
this,
tr("Save File"),
QString(),
tr("file Name(*.txt)")
);
if(!filename.isEmpty()) {
QFile file(filename);
if (!file.open(QIODevice::WriteOnly)) {
QMessageBox::critical(this, tr("Error"), tr("Could not open file"));
return;
} else {
QTextStream stream(&file);
QTextEdit *textEdit;
stream << textEdit->toPlainText();
stream.flush();
file.close();
}
}
}
void MainWindow::on_actionQuit_2_triggered(){
MainWindow *window;
window->close();
}
void MainWindow::drawText(){
ui->graphicsView->setScene(scene);
text *item5 = new text;
scene->addItem(item5);
qDebug() << "text created";
connect(item5, SIGNAL(DrawFinished()), this, SLOT(drawText()));
}
MainWindow::~MainWindow()
{
delete ui;
}
text.h
#ifndef TEXT_H
#define TEXT_H
#include <QGraphicsTextItem>
#include <QPen>
#include<QFocusEvent>
#include<QGraphicsItem>
#include<QGraphicsScene>
#include<QGraphicsSceneMouseEvent>
#include<QGraphicsTextItem>
#include<QFont>
#include"mainwindow.h"
#include"ui_mainwindow.h"
class text:public QGraphicsTextItem
{
Q_OBJECT
public:
enum { Type = UserType + 3 };
enum Mode { InsertText };
void setFont(const QFont &font);
text(QGraphicsItem *parent = 0);
int type() const { return Type; }
public slots:
void setMode(Mode mode);
signals:
void lostFocus(text *item);
void selectedChange(QGraphicsItem *item);
void textInserted(QGraphicsTextItem *item);
void itemSelected(QGraphicsItem *item);
protected:
QVariant itemChange(GraphicsItemChange change, const QVariant &value);
void focusOutEvent(QFocusEvent *event);
void mouseDoubleClickEvent(QGraphicsSceneMouseEvent *event);
void mousePressEvent(QGraphicsSceneMouseEvent *mouseEvent);
private:
Mode myMode;
QFont myFont;};
#endif // TEXT_H
text.cpp
#include "text.h"
#include"mainwindow.h"
#include"ui_mainwindow.h"
text::text(QGraphicsItem *parent):QGraphicsTextItem(parent)
{
setFlag(QGraphicsItem::ItemIsMovable);
setFlag(QGraphicsItem::ItemIsSelectable);
}
QVariant text::itemChange(GraphicsItemChange change,
const QVariant &value)
{
if (change == QGraphicsItem::ItemSelectedHasChanged)
emit selectedChange(this);
return value;
}
void text::focusOutEvent(QFocusEvent *event)
{
setTextInteractionFlags(Qt::NoTextInteraction);
emit lostFocus(this);
QGraphicsTextItem::focusOutEvent(event);
}
void text::setMode(Mode mode)
{
myMode = mode;
}
void text::mouseDoubleClickEvent(QGraphicsSceneMouseEvent *event)
{
if (textInteractionFlags() == Qt::NoTextInteraction)
setTextInteractionFlags(Qt::TextEditorInteraction);
QGraphicsTextItem::mouseDoubleClickEvent(event);
}
void text::mousePressEvent(QGraphicsSceneMouseEvent *mouseEvent)
{
if (mouseEvent->button() != Qt::LeftButton)
return;
switch(myMode){
case InsertText:
text *textItem;
textItem = new text();
// textItem->setFont(myFont);
textItem->setPlainText("hello");
textItem->setTextInteractionFlags(Qt::TextEditorInteraction);
textItem->setZValue(1000.0);
connect(textItem, SIGNAL(lostFocus(DiagramTextItem*)),
this, SLOT(editorLostFocus(DiagramTextItem*)));
connect(textItem, SIGNAL(selectedChange(QGraphicsItem*)),
this, SIGNAL(itemSelected(QGraphicsItem*)));
//addItem(textItem);
// textItem->setDefaultTextColor(myTextColor);
textItem->setPos(mouseEvent->scenePos());
emit textInserted(textItem);
//! [8] //! [9]
default:
;
}
// QGraphicsScene::mousePressEvent(mouseEvent);
}
Hm, if i am not mistaken, it does look like you are setting all kinds of properties of the text item, like Interaction-flags, z-value, color and so on -- everything but not the actual text. The text would be empty and therefore your QGraphicsTextItem will be invisible.
Use setPlainText(), setHtml() or setDocument() on your text item.
There are two places where text-items are created; one is in the mainwindow.cpp:
void MainWindow::drawText(){
ui->graphicsView->setScene(scene);
text *item5 = new text;
scene->addItem(item5);
qDebug() << "text created";
connect(item5, SIGNAL(DrawFinished()), this, SLOT(drawText()));
}
The text is created and added to the scene (with addItem()), but it does not have an actual content; set its content:
item5->setPlainText ("Mickey");
The second text-item is created from inside the text (which is a subclass of a QGraphicsTextItem) class itself:
void text::mousePressEvent(QGraphicsSceneMouseEvent *mouseEvent)
{
...
switch(myMode){
case InsertText:
text *textItem;
textItem = new text();
// textItem->setFont(myFont);
textItem->setPlainText("hello");
It is created correctly, and given a text, but not added to the scene. Add it to the scene, for instance by making it a child of the current text item:
textItem->setParentItem (this);