c++ - 使用 Qt 在 C++ 中编写函数

标签 c++ qt qmainwindow qsqlquery

除了我以前从未见过的这种情况外,我大部分时间都知道如何在 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 的内容。

最佳答案

您可以为 MainWindow 类编写公共(public)函数,这些函数可以从您的 DataControl 类访问,从而修改 ui 元素。
编辑:或者您可以在 MainWindow 中编写一个函数,它会返回一个指向 ui 变量的指针并从那里修改用户界面。
像这样:

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

现在您可以从 DataControler 类调用 MainWindow::getUI() 函数并操作您的 Ui

关于c++ - 使用 Qt 在 C++ 中编写函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20888275/

相关文章:

c++ - 将 boost shared_ptr 转换为 void*,反之亦然

c++ - 如何在 c++17 中传递 Callable 对象以与 std::invoke 一起使用

Qt:HBoxLayout - 停止 MainWindow 调整内容大小

c++ - Qt简单记事本,QmainWindow状态栏打印行号

c++ - 接受对话框时如何调用带有参数的插槽?

c++ - Boost spirit 将整个比赛作为一个字符串

c++ - Qt Bluetooth Low Energy - 使用非标准 GATT 的问题

c++ - 没有可调用的匹配函数

c++ - Memset 内存溢出

c++ - 如何使用 focusInEvent 和 focusOutEvent