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 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 |
#include "manager.h" #include "ui_Manager.h" using std::unique_ptr; Manager::Manager(QWidget *parent) : QWidget(parent), ui(new Ui::Manager) { ui->setupUi(this); ui->stackedWidget->setCurrentIndex(0); // ui->tableWidget_Employee->setSelectionMode(QAbstractItemView::NoSelection); // ui->tableWidget_Employee->setFocusPolicy(Qt::NoFocus); //ui->tableWidget_Employee->setSelectionBehavior(QAbstractItemView::AdjustToContentsOnFirstShow); loadTableEmployee(); loadAllTables(); loadComboPost(); connect(ui->pushButton_addEmployee, &QPushButton::clicked, this, &Manager::on_pushButton_AddEmployee_clicked); connect(ui->pushButton_backToTables, &QPushButton::clicked, this, &Manager::on_pushButton_backToTables_clicked); connect(ui->tableWidget_Employee, &QTableWidget::cellClicked, this, &Manager::on_tableWidget_itemClicked); connect(ui->pushButton_toEditEmployee, &QPushButton::clicked, this, &Manager::on_pushButton_toEditEmployee_clicked); } Manager::~Manager() { delete ui; } int Manager::getCurrentPost() { int id_post = Database::id_post(ui->comboBox_Post->currentText()); if(id_post == -1) { qDebug() << "nINSERT INTO EmployeePost(title = " <<ui->comboBox_Post->currentText() << ")"; id_post = Database::addPost(ui->comboBox_Post->currentText()); if(id_post == -1) { qDebug() << "Errorn"; } else { qDebug() << "Succes (id = "<< id_post << ")n"; ui->comboBox_Post->addItem(ui->comboBox_Post->currentText()); } } return id_post; } void Manager::loadComboPost() { ui->comboBox_Post->addItems(Database::listPost()); } void Manager::loadTableEmployee() { ui->tableWidget_Employee->setRowCount(Database::countEmployee()); // указываем количество строк unique_ptr<QSqlQuery> query(new QSqlQuery()); query->exec("SELECT p.surname, p.name, p.second_name, x.title, e.phone, e.salary, e.recruitment " "FROM Employee AS e " "JOIN Passport AS p " "ON p.itn = e.id_passport " "JOIN EmployeePost AS x " "ON x.id = e.id_post " ); QString fullname; for(int row = 0; row < ui->tableWidget_Employee->rowCount(); ++row) { query->next(); fullname = QString(query->value(0).toString() + " " + query->value(1).toString().at(0) + ". " + query->value(2).toString().at(0) + "."); ui->tableWidget_Employee->setItem(row, 0, new QTableWidgetItem(fullname)); for(int column = 1; column < ui->tableWidget_Employee->columnCount(); ++column) ui->tableWidget_Employee->setItem(row, column, new QTableWidgetItem(query->value(column+2).toString())); } } void Manager::loadTable(const int&& tableTitle, QTableView* tableView) { model = new QSqlTableModel(); switch(tableTitle) { case Table::Schedule: { model->setTable("Schedule"); model->setHeaderData(0,Qt::Horizontal, "Начало"); model->setHeaderData(1,Qt::Horizontal, "Контент"); model->setHeaderData(2,Qt::Horizontal, "Команда"); } break; case Table::Employee: { model->setTable("Employee"); model->setHeaderData(0,Qt::Horizontal, "Ф.И.О."); model->setHeaderData(1,Qt::Horizontal, "Телефон"); model->setHeaderData(2,Qt::Horizontal, "Должность"); model->setHeaderData(3,Qt::Horizontal, "Зарплата"); model->setHeaderData(4,Qt::Horizontal, "Работает с"); model->setHeaderData(5,Qt::Horizontal, "Отпускные"); model->setHeaderData(6,Qt::Horizontal, "Больничные"); }break; case Table::TeamList: { model->setTable("TeamList"); model->setHeaderData(0,Qt::Horizontal, "Команда"); model->setHeaderData(1,Qt::Horizontal, "Работник"); }break; }; model->select(); tableView->setModel(model); tableView->resizeColumnsToContents(); tableView->show(); } void Manager::loadAllTables() { loadTable(Table::Schedule, ui->tableView_Schedule); loadTable(Table::TeamList, ui->tableView_TeamList); } void Manager::on_pushButton_toEditEmployee_clicked() { } void Manager::on_tableWidget_itemClicked(int row, int col) { //ui->tableWidget_Employee->setRangeSelected(QTableWidgetSelectionRange(row, 0, row, 4), true); } void Manager::on_listWidget_itemSelectionChanged() { ui->stackedWidget_Tables->setCurrentIndex(ui->listWidget->currentRow()); } void Manager::on_pushButton_toAddEmployee_clicked() { ui->stackedWidget->setCurrentIndex(Form::AddEmployee); } void Manager::on_pushButton_backToTables_clicked() { ui->stackedWidget->setCurrentIndex(Form::Tables); } void Manager::on_pushButton_AddEmployee_clicked() { Passport passport(ui->lineEdit_Surname->text(), ui->lineEdit_Name->text(), ui->lineEdit_SecondName->text(), ui->dateEdit_Birthday->date(), ui->lineEdit_itn->text().toInt()); Employee employee(passport, ui->lineEdit_Phone->text(), getCurrentPost(), ui->lineEdit_Salary->text().toInt(), ui->dateEdit_Recruitment->date()); if(!employee.isValid()) { QMessageBox::information(0,0,"Ошибка при добавлении"); return; } if(Database::addEmployee(employee)) QMessageBox::information(0,0,"Сотрудник добавлен"); else QMessageBox::warning(0,0,"Ошибка! Сотрудник не добавлен"); } |
- Печать
Страницы: [1] Вниз
Тема: Проблема в Qt. ошибка поиска/добавления слота в редакторе форм (Прочитано 1846 раз)
0 Пользователей и 1 Гость просматривают эту тему.

