Lighthat Lighthat - 1 month ago 21
C++ Question

Writing a function in C++ with Qt

I know how to format functions in C++ for the most part, except for this scenario which I've never seen before.

I currently have this:

void MainWindow::on_viewEmployees_clicked()
{
QDebug debugTxt(QtDebugMsg);
DatabaseControl myDBControl; //this is the header file that I want to use
QSqlQuery qry;
bool ok;
int rows = myDBControl.getNumEmployees();
ui->table->setRowCount(rows);
int count = 0;
int currentCol = 0;

while(count < rows){
qry.prepare("SELECT * FROM employees ORDER BY lastname LIMIT :f1, :f2");
qry.bindValue(":f1", count);
qry.bindValue(":f2", count+1);
qry.exec();
qry.next();
currentCol = 0;
while(currentCol < ui->table->columnCount()){
QTableWidgetItem *setdes = new QTableWidgetItem;
setdes->setText(qry.value(currentCol).toString());
ui->table->setItem(count, currentCol-1, setdes);
currentCol++;
}
count++;

}
debugTxt << "Table successfully populated";
ui->lblResult->setText("[+] Table successfully populated");
}


which compiles okay and everything, of course. It does exactly what it's supposed to do - scan the contents of a SQLite database and output it through a QTableWidget, ordered by employee last name, whenever you click the "viewEmployees" button. No issues.

However I want to convert this into a function...say, DatabaseControl.refreshTableView().

I copy/pasted this into the DatabaseControl class, and I know to change all of the DatabaseControl references to 'this,' however I don't know what to do with the 'ui->' bits, as ui-> is something in my mainwindow.cpp:

MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
}


As a result, I can't alter any of the UI elements in MainWindow (as far as I know). What I want to do is be able to edit those UI elements through the DatabaseControl class. More specifically, I want to edit the contents of that QTableWidget through DatabaseControl.

Answer

You could write public functions for the MainWindow class that can be accessed from your DataControl class that would modify the ui elements.
Edit: Or you could write a funciton in the MainWindow that would return a pointer to the ui variable and modify the the user interface from there.
like this:

MainWindow::getUI(){ return ui} // if your ui variable is already stored as a pointer

and now you can call the MainWindow::getUI() function from the DataControler class and manipulate your Ui