如何在qt creator上的tab上加载数据

时间:2014-12-12 15:09:25

标签: c++ qt qt4 qt-creator

我在Qt创建器中使用QtabWidget并创建了三个选项卡(tab-1,tab-2,tab-3)。每个选项卡有大约30个字段。现在我最初运行应用程序时用户将在选项卡上1.目前,所有三个标签中显示的所有数据都被拉出。有什么方法当用户点击Tab-2时,才会加载与tab-2相对应的数据,而tab-3则相同。我正在寻找像“onTabClick”这样的功能。我检查了与标签小部件相关的插槽,但找不到任何插槽。

我在Qt中的表单代码:

Mainwindow.cpp

#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <ctime>
#include <iostream>
#include <QPixmap>
#include <stdio.h>
#include <QProcess>
#include <QString>
#include <QPainter>
#include <QPen>
#include <QBrush>
#include <QLabel>
#include <QTimer>
#include <ctime>


using namespace std;

void MainWindow::onTabChanged(int tabIndex) {

    cout<<"the tab index is:"<<tabIndex<<endl;
    if (tabIndex == 0) {
        // Create the first tab elements

        cout<<"tab 0"<<endl;
    } else if (tabIndex == 1) {
        // ...

        cout<<"tab 1"<<endl;

    }
}

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{


    time_t now = time(0);
    char* dt = ctime(&now);

    ui->setupUi(this);
    this->setWindowTitle("First Qt Project");
    connect(ui->tabWidget, SIGNAL(currentChanged(int)), this, SLOT(onTabChanged(int)));    

}



MainWindow::~MainWindow()
{
    delete ui;
}

MainWindow.h

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>

namespace Ui {
class MainWindow;
}

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    explicit MainWindow(QWidget *parent = 0);
    ~MainWindow();

private slots:


    void onTabChanged(int tabIndex);



private:
    Ui::MainWindow *ui;
};

#endif // MAINWINDOW_H

2 个答案:

答案 0 :(得分:0)

您可以使用QTabWidget::currentChanged(int)信号来处理标签更改事件。即:

将信号连接到相应的插槽:

connect(tabWidget, SIGNAL(currentChanged(int)), this, SLOT(onTabChanged(int)));

并在插槽中:

void MyClass::onTabChanged(int tabIndex) {
    if (tabIndex == 0) {
        // Create the first tab elements
    } else if (tabIndex == 1) {
        // ...
    }
}

答案 1 :(得分:0)

我找到了解决这个问题的方法:

默认情况下,创建的任何插槽都位于&#34;私有插槽&#34;在MainWindow.h文件中,如下所示:

private slots:
//default slots created from the ui(when the user right clicks on a button and then connects to a     slot)

所以在我的情况下,因为函数onTabChanges是一个用户定义的函数,我手动为这个函数创建了一个SLOT,这应该在公共插槽部分。因此,以这种方式包含它解决了这个问题。

public slots:

void onTabChanged(int tabIndex);