话不多说,先上图吧:
基本上实现了这个功能,这个是书籍:
Qt5C++GUIProgrammingCookbook 书中的第二个小例子,我只是添加了一个点击按钮可以切换tabWidget的功能。
估计很多人会说,这不是一个非常简单的例子吗,没啥特别的,界面也不好看,反正你一定会吐槽的。
其实你多了解看看一下很多程序都是这个模式,比如:
图中是不是很熟悉呀,点击一个按钮,达到不同的界面,实现界面的切换,只是这个例子没有贴好看的图,图贴的好,那就是焕然一新了 ,据这个例子呢,学习中多思考,就会有不同的感觉。
好了先上布局:
布局非常的简单,大家估计很容易都能画出啦。接下来是对应的qss样式表:
QPushButton
{
color: white;
background-color: #27a9e3;
border-width: 0px;
border-radius: 3px;
}
QPushButton:hover
{
color: white;
background-color: #66c011;
border-width: 0px;
border-radius: 3px;
}
QPushButton:pressed
{
color: white;
background-color: yellow;
border-width: 0px;
border-radius: 3px;
}
QPushButton[pagematches=true]
{
color: white;
background-color: red;
border-width: 0px;
border-radius: 3px;
}
按钮4个状态的按钮,选中对应的为红色,然后不触发其他状态,让人觉得是选中的感觉;
那开始上代码部分吧:
#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 on_tabWidget_currentChanged(int index);
void on_button1_clicked();
void on_button2_clicked();
void on_button3_clicked();
private:
Ui::MainWindow *ui;
};
#endif // MAINWINDOW_H
对应的cpp文件:
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QStyle>
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
ui->button1->setProperty("pagematches", true);
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::on_tabWidget_currentChanged(int index)
{
// Set all buttons to false
ui->button1->setProperty("pagematches", false);
ui->button2->setProperty("pagematches", false);
ui->button3->setProperty("pagematches", false);
// Set one of the buttons to true
if (index == 0)
ui->button1->setProperty("pagematches", true);
else if (index == 1)
ui->button2->setProperty("pagematches", true);
else
ui->button3->setProperty("pagematches", true);
// Update buttons style
ui->button1->style()->polish(ui->button1);
ui->button2->style()->polish(ui->button2);
ui->button3->style()->polish(ui->button3);
}
void MainWindow::on_button1_clicked()
{
ui->tabWidget->setCurrentIndex(0);
}
void MainWindow::on_button2_clicked()
{
ui->tabWidget->setCurrentIndex(1);
}
void MainWindow::on_button3_clicked()
{
ui->tabWidget->setCurrentIndex(2);
}
是不是非常的简单:
喜欢的朋友可以关注我的博客,你的点赞会让我更加有动力编写,谢谢,例子在后边的连接里,可以下载来看:
链接:https://pan.baidu.com/s/1C0vRxnXMC29AcDLM9GK46A
提取码:csc9
如果连接失效的话,可以私信我,一起加油学习吧。