我是 C++ 的新手,我刚开始将一个最初在 python/Qt 中的程序移植到 C++/Qt 为了利用我可以嵌入到我的程序中的更好的终端小部件。现在我有点卡住了,我正在尝试设置如果从下拉框中选择不同的项目,则选项卡小部件的 currentIndex()
会相应更改。
到目前为止,这是我的代码:
//main.cpp
#include <QApplication>
#include "mainwindow.h"
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MainWindow w;
w.show();
return a.exec();
}
这里是mainwindow.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <QTimer>
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
QTimer *timer;
void startMyTimer()
{
timer = new QTimer();
timer->setInterval(1);
timer->start();
QObject::connect(timer,SIGNAL(timeout()),this,SLOT(changeIndex()));
}
private:
Ui::MainWindow *ui;
void changeIndex();
};
#endif // MAINWINDOW_H
最后是 mainwindow.cpp
#include "mainwindow.h"
#include "ui_mainwindow.h"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
changeIndex();
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::changeIndex()
{
if (ui->comboBox->currentText() == "add-apt-repository")
{
ui->stackedWidget->setCurrentIndex(0);
ui->checkBox->setCheckState(Qt::Checked);
}
if (ui->comboBox->currentText() == "apt-get")
{
ui->stackedWidget->setCurrentIndex(1);
ui->checkBox->setCheckState(Qt::Checked);
}
if (ui->comboBox->currentText() == "aptitude")
{
ui->stackedWidget->setCurrentIndex(2);
ui->checkBox->setCheckState(Qt::Checked);
}
if (ui->comboBox->currentText() == "bzr")
{
ui->stackedWidget->setCurrentIndex(3);
ui->checkBox->setCheckState(Qt::Unchecked);
}
if (ui->comboBox->currentText() == "cd")
{
ui->stackedWidget->setCurrentIndex(4);
ui->checkBox->setCheckState(Qt::Unchecked);
}
if (ui->comboBox->currentText() == "chmod")
{
ui->stackedWidget->setCurrentIndex(5);
ui->checkBox->setCheckState(Qt::Checked);
}
}
我看过很多 QTimer 示例,但我不知所措。
我也尝试过 if (ui->comboBox->changeEvent())
但我也可能用错了。
最佳答案
首先,您可能必须将 changeIndex()
标记为插槽,如下所示:
class MainWindow : public QMainWindow
{
Q_OBJECT
// ...
private slots:
void changeIndex();
private:
Ui::MainWindow *ui;
}
这还需要您调用 Qt 元对象编译器。如果您使用 qmake,那已经为您完成了。否则,这取决于您的构建系统。
其次,使用计时器有什么特别的原因吗?您还可以连接到组合框的 currentIndexChanged
信号之一。
关于c++ - 从下拉框中选择不同的项目时更改选项卡小部件的 currentIndex(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14589066/