0

我大部分都知道如何在 C++ 中格式化函数,除了我以前从未见过的这种情况。

我目前有这个:

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");
}

当然,它可以编译一切。它做的正是它应该做的——扫描 SQLite 数据库的内容并通过 QTableWidget 输出它,按员工姓氏排序,只要你点击“viewEmployees”按钮。没有问题。

但是我想把它转换成一个函数......比如说,DatabaseControl.refreshTableView()。

我将其复制/粘贴到 DatabaseControl 类中,并且我知道将所有 DatabaseControl 引用更改为“this”,但是我不知道如何处理“ui->”位,因为 ui-> 在我的 mainwindow.cpp:

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

结果,我无法更改 MainWindow 中的任何 UI 元素(据我所知)。我想要做的是能够通过 DatabaseControl 类编辑这些 UI 元素。更具体地说,我想通过 DatabaseControl 编辑该 QTableWidget 的内容。

4

2 回答 2

2

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

于 2014-01-02T17:41:10.760 回答
2

好吧,要直接回答您的问题,一种方法是将 ui->table 对象传递给您的 refreshTableView() 方法。或者以某种方式让您的 DatabaseControl 对象访问 MainWindow(例如,像 redshark 建议的那样)。

但是,我怀疑这可能不是构建代码的好方法。许多应用程序试图将数据库与数据库中的信息表示分开。一个原因是,如果您想更改数据的表示方式,它应该独立于从数据库中检索信息的方式。同样,如果您必须切换到具有不同 API 的新数据库等,您也不想破坏您的演示代码。

关于这一点还有很多可以说的,但希望这足以让你沿着已经被很好地穿越和证明的脉络思考。

于 2014-01-02T17:44:50.473 回答