I would like to make a simple QT mainwindow with the button to open a second window or dialog. I followed literally the step from the QT link «Using a Designer UI File in Your Application» and following the single inheritance example.
But QT gives 4 errors , which you will see a snapshot of below.
Now, what I did is I created a mainwindow in Qt designer, then I added a second form to the project , which will be the second dialog window when a button clicked. Because I created the form manually «mydialog.ui», I added class «mydialog.h and mydialog.cpp» and put the header of «ui-mydialog» in the source file «mydialog.cpp».
I’ not sure what am I missing ?
Below is the code :
— mydialog.h
#ifndef MYDIALOG_H
#define MYDIALOG_H
#include<QWidget>
class mydialog ;
namespace Ui {
class mydialog;
}
class mydialog : public QWidget
{
Q_OBJECT
public:
explicit mydialog(QWidget *parent = 0);
virtual ~mydialog();
private :
Ui::mydialog *ui;
};
#endif // MYDIALOG_H
— mainwindow.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QtCore/QtGlobal>
#include <QMainWindow>
QT_USE_NAMESPACE
QT_BEGIN_NAMESPACE
namespace Ui {
class MainWindow;
}
QT_END_NAMESPACE
class mydialog;
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
private slots:
void on_Start_clicked();
private:
Ui::MainWindow *ui;
mydialog *dialog1;
};
#endif // MAINWINDOW_H
— mydialog.cpp
#include"mydialog.h"
#include "ui_mydialog.h"
mydialog::mydialog(QWidget *parent) : QWidget(parent), ui(new Ui::mydialog)
{
ui->setupUi(this);
}
mydialog::~mydialog()
{
delete ui;
}
— mainwindow.cpp
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include"mydialog.h"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
dialog1 = new mydialog ;
}
MainWindow::~MainWindow()
{
delete ui;
delete dialog1;
}
void MainWindow::on_Start_clicked()
{
}
— main.cpp
#include"mainwindow.h"
#include<QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MainWindow w;
w.show();
return a.exec();
}
— The .pro file
#-------------------------------------------------
#
# Project created by QtCreator 2015-12-17T00:10:58
#
#-------------------------------------------------
QT += core gui
greaterThan(QT_MAJOR_VERSION, 4): QT += widgets
TARGET = TestTool
TEMPLATE = app
SOURCES += main.cpp
mainwindow.cpp
mydialog.cpp
HEADERS += mainwindow.h
mydialog.h
FORMS += mainwindow.ui
mydialog.ui
RESOURCES +=
misc.qrc
— Qt compilation output error
Compilation error
The generated file Ui_mydialog.h is :
#ifndef UI_MYDIALOG_H
#define UI_MYDIALOG_H
#include <QtCore/QVariant>
#include <QtWidgets/QAction>
#include <QtWidgets/QApplication>
#include <QtWidgets/QButtonGroup>
#include <QtWidgets/QDialog>
#include <QtWidgets/QDialogButtonBox>
#include <QtWidgets/QHeaderView>
QT_BEGIN_NAMESPACE
class Ui_Dialog
{
public:
QDialogButtonBox *buttonBox;
void setupUi(QDialog *Dialog)
{
if (Dialog->objectName().isEmpty())
Dialog->setObjectName(QStringLiteral("Dialog"));
Dialog->resize(400, 300);
buttonBox = new QDialogButtonBox(Dialog);
buttonBox->setObjectName(QStringLiteral("buttonBox"));
buttonBox->setGeometry(QRect(30, 240, 341, 32));
buttonBox->setOrientation(Qt::Horizontal);
buttonBox->setStandardButtons(QDialogButtonBox::Cancel|QDialogButtonBox::Ok);
retranslateUi(Dialog);
QObject::connect(buttonBox, SIGNAL(accepted()), Dialog, SLOT(accept()));
QObject::connect(buttonBox, SIGNAL(rejected()), Dialog, SLOT(reject()));
QMetaObject::connectSlotsByName(Dialog);
} // setupUi
void retranslateUi(QDialog *Dialog)
{
Dialog->setWindowTitle(QApplication::translate("Dialog", "Dialog", 0));
} // retranslateUi
};
namespace Ui {
class Dialog: public Ui_Dialog {};
} // namespace Ui
QT_END_NAMESPACE
#endif // UI_MYDIALOG_H
Update: Forum Guidelines & Code of Conduct
Qt World Summit: Early-Bird Tickets
This topic has been deleted. Only users with topic management privileges can see it.
-
C:UsersLorence30Desktoptestmainwindow.h:32: error: invalid use of incomplete type ‘class Ui::MainWindow’ ui->grassyTile
^why i keep getting this error?
I have my Q_OBJECT macro inside the MainWindow class.
*[link text](link url) class MainWindow : public QMainWindow
{
Q_OBJECTpublic:
explic[it MainWindow(QWidget *parent = 0);
~MainWindow();](link url)private slots:
void changeTile();
void pushTile();private:
Ui::MainWindow *ui;
int counter;std::array<Tile,1> tile_list { ui->grassyTile // heres where error coming from };
};
-
@Lorence said:
grassyTile
What type is that ?
«use of incomplete type» often means a include file is missing
or you forwarded a class
like
class SomeClass;And try to use it in a context where it needs to be fully defined.
Like adding to some template lists.Not sure what you tried to define here ?
std::array<Tile,1> tile_list <—- ; missing here?
{
ui->grassyTile // heres where error coming from
}; -
grassyTile is of type Tile that is inheriting QLabel
Not sure what you tried to define here ?
i dont know how to list intialize an array on constructor so i decided to do it in side a class definition -
@mrjj said:
and «tile.h» is included ?
in mainwindow.hdo you mean like ?
std::array<std::string, 2> strings = {{ «a», «b» }}; -
and «tile.h» is included ?
yes i got all i need included.
do you mean like ?
std::array<std::string, 2> strings = {{ «a», «b» }};yes, in the mainwindow.cpp i can freely use ui->grassyTile; without error.
-
@Lorence
Ok so it must be the tile_list statement.Would it like
std::array<Tile,1> tile_list {{ui->grassyTile }}; -
Would it like
std::array<Tile,1> tile_list {{ui->grassyTile }};thanks for the help but i still get the same error
-
@Lorence
Ok, and you are 100% it knows the tile type here?
you can declare one over the tile_list and it will like it ?
Tile *Test;One thing I wonder, you say
std::array<Tile> and not std::array<Tile *) or & so it must make a copy of
it (the tile). Is that the effect you want? -
@Lorence
Hmm it seems its «ui» it do not like.
Let me test. -
@mrjj
ahh, Ui::MainWindow is defined in
#include «ui_main_window.h»
which is included in the CPP file so the type is not fully defined so you cannot say
ui->Somename
as Ui::MainWindow is not defined yet.moving
#include «ui_main_window.h»
to the minwin.h file allows it but not sure if it will confuse Qt Creator.Also it will complain about not being able to convert Tile to Tile * as list is not pointers and ui->grassyTile will be.
-
ahh, Ui::MainWindow is defined in
#include «ui_main_window.h»didnt think of that, thanks! but new error comes
-
@Lorence
Yeah, it tries to construct a new Tile to go into the list.
Can I ask if you want a list of pointers to tiles you have on screen or
a list with new Tiles that has nothing to do with those on screen? -
sorry for the late reply.
i just want a list of tiles to choose from.
but QT disabled the copying of QLabel,
so i really need to have a pointer of tiles? -
@Lorence
heh 9 mins is not considered latethen the list must be pointer type or it will be new ones and not the ones on screen.
so
std::array<Tile> should be std::array<Tile *> or std::array<Tile &>
so its the ones on screen and not new ones
Yes you must at least use & as it must «point» to the real one. -
then the list must be pointer type
yea, i edited my last replyit will be new ones and not the ones on screen.
it is the ones on the screen, there will be a list of tiles on the screen and the user will choose what tiles they want to render
*so
std::array<Tile> should be std::array<Tile > or std::array<Tile &>
so its the ones on screen and not new ones
Yes you must at least use & as it must «point» to the real one.thanks!!!!!!!!
all my problem is fixed
I have not coded for weeks and C++ is already kicking me damit
-
@mrjj said:
ok. Superand tile_list is the ones to choose from ?
Dont worry. I programmed c++ for 20 years and it still kicks me
-
and tile_list is the ones to choose from ?
yes, it is a list of Tile which is inheriting QLabel
Dont worry. I programmed c++ for 20 years and it still kicks me
woaaaaa, me is about a year, and started this QT last week, i choose this for my tile engine’s interface from SFML, i still have more ways to go !^_^
-
@Lorence said:
welcome on board to Qt. its a nice frame work.Oh so its some sort of game editor your are making ?
-
welcome on board to Qt. its a nice frame work.
Yes my first choice is wxwidget and windows form application, but signals and slots mechanism of qt makes me decide to choose qt
Oh so its some sort of game editor your are making ?
yes exatcly, like the rpg maker vx ace of steam
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 |
#include "dialogadddevice.h" #include "ui_dialogadddevice.h" DialogAddDevice::DialogAddDevice(int row, QWidget *parent) : QDialog(parent), ui(new Ui::DialogAddDevice) { ui->setupUi(this); /* Метода для инициализации модели, * из которой будут транслироваться данные * */ setupModel(); /* Если строка не задана, то есть равна -1, * тогда диалог работает по принципу создания новой записи. * А именно, в модель вставляется новая строка и работа ведётся с ней. * */ if(row == -1){ model->insertRow(model->rowCount(QModelIndex())); mapper->toLast(); /* В противном случае диалог настраивается на заданную запись * */ } else { mapper->setCurrentModelIndex(model->index(row,0)); } createUI(); } DialogAddDevice::~DialogAddDevice() { delete ui; } /* Метод настройки модели данных и mapper * */ void DialogAddDevice::setupModel() { /* Инициализируем модель и делаем выборку из неё * */ model = new QSqlTableModel(this); model->setTable(DEVICE); model->setEditStrategy(QSqlTableModel::OnManualSubmit); model->select(); /* Инициализируем mapper и привязываем * поля данных к объектам LineEdit * */ mapper = new QDataWidgetMapper(); mapper->setModel(model); mapper->addMapping(ui->HostnameLineEdit, 1); mapper->addMapping(ui->IPAddressLineEdit, 2); mapper->addMapping(ui->MACLineEdit, 3); /* Ручное подтверждение изменения данных * через mapper * */ mapper->setSubmitPolicy(QDataWidgetMapper::ManualSubmit); /* Подключаем коннекты от кнопок пролистывания * к прилистыванию модели данных в mapper * */ connect(ui->previousButton, SIGNAL(clicked()), mapper, SLOT(toPrevious())); connect(ui->nextButton, SIGNAL(clicked()), mapper, SLOT(toNext())); /* При изменении индекса в mapper изменяем состояние кнопок * */ connect(mapper, SIGNAL(currentIndexChanged(int)), this, SLOT(updateButtons(int))); } /* Метод для установки валидатора на поле ввода IP и MAC адресов * */ void DialogAddDevice::createUI() { QString ipRange = "(?:[0-1]?[0-9]?[0-9]|2[0-4][0-9]|25[0-5])"; QRegExp ipRegex ("^" + ipRange + "\." + ipRange + "\." + ipRange + "\." + ipRange + "$"); QRegExpValidator *ipValidator = new QRegExpValidator(ipRegex, this); ui->IPAddressLineEdit->setValidator(ipValidator); QString macRange = "(?:[0-9A-Fa-f][0-9A-Fa-f])"; QRegExp macRegex ("^" + macRange + "\:" + macRange + "\:" + macRange + "\:" + macRange + "\:" + macRange + "\:" + macRange + "$"); QRegExpValidator *macValidator = new QRegExpValidator(macRegex, this); ui->MACLineEdit->setValidator(macValidator); } void DialogAddDevice::on_buttonBox_accepted() { /* SQL-запрос для проверки существования записи * с такими же учетными данными. * Если запись не существует или находится лишь индекс * редактируемой в данный момент записи, * то диалог позволяет вставку записи в таблицу данных * */ QSqlQuery query; QString str = QString("SELECT EXISTS (SELECT " DEVICE_HOSTNAME " FROM " DEVICE " WHERE ( " DEVICE_HOSTNAME " = '%1' " " OR " DEVICE_IP " = '%2' )" " AND id NOT LIKE '%3' )") .arg(ui->HostnameLineEdit->text(), ui->IPAddressLineEdit->text(), model->data(model->index(mapper->currentIndex(),0), Qt::DisplayRole).toString()); query.prepare(str); query.exec(); query.next(); /* Если запись существует, то диалог вызывает * предупредительное сообщение * */ if(query.value(0) != 0){ QMessageBox::information(this, trUtf8("Ошибка хоста"), trUtf8("Хост с таким именем или IP-адресом уже существует")); /* В противном случае производится вставка новых данных в таблицу * и диалог завершается с передачей сигнала для обновления * таблицы в главном окне * */ } else { mapper->submit(); model->submitAll(); emit signalReady(); this->close(); } } void DialogAddDevice::accept() { } /* Метод изменения состояния активности кнопок пролистывания * */ void DialogAddDevice::updateButtons(int row) { /* В том случае, если мы достигаем одного из крайних (самый первый или * самый последний) из индексов в таблице данных, * то мы изменяем состояние соответствующей кнопки на * состояние неактивна * */ ui->previousButton->setEnabled(row > 0); ui->nextButton->setEnabled(row < model->rowCount() - 1); } |
-
Home -
Qt Development -
General and Desktop -
[SOLVED] Invalid use of incomplete type ‘class UI::MainWindow’
Congratulations to our 2022 Qt Champions!
This topic has been deleted. Only users with topic management privileges can see it.
-
C:UsersLorence30Desktoptestmainwindow.h:32: error: invalid use of incomplete type ‘class Ui::MainWindow’ ui->grassyTile
^why i keep getting this error?
I have my Q_OBJECT macro inside the MainWindow class.
*[link text](link url) class MainWindow : public QMainWindow
{
Q_OBJECTpublic:
explic[it MainWindow(QWidget *parent = 0);
~MainWindow();](link url)private slots:
void changeTile();
void pushTile();private:
Ui::MainWindow *ui;
int counter;std::array<Tile,1> tile_list { ui->grassyTile // heres where error coming from };
};
-
@Lorence said:
grassyTile
What type is that ?
«use of incomplete type» often means a include file is missing
or you forwarded a class
like
class SomeClass;And try to use it in a context where it needs to be fully defined.
Like adding to some template lists.Not sure what you tried to define here ?
std::array<Tile,1> tile_list <—- ; missing here?
{
ui->grassyTile // heres where error coming from
};
-
grassyTile is of type Tile that is inheriting QLabel
Not sure what you tried to define here ?
i dont know how to list intialize an array on constructor so i decided to do it in side a class definition
-
@mrjj said:
and «tile.h» is included ?
in mainwindow.hdo you mean like ?
std::array<std::string, 2> strings = {{ «a», «b» }};
-
and «tile.h» is included ?
yes i got all i need included.
do you mean like ?
std::array<std::string, 2> strings = {{ «a», «b» }};yes, in the mainwindow.cpp i can freely use ui->grassyTile; without error.
-
@Lorence
Ok so it must be the tile_list statement.Would it like
std::array<Tile,1> tile_list {{ui->grassyTile }};
-
Would it like
std::array<Tile,1> tile_list {{ui->grassyTile }};thanks for the help but i still get the same error
-
@Lorence
Ok, and you are 100% it knows the tile type here?
you can declare one over the tile_list and it will like it ?
Tile *Test;One thing I wonder, you say
std::array<Tile> and not std::array<Tile *) or & so it must make a copy of
it (the tile). Is that the effect you want?
-
-
@Lorence
Hmm it seems its «ui» it do not like.
Let me test.
-
@mrjj
ahh, Ui::MainWindow is defined in
#include «ui_main_window.h»
which is included in the CPP file so the type is not fully defined so you cannot say
ui->Somename
as Ui::MainWindow is not defined yet.moving
#include «ui_main_window.h»
to the minwin.h file allows it but not sure if it will confuse Qt Creator.Also it will complain about not being able to convert Tile to Tile * as list is not pointers and ui->grassyTile will be.
-
ahh, Ui::MainWindow is defined in
#include «ui_main_window.h»didnt think of that, thanks! but new error comes
View post on imgur.com
-
@Lorence
Yeah, it tries to construct a new Tile to go into the list.
Can I ask if you want a list of pointers to tiles you have on screen or
a list with new Tiles that has nothing to do with those on screen?
-
sorry for the late reply.
i just want a list of tiles to choose from.
but QT disabled the copying of QLabel,
so i really need to have a pointer of tiles?
-
@Lorence
heh 9 mins is not considered latethen the list must be pointer type or it will be new ones and not the ones on screen.
so
std::array<Tile> should be std::array<Tile *> or std::array<Tile &>
so its the ones on screen and not new ones
Yes you must at least use & as it must «point» to the real one.
-
then the list must be pointer type
yea, i edited my last replyit will be new ones and not the ones on screen.
it is the ones on the screen, there will be a list of tiles on the screen and the user will choose what tiles they want to render
*so
std::array<Tile> should be std::array<Tile > or std::array<Tile &>
so its the ones on screen and not new ones
Yes you must at least use & as it must «point» to the real one.thanks!!!!!!!!
all my problem is fixed
I have not coded for weeks and C++ is already kicking me damit
-
@mrjj said:
ok. Superand tile_list is the ones to choose from ?
Dont worry. I programmed c++ for 20 years and it still kicks me
-
and tile_list is the ones to choose from ?
yes, it is a list of Tile which is inheriting QLabel
Dont worry. I programmed c++ for 20 years and it still kicks me
woaaaaa, me is about a year, and started this QT last week, i choose this for my tile engine’s interface from SFML, i still have more ways to go !^_^
-
@Lorence said:
welcome on board to Qt. its a nice frame work.Oh so its some sort of game editor your are making ?
-
welcome on board to Qt. its a nice frame work.
Yes my first choice is wxwidget and windows form application, but signals and slots mechanism of qt makes me decide to choose qt
Oh so its some sort of game editor your are making ?
yes exatcly, like the rpg maker vx ace of steam
-
@Lorence
Well IMHO Qt is more feature rich than wxwidget even I did like that also.Oh. Wow. thats a huge project. !
So its an editor and and tile engine for making tile games. Pretty cool.
-
Well IMHO Qt is more feature rich than wxwidget even I did like that also.
yea, in other forum’s debation, QT always win, whats IMHO?Oh. Wow. thats a huge project. !
yes this is a huge project for me XD,
and i still got no idea about integrating script language into this project
-
@Lorence
IMHO = In my humble opinion
Well I tested both and choose Qt.Would also be huge for me to make as single person if we are talking full
game editor and engineI would have a good look at http://doc.qt.io/qt-5/qtscript-index.html
Should be fast enough and quite easy to mix c++ and script.
-
I see
Im planning to finish this as in 100%
I would have a good look at http://doc.qt.io/qt-5/qtscript-index.html
Should be fast enough and quite easy to mix c++ and script.thanks!
We have group on skype do you want to join?
-
@Lorence
ok. to make it a full product? To sell or make games and sell ?— We have group on skype do you want to join?
Oh thanks for the offer but I only use skype at work as I sit in the living room and
taking in mics drives the others crazy
So no Team Speak for me eitherSo you are a group of people making this?
-
ok. to make it a full project ? To sell or make games and sell ?
I want to sell the whole project. i dont want wasting time doing things that is unrelated to programming so i dont want to make games and sell.okay i see np.
So you are a group of people making this?
No im the only one making this. the skype group is a group of programmers experts and newbies. just for teaching things
-
@Lorence
Ok, a game maker product.
You should also consider how to handle support.
Takes more time than one realizes.Ah, that way. Did not know skype has such forums/groups.
Really good luck with it.
-
yea thanks.
Ah, that way. Did not know skype has such forums/groups.
oh no, im really bad at explaining things. i mean
you can create a conversation group in skype and invite people as many as you can. so i just found this group and then i joinedokay thanks again
-
my friends,i had a similar case and found this happens when you mix different versions of Qt to compile the project
they simply change the ui_*.h files or sometimes they empty it and thus this happens. Occured at least with me ..
-
@mrjj Thanks, you are right for saying that some header files might be missing.
I would like to make a simple QT mainwindow with the button to open a second window or dialog. I followed literally the step from the QT link «Using a Designer UI File in Your Application» and following the single inheritance example.
But QT gives 4 errors , which you will see a snapshot of below.
Now, what I did is I created a mainwindow in Qt designer, then I added a second form to the project , which will be the second dialog window when a button clicked. Because I created the form manually «mydialog.ui», I added class «mydialog.h and mydialog.cpp» and put the header of «ui-mydialog» in the source file «mydialog.cpp».
I’ not sure what am I missing ?
Below is the code :
— mydialog.h
#ifndef MYDIALOG_H
#define MYDIALOG_H
#include<QWidget>
class mydialog ;
namespace Ui {
class mydialog;
}
class mydialog : public QWidget
{
Q_OBJECT
public:
explicit mydialog(QWidget *parent = 0);
virtual ~mydialog();
private :
Ui::mydialog *ui;
};
#endif // MYDIALOG_H
— mainwindow.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QtCore/QtGlobal>
#include <QMainWindow>
QT_USE_NAMESPACE
QT_BEGIN_NAMESPACE
namespace Ui {
class MainWindow;
}
QT_END_NAMESPACE
class mydialog;
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
private slots:
void on_Start_clicked();
private:
Ui::MainWindow *ui;
mydialog *dialog1;
};
#endif // MAINWINDOW_H
— mydialog.cpp
#include"mydialog.h"
#include "ui_mydialog.h"
mydialog::mydialog(QWidget *parent) : QWidget(parent), ui(new Ui::mydialog)
{
ui->setupUi(this);
}
mydialog::~mydialog()
{
delete ui;
}
— mainwindow.cpp
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include"mydialog.h"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
dialog1 = new mydialog ;
}
MainWindow::~MainWindow()
{
delete ui;
delete dialog1;
}
void MainWindow::on_Start_clicked()
{
}
— main.cpp
#include"mainwindow.h"
#include<QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MainWindow w;
w.show();
return a.exec();
}
— The .pro file
#-------------------------------------------------
#
# Project created by QtCreator 2015-12-17T00:10:58
#
#-------------------------------------------------
QT += core gui
greaterThan(QT_MAJOR_VERSION, 4): QT += widgets
TARGET = TestTool
TEMPLATE = app
SOURCES += main.cpp
mainwindow.cpp
mydialog.cpp
HEADERS += mainwindow.h
mydialog.h
FORMS += mainwindow.ui
mydialog.ui
RESOURCES +=
misc.qrc
— Qt compilation output error
Compilation error
The generated file Ui_mydialog.h is :
#ifndef UI_MYDIALOG_H
#define UI_MYDIALOG_H
#include <QtCore/QVariant>
#include <QtWidgets/QAction>
#include <QtWidgets/QApplication>
#include <QtWidgets/QButtonGroup>
#include <QtWidgets/QDialog>
#include <QtWidgets/QDialogButtonBox>
#include <QtWidgets/QHeaderView>
QT_BEGIN_NAMESPACE
class Ui_Dialog
{
public:
QDialogButtonBox *buttonBox;
void setupUi(QDialog *Dialog)
{
if (Dialog->objectName().isEmpty())
Dialog->setObjectName(QStringLiteral("Dialog"));
Dialog->resize(400, 300);
buttonBox = new QDialogButtonBox(Dialog);
buttonBox->setObjectName(QStringLiteral("buttonBox"));
buttonBox->setGeometry(QRect(30, 240, 341, 32));
buttonBox->setOrientation(Qt::Horizontal);
buttonBox->setStandardButtons(QDialogButtonBox::Cancel|QDialogButtonBox::Ok);
retranslateUi(Dialog);
QObject::connect(buttonBox, SIGNAL(accepted()), Dialog, SLOT(accept()));
QObject::connect(buttonBox, SIGNAL(rejected()), Dialog, SLOT(reject()));
QMetaObject::connectSlotsByName(Dialog);
} // setupUi
void retranslateUi(QDialog *Dialog)
{
Dialog->setWindowTitle(QApplication::translate("Dialog", "Dialog", 0));
} // retranslateUi
};
namespace Ui {
class Dialog: public Ui_Dialog {};
} // namespace Ui
QT_END_NAMESPACE
#endif // UI_MYDIALOG_H
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 |
#include "dialogadddevice.h" #include "ui_dialogadddevice.h" DialogAddDevice::DialogAddDevice(int row, QWidget *parent) : QDialog(parent), ui(new Ui::DialogAddDevice) { ui->setupUi(this); /* Метода для инициализации модели, * из которой будут транслироваться данные * */ setupModel(); /* Если строка не задана, то есть равна -1, * тогда диалог работает по принципу создания новой записи. * А именно, в модель вставляется новая строка и работа ведётся с ней. * */ if(row == -1){ model->insertRow(model->rowCount(QModelIndex())); mapper->toLast(); /* В противном случае диалог настраивается на заданную запись * */ } else { mapper->setCurrentModelIndex(model->index(row,0)); } createUI(); } DialogAddDevice::~DialogAddDevice() { delete ui; } /* Метод настройки модели данных и mapper * */ void DialogAddDevice::setupModel() { /* Инициализируем модель и делаем выборку из неё * */ model = new QSqlTableModel(this); model->setTable(DEVICE); model->setEditStrategy(QSqlTableModel::OnManualSubmit); model->select(); /* Инициализируем mapper и привязываем * поля данных к объектам LineEdit * */ mapper = new QDataWidgetMapper(); mapper->setModel(model); mapper->addMapping(ui->HostnameLineEdit, 1); mapper->addMapping(ui->IPAddressLineEdit, 2); mapper->addMapping(ui->MACLineEdit, 3); /* Ручное подтверждение изменения данных * через mapper * */ mapper->setSubmitPolicy(QDataWidgetMapper::ManualSubmit); /* Подключаем коннекты от кнопок пролистывания * к прилистыванию модели данных в mapper * */ connect(ui->previousButton, SIGNAL(clicked()), mapper, SLOT(toPrevious())); connect(ui->nextButton, SIGNAL(clicked()), mapper, SLOT(toNext())); /* При изменении индекса в mapper изменяем состояние кнопок * */ connect(mapper, SIGNAL(currentIndexChanged(int)), this, SLOT(updateButtons(int))); } /* Метод для установки валидатора на поле ввода IP и MAC адресов * */ void DialogAddDevice::createUI() { QString ipRange = "(?:[0-1]?[0-9]?[0-9]|2[0-4][0-9]|25[0-5])"; QRegExp ipRegex ("^" + ipRange + "." + ipRange + "." + ipRange + "." + ipRange + "$"); QRegExpValidator *ipValidator = new QRegExpValidator(ipRegex, this); ui->IPAddressLineEdit->setValidator(ipValidator); QString macRange = "(?:[0-9A-Fa-f][0-9A-Fa-f])"; QRegExp macRegex ("^" + macRange + ":" + macRange + ":" + macRange + ":" + macRange + ":" + macRange + ":" + macRange + "$"); QRegExpValidator *macValidator = new QRegExpValidator(macRegex, this); ui->MACLineEdit->setValidator(macValidator); } void DialogAddDevice::on_buttonBox_accepted() { /* SQL-запрос для проверки существования записи * с такими же учетными данными. * Если запись не существует или находится лишь индекс * редактируемой в данный момент записи, * то диалог позволяет вставку записи в таблицу данных * */ QSqlQuery query; QString str = QString("SELECT EXISTS (SELECT " DEVICE_HOSTNAME " FROM " DEVICE " WHERE ( " DEVICE_HOSTNAME " = '%1' " " OR " DEVICE_IP " = '%2' )" " AND id NOT LIKE '%3' )") .arg(ui->HostnameLineEdit->text(), ui->IPAddressLineEdit->text(), model->data(model->index(mapper->currentIndex(),0), Qt::DisplayRole).toString()); query.prepare(str); query.exec(); query.next(); /* Если запись существует, то диалог вызывает * предупредительное сообщение * */ if(query.value(0) != 0){ QMessageBox::information(this, trUtf8("Ошибка хоста"), trUtf8("Хост с таким именем или IP-адресом уже существует")); /* В противном случае производится вставка новых данных в таблицу * и диалог завершается с передачей сигнала для обновления * таблицы в главном окне * */ } else { mapper->submit(); model->submitAll(); emit signalReady(); this->close(); } } void DialogAddDevice::accept() { } /* Метод изменения состояния активности кнопок пролистывания * */ void DialogAddDevice::updateButtons(int row) { /* В том случае, если мы достигаем одного из крайних (самый первый или * самый последний) из индексов в таблице данных, * то мы изменяем состояние соответствующей кнопки на * состояние неактивна * */ ui->previousButton->setEnabled(row > 0); ui->nextButton->setEnabled(row < model->rowCount() - 1); } |
|
Автор | Тема: invalid use of incomplete type (решено) (Прочитано 24681 раз) |
|
||||||
|
||||||
|
||||||
|
||||||
|
||||||
|
||||||
|
||||||
|
||||||
|
||||||
|
||||||
|
||||||
- Forum
- Beginners
- Invalid use of incomplete type
Invalid use of incomplete type
I get these errors i dont have any idea how to solve.
I have searched Goolge and StackOverflow and found stuff related to this but i couldn’t solve this.
Any help is much appreciated.
error: invalid use of incomplete type ‘class Ui::AddDialog’
error: forward declaration of ‘class Ui::AddDialog’
addDialog.h
|
|
AddDialog.cpp
|
|
gpa.h
|
|
gpa.cpp
|
|
How does «ui_addDialog.h» look like?
its a form. Im programming with Qt
Why are the errors only for AddDialog
when AddDialog
has the same structure as Gpa
Last edited on
ui_AddDialog is generated by Qt Creator.
Make sure you made AddDialog with Qt Creator.
Also try doing a clean build.
I have done the clean build but no change.
Yes i made AddDialog with QtCreator.
I then added the header and .cpp files manually instead of them being generated automatically as it was with Gpa.
But I think Gpa files were automatically generated becauase Gpa is my main project.
I fixed the issue.
I selected Designer form file instead of Designer form class when creating the AddDialog form.
Topic archived. No new replies allowed.
Я пытался решить эту проблему, но должно быть какое-то недопонимание в том, как я понимаю предварительную декларацию.
Я получаю следующую ошибку:
src/algorithm.cpp: In constructor ‘Algorithm::Algorithm(MainWindow*)’: src/algorithm.cpp:22:20: error: invalid use of incomplete type ‘struct Ui::MainWindow’ src/mainwindow.h:23:10: error: forward declaration of ‘struct Ui::MainWindow’
У меня есть эти файлы (я пропустил некоторые строки и файлы и вставил только соответствующий код):
algorithm.cpp
#include "algorithm.h"#include "mainwindow.h" Algorithm::Algorithm(MainWindow *mainWindow) { this->mainWindow = mainWindow; QAction *action = new QAction(this); action->setObjectName(QStringLiteral("action")); action->setText(this->getName()); mainWindow->m_ui->menuAlgorithms->addAction(action); mainWindow->connect(action, SIGNAL(triggered()), this, SLOT(this->start())); }
algorithm.h
#ifndef ALGORITHM_H #define ALGORITHM_H #include <QObject> #include "graphwidget.h"#include "edge.h"#include "vertex.h" class MainWindow; class Algorithm : public QObject { public: MainWindow *mainWindow; Algorithm(MainWindow *mainWindow); void start(); virtual void solve(); virtual QString getDescription(); virtual QString getName(); };
mainwindow.cpp
#include "mainwindow.h"#include "algorithm.h"#include "../ui/ui_mainwindow.h"#include "vertex.h"#include "edge.h"#include "warning.h" mode_type mode; MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), m_ui(new Ui::MainWindow) { gundirected = NULL; gdirected = NULL; m_ui->setupUi(this); ...
mainwindow.h
#ifndef MAINWINDOW_H #define MAINWINDOW_H #include <QMainWindow> #include <QSystemTrayIcon> #include <QSignalMapper> #include <QUndoView> #include <QGraphicsView> #include <QGraphicsScene> #include <QKeyEvent> #include <QGraphicsSceneMouseEvent> #include <QLabel> #include <QVBoxLayout> #include <QPushButton> #include "graphwidget.h" enum mode_type {NORMAL, VERTEX, EDGE}; // vyctovy typ pro urceni editoacniho modu extern mode_type mode; namespace Ui { class MainWindow; } class MainWindow : public QMainWindow { Q_OBJECT public: explicit MainWindow(QWidget *parent = 0); ~MainWindow(); Ui::MainWindow *m_ui; ...
4
Решение
Проблема в вашем коде в том, что вы пытаетесь использовать m_ui
член MainWindow
класс в вашем Algorithm
класс и тип m_ui
является Ui::MainWindow
, но твой Algorithm
класс не знает о таком типе. Вы можете решить эту проблему, включив ui_mainwindow.h
в вашем algorithm.cpp
,
Но это все еще плохой дизайн. m_ui
должен быть частным членом MainWindow
учебный класс. Вы не должны получать к нему доступ из других классов. Вместо этого создайте функции в вашем MainWindow
класс, который позволит вам делать то, что вы хотите.
Например, создайте публичную функцию следующим образом:
void MainWindow::addCustomAction(QAction *action) { m_ui->menuAlgorithms->addAction(action); }
Затем вызовите эту функцию из вашего Algorithm
учебный класс:
Algorithm::Algorithm(MainWindow *mainWindow) { this->mainWindow = mainWindow; QAction *action = new QAction(this); action->setObjectName(QStringLiteral("action")); action->setText(this->getName()); mainWindow->addCustomAction(action); connect(action, SIGNAL(triggered()), this, SLOT(start())); }
4
Другие решения
Ваша предварительная декларация появляется в пространстве имен UI
, но объявление вашего класса появляется за пределами этого пространства имен. Вы должны изменить это на
namespace UI { class MainWindow : public QMainWindow { Q_OBJECT // ... }; }
Также кажется, что вам вообще не нужно предоставлять предварительную декларацию, но измените предварительную декларацию в Algorithm.h
снова появиться MainWindow
в правильном пространстве имен:
namespace UI { class MainWindow; }
4
- 1. Project structure
- 2. Exterior windows
- 3. main.cpp
- 4. mainwindow.h
- 5. mainwindow.cpp
- 6. anotherwindow.h
- 7. anotherwindow.cpp
- 8. Result. Switch between windows
- 9. Video
Recently, a subscriber asked me for help on the issue, the answer to which he was looking for on the Internet. I do not have much free time, but it seems the stars have converged so that time was the question from the category of those that have already had some experience.
So, the crux of the matter was that, in order to arrange to switch between the main window and the secondary. Yes thereby to shut the open window and the second window opened instead. That is to say that at the touch of a button in the main window to open another window and close the main window at the same time. In this second box contains a button, clicking on which opens the main window and the second window is closed, respectively.
Project structure
The project structure is characterized by the presence of an additional class of default, which would be responsible for the secondary window.
anotherwindow.h
— header secondary window;
anotherwindow.cpp
— source file of secondary window.
Exterior windows
I created here the windows with the help of the designer interface.
Switch between windows. Main window
Switch between windows. secondary window
main.cpp
This file, which starts with an application created by default. Nothing here is not changing.
#include "mainwindow.h" #include <QApplication> int main(int argc, char *argv[]) { QApplication a(argc, argv); MainWindow w; w.show(); return a.exec(); }The header of the main window of the application you must include the header file window secondary application.
#ifndef MAINWINDOW_H #define MAINWINDOW_H #include <QMainWindow> #include <anotherwindow.h> namespace Ui { class MainWindow; } class MainWindow : public QMainWindow { Q_OBJECT public: explicit MainWindow(QWidget *parent = 0); ~MainWindow(); private slots: void on_pushButton_clicked(); void on_pushButton_2_clicked(); private: Ui::MainWindow *ui; // second and third windows AnotherWindow *sWindow; AnotherWindow *thirdWindow; }; #endif // MAINWINDOW_Hmainwindow.cpp
Initialize both secondary windows are in the main window and use the signals and slots system, these windows are displayed on the signals from the main window buttons. At the same time the main window will be closed.
#include "mainwindow.h" #include "ui_mainwindow.h" MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); // Initialize the second window sWindow = new AnotherWindow(); // connected to the slot start the main window on the button in the second window connect(sWindow, &AnotherWindow::firstWindow, this, &MainWindow::show); // Initialize the third window thirdWindow = new AnotherWindow(); // connected to the slot start the main window on the button in the third window connect(thirdWindow, &AnotherWindow::firstWindow, this, &MainWindow::show); } MainWindow::~MainWindow() { delete ui; } void MainWindow::on_pushButton_clicked() { sWindow->show(); // Show a second window this->close(); // Close the main window } void MainWindow::on_pushButton_2_clicked() { thirdWindow->show(); // Show a third window this->close(); // Close the main window }anotherwindow.h
#ifndef ANOTHERWINDOW_H #define ANOTHERWINDOW_H #include <QWidget> namespace Ui { class AnotherWindow; } class AnotherWindow : public QWidget { Q_OBJECT public: explicit AnotherWindow(QWidget *parent = 0); ~AnotherWindow(); signals: void firstWindow(); private slots: void on_pushButton_clicked(); private: Ui::AnotherWindow *ui; }; #endif // ANOTHERWINDOW_Hanotherwindow.cpp
And likewise do the button handler in a secondary window. The difference is that the main window already exists, so we need to send a signal to the side of the main window, so that it opened.
#include "anotherwindow.h" #include "ui_anotherwindow.h" AnotherWindow::AnotherWindow(QWidget *parent) : QWidget(parent), ui(new Ui::AnotherWindow) { ui->setupUi(this); } AnotherWindow::~AnotherWindow() { delete ui; } void AnotherWindow::on_pushButton_clicked() { this->close(); emit firstWindow(); }Result. Switch between windows
As a result of such manipulations you will be able to switch between application windows, and at the same time you will be always open only one application window.
Video
|
Автор | Тема: invalid use of incomplete type (решено) (Прочитано 25225 раз) |
|
||||||
|
||||||
|
||||||
|
||||||
|
||||||
|
||||||
|
||||||
|
||||||
|
||||||
|
||||||
|
||||||