agarkov
Перешел в Ubuntu недавно и искал себе аналог visual studio в котором начал экспериментировать с кодом на С++
нашел qt creator.
внешне он мне очень даже понравился но не сразу сообразил что к чему, потому что до этого «работал» только пару дней в майкросовтовском вижуал экспресс и не знал много тонкостей.( и продолжаю не знать)
вообщем начал писать «Привет, мир!» по какому то англоязычному мануалу и столкнулся в проблемой следующей.
Не удалось найти в /home/maxim/prog/111pr/class.cpp определение класса ‘Ui::class’.
возникает она как ошибка поиска/добавления слота на кнопку в редакторе форм.
скорее всего, это что то не страшное, но в любом случае я не пойму.

RazrFalcon

agarkov
кода еще нет, по мануалу первое нужно создать кнопку со слотом.
http://linux301.wordpress.com/2009/06/15/hello-world-with-qt/
Пользователь решил продолжить мысль 02 Ноября 2011, 08:53:14:
вот то что он автоматом создал
TARGET = 111pr
TEMPLATE = app
SOURCES += main.cpp
class.cpp
HEADERS += class.h
FORMS += class.ui
Пользователь решил продолжить мысль 02 Ноября 2011, 14:21:31:
проблема решена пересозданием проекта.
скорее всего я просто зря переименовал имя класса когда его создавал.
« Последнее редактирование: 02 Ноября 2011, 14:21:31 от agarkov »
- Печать
Страницы: [1] Вверх
Problem is that I keep getting the ‘No Such Slot’ runtime error in Qt Creator every time I launch a ‘settings’ window from my main window. I’ve found Qt to be quite counter-intuitive so far and this slots ‘n signals concept seems a bit of a stretch from simply passing vars or function calls. Basically, I have menu with a settings option, that when clicked, opens a settings window which needs to grab a double from the user and update a var in the main window.
SettingsWindow.h
class SettingsWindow : public QWidget
{
Q_OBJECT
public:
SettingsWindow(QWidget *parent = 0);
signals:
void ValChanged(double newVal);
public slots:
void Accept();
private:
QLineEdit *le1;
};
The settings window has an accept button which calls Accept() which emits the ValChanged signal with newVal set as the user input in le1 as a double.
SettingsWindow.cpp
void SettingsWindow::Accept(){
emit ValChanged(le1->text().toDouble());
this->close();
}
This settings window is called by the application’s main window: MainWindow
MainWindow.cpp
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
MainWindow(QWidget *parent = 0);
public slots:
void SetVal(double x);
private slots:
void NewWindow();
private:
double theVal;
};
This main window has a menu which one would select settings from. This creates a new window with a field for one to enter a number.
MainWindow.cpp
void MainWindow::NewWindow()
{
SettingsWindow *MySettings=new SettingsWindow(this);
QObject::connect(MySettings, SIGNAL(ValChanged(double)), this, SLOT(SetVal(double)));
MySettings->show();
MySettings->raise();
}
void MainWindow::SetVal(double x){
theVal = x;
}
My hope is that when the settings window is opened, the user can enter a val into the field which then emits the ValChanged Signal which sets theVal to the value specified by the user. Most of the time I saw an issue with people not including Q_OBJECT macro, but I’ve included it both times. Any suggestions on why this doesn’t work?
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.
-
As the title saiz .
This has been a problem in past (2012) and the attached link does not really provide solution.This is a first attempt to work with signal / slot AFTER I reinstalled my Qt Creator .
Since I am adding a slot in «device.cpp» I do not get why the error is reporting missing header from so any places.I assume it is missing from some common place , but I do not get from where.
Could use some help.
Thanks.https://forum.qt.io/topic/20570/qtcreator-ui-designer-suddenly-fails-to-add-find-slots
-
Hi,
Did you nuke the build folder ?
Delete the .pro.user file ? -
Did you nuke the build folder ?
Not sure what you are asking. I can fully rebuild / compile and run everything, including all «events» in «device» object.
I have several dialogs under tab and they all complain about same things.
It has to be something common.Delete the .pro.user file ?
No.I have build a simple main window and added button and list and it all works as expected.
I really cannot figure out what header is missing and why only when I try to add «connect» in Qt Designer.
I will add another test tab dialog and see if I can identify the missing #inlcude header.l
-
@AnneRanch said in Error finding /adding a slot — in Qr Designer:
Not sure what you are asking
Delete the build folder. If you don’t know where it is you can check in QtCreator: Projects/General/Build Directory
-
Here is something which may lead to solution.
I have never had a need to look into «projects» form.
I copy — using «files» to keep track of my development — poor man version control.Noticed that the «tab» and «build directory» do not match.
Not sure what to do about error which is going to be «overwritten» ??
Also — I do not know wnat «shadow build» does.
I went to my early version of the project and experienced same issue — missing still unknown header.
Thanks for all your help, appreciate that very much
-
@AnneRanch said in Error finding /adding a slot — in Qr Designer:
Not sure what to do about error which is going to be «overwritten» ??
Nothing. Next time you build the content of that folder will be overwritten. This is just a warning telling you that there is already something in that folder.
«Also — I do not know wnat «shadow build» does» — is explained in the documentation: https://doc.qt.io/qtcreator/creator-glossary.html
-
BUMP
I am back with same issue — this time only one error.
To get rid of the original post error I have totally abandoned my original project and started over.
This time I included only one class from the original code (btscanner) and as expected got the error back.
( I’ll admit I am still not sure about anything «ui» in QtCreator )I really do not understand how to find / identify the missing reference to «ui::DeviceDiscovery» so I can add appropriate header into my code.
Here is a refresher , just a text of the error.
The class containing «Ui::DeviceDiscovery» could not be found in
/media/f/QT/Qt/QT/qtconnectivity/examples/bluetooth/CAT_BT_18112020/device.h.
Please verify the #include-directives. -
Hi,
The complete example (5.15 version) can be found here.
Check the .pro file to see if yours is missing anything like the FORMS directive.
-
@SGaist
My FORMS in .pro seem to work , no problem.I basically have two dialogs — MainWindow and Bluetooth scanner.
I can «go to slot …» and add a slot in MainWIndow and do «connect» , but I get this error doing same in Bluetooth scanner.
I did check both headers and see no obvious difference.
I am doing both «slot» assignment in QtDesigner , but since it fails for Bluetooth dialog I cannot continue in QtDesigner and do the connect there.I have two options
do the Bluetooth «connect» manually, which I am still not comfortable with, or
just rebuild the «device class » — an original scanner dialog — and hope it will work.Many thanks for your help.
-
Which slot are you trying to connect ?
Advice: get yourself comfortable with doing things in code code. That’s a very good long term investment.
QObject::connect(button,SIGNAL(pressed()),newlabel,SLOT(setText(«GAMA
GAMA»)));
If you want to create a handler for QPushButton::pressed()
event, i.e. after a button was pressed a label text should be changed, you can
// Create a halper that transforms pressed() signal to textChanged(text) signal
// that will be connected to setText() slot, i.e.
// button.pressed() -> proxy.onButtonPressed() -> label.setText(text)
//
class SignalHelper : public QObject {
Q_OBJECT
QString text_;
public:
SignalHelper(const QString & text)
: text_(text) {
}
signals:
void textChanged(const QString & text);
public slots:
void onButtonPressed() {
emit textChanged(text_);
}
};
int main(int argc, char *argv[]) {
...
// Connect
//
QScopedPointer<SignalHelper> pHelper(new SignalHelper(QStringLiteral("GAMA GAMA")));
QObject::connect(button, &QPushButton::pressed,
pHelper.data(), &SignalHelper::onButtonPressed);
QObject::connect(pHelper.data(), &SignalHelper::textChanged,
newlabel, &QLabel::setText);
...
// Also you can add another button that sets another text
//
QPushButton *button2 = new QPushButton("PRESS TO DECREASE");
QScopedPointer<SignalHelper> pHelper2(new SignalHelper(QStringLiteral("Decreased")));
QObject::connect(button2, &QPushButton::pressed,
pHelper2.data(), &SignalHelper::onButtonPressed);
QObject::connect(pHelper2.data(), &SignalHelper::textChanged,
newlabel, &QLabel::setText);
...
}
Another way is to use a signal handler + std::bind() — in this case you do not need to define any specific signal in a helper class, so you can attach any handler to pressed() signal.
typedef std::function<void()> Handler_t;
class BtnPressHandler : public QObject {
Q_OBJECT
Handler_t handler_;
public:
BtnPressHandler(Handler_t handler)
: handler_(handler) {
}
public slots:
void onButtonPressed() {
handler_();
}
};
// Connect
//
QScopedPointer<BtnPressHandler> pHandler(new BtnPressHandler(
std::bind(&QLabel::setText, newlabel, QStringLiteral("GAMA GAMA"))));
QObject::connect(button, &QPushButton::pressed,
pHandler.data(), &BtnPressHandler::onButtonPressed);
// Create a button that closes an application
//
QPushButton * exitBtn = new QPushButton("PRESS TO EXIT");
QScopedPointer<BtnPressHandler> pHandler2(new BtnPressHandler(
std::bind(&QApplication::quit, &a)));
QObject::connect(exitBtn, &QPushButton::pressed,
pHandler2.data(), &BtnPressHandler::onButtonPressed);