我有一些代码可以检测QListWidget
int currentTab=ui->tabWidget->currentIndex();
if (currentTab==0)
{
// Code here
}
else if (currentTab==1)
{
// Code here
}
else if (currentTab==2)
{
// code here
}
else if (currentTab==3)
{
// code here
}
如何使用枚举代替if(currentTab==0)
或if(currentTab==1)
或if(currentTab==2)
或if(currentTab==3)
答案 0 :(得分:6)
我将按以下方式处理相同的事情(使用枚举类型):
enum Tabs {
Tab1,
Tab2,
Tab3
};
void foo()
{
int currentTab = ui->tabWidget->currentIndex();
switch (currentTab) {
case Tab1:
// Handle the case
break;
case Tab2:
// Handle the case
break;
case Tab3:
// Handle the case
break;
default:
// Handle all the rest cases.
break;
}
}
答案 1 :(得分:0)
使用下面给出的枚举的示例 如果你想在两个枚举中使用相同的枚举元素,那么你可以使用enum classes (strongly typed enumerations) C++11。
#include <iostream>
#include <cstdint>
using namespace std;
//enumeration with type and size
enum class employee_tab : std::int8_t {
first=0 /*default*/, second, third, last /*last tab*/
};
enum class employee_test : std::int16_t {
first=10 /*start value*/, second, third, last /*last tab*/
};
enum class employee_name : char {
first='F', middle='M', last='L'
};
int main(int argc, char** argv) {
//int currentTab=ui->tabWidget->currentIndex();
employee_tab currentTab = (employee_tab)1;
switch (currentTab) {
case employee_tab::first: //element with same name
cout << "First tab Selected" << endl;
break;
case employee_tab::second:
cout << "Second tab Selected" << endl;
break;
case employee_tab::third:
cout << "Third tab Selected" << endl;
break;
case employee_tab::last: //element with same name
cout << "Fourth tab Selected" << endl;
break;
}
employee_name currentName = (employee_name)'F';
switch (currentName) {
case employee_name::first: //element with same name
cout << "First Name Selected" << endl;
break;
case employee_name::middle:
cout << "Middle Name Selected" << endl;
break;
case employee_name::last: //element with same name
cout << "Last Name Selected" << endl;
break;
}
return 0;
}
<强>输出:强>
第二个选项卡选择
选择名字