四、字符串与数值

发布时间:2024年01月14日

一、字符串与输入输出

1、字符串与数值之间转换

(1)SQtring类从字符串转换为整数的函数

// base 为进制
int toint(bool *ok=QUNLLPTR, int base=10);
const long toLong(bool *ok=QUNLLPTR, int base=10);
const short toShort(bool *ok=QUNLLPTR, int base=10);
const unsigned int toUInt(bool *ok=QUNLLPTR, int base=10);
const unsigned long toULong(bool *ok=QUNLLPTR, int base=10);

(2)QString将字符串转换为浮点数的函数

double toDouble(bool *ok=QUNLLPTR) const;
float toFloat(bool *ok=QUNLLPTR) const;

(3)数值格式化为字符串

格式化显示两位小数
str = QString::number(value, 'f', 2);
str = QString::asprintf("%.2f", value);
str = str.setNum(value, 'f', 2);
str = str.sprintf("%.2f", value);

2、实现一个进制转换工具

在这里插入图片描述

(1)创建项目,基于QWidget

(2)添加组件

在这里插入图片描述

(3)实现按钮信号与槽函数

void Widget::on_pushButton_clicked()
{
    QString str = ui->editNum->text();
    int num = str.toInt();
    str = ui->editPrice->text();
    float price = str.toFloat();

    float total = num*price;

    ui->editTotal->setText(QString::asprintf("%.2f", total));
}

void Widget::on_btnDec_clicked()
{
    QString str = ui->editDec->text();
    int nValue = str.toInt();
    str = str.setNum(nValue, 2);
    ui->editBin->setText(str);
    str = str.setNum(nValue, 16);
    ui->editHex->setText(str.toUpper());

}

void Widget::on_btnBin_clicked()
{
    QString str = ui->editBin->text();
    bool ok;
    int nValue = str.toInt(&ok, 2);
    str = str.setNum(nValue, 10);
    ui->editDec->setText(str);
    str = str.setNum(nValue, 16);
    ui->editHex->setText(str.toUpper());
}

void Widget::on_btnHex_clicked()
{
    QString str = ui->editHex->text();
    bool ok;
    int nValue = str.toInt(&ok, 16);
    str = str.setNum(nValue, 2);
    ui->editBin->setText(str);
    str = str.setNum(nValue, 10);
    ui->editDec->setText(str);
}

二、Qstring常用功能

QString存储字符采用Unicode码(16bit QChar)

1、创建项目,基于widget

2、添加组件

在这里插入图片描述

3、添加信号与槽

#include "widget.h"
#include "ui_widget.h"

Widget::Widget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget)
{
    ui->setupUi(this);
}

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

void Widget::on_pushButtonAppend_clicked()
{
    QString str1 = ui->comboBoxStr1->currentText();
    QString str2 = ui->comboBoxStr2->currentText();
    ui->lineEdit->setText(str1.append(str2));
}

void Widget::on_pushButtonCount_clicked()
{
    QString str1 = ui->comboBoxStr1->currentText();
    ui->labelSpin->setText("count:");
    ui->spinBox->setValue(str1.count());
}

void Widget::on_pushButtonStartWith_clicked()
{
    QString str1 = ui->comboBoxStr1->currentText();
    QString str2 = ui->comboBoxStr2->currentText();
    ui->checkBox->setChecked(str1.startsWith(str2));
}

void Widget::on_pushButtonEndWith_clicked()
{
    QString str1 = ui->comboBoxStr1->currentText();
    QString str2 = ui->comboBoxStr2->currentText();
    ui->checkBox->setChecked(str1.endsWith(str2));
}

void Widget::on_pushButtonPrepend_clicked()
{
    QString str1 = ui->comboBoxStr1->currentText();
    QString str2 = ui->comboBoxStr2->currentText();
    ui->lineEdit->setText(str1.prepend(str2));
}

void Widget::on_pushButtonToUpper_clicked()
{
    QString str1 = ui->comboBoxStr1->currentText();
    ui->lineEdit->setText(str1.toUpper());
}

void Widget::on_pushButtonToLower_clicked()
{
    QString str1 = ui->comboBoxStr1->currentText();
    ui->lineEdit->setText(str1.toLower());
}

void Widget::on_pushButtonLeft_clicked()
{

}

void Widget::on_pushButtonRight_clicked()
{

}

void Widget::on_pushButtonSize_clicked()
{
    QString str1 = ui->comboBoxStr1->currentText();
    ui->labelSpin->setText("size:");
    ui->spinBox->setValue(str1.size());
}

void Widget::on_pushButtonTrimmed_clicked()
{
    QString str1 = ui->comboBoxStr1->currentText();
    ui->lineEdit->setText(str1.trimmed());
}

void Widget::on_pushButtonSimplified_clicked()
{
    QString str1 = ui->comboBoxStr1->currentText();
    ui->lineEdit->setText(str1.simplified());
}

void Widget::on_pushButtonIndexof_clicked()
{
    QString str1 = ui->comboBoxStr1->currentText();
    QString str2 = ui->comboBoxStr2->currentText();
    ui->labelSpin->setText("Indexof:");
    ui->spinBox->setValue(str1.indexOf(str2));
}

void Widget::on_pushButtonLastIndexof_clicked()
{
    QString str1 = ui->comboBoxStr1->currentText();
    QString str2 = ui->comboBoxStr2->currentText();
    ui->labelSpin->setText("LastIndexof:");
    ui->spinBox->setValue(str1.lastIndexOf(str2));
}

void Widget::on_pushButtonIsNull_clicked()
{
    QString str1 = ui->comboBoxStr1->currentText();
    ui->checkBox->setChecked(str1.isNull());
}

void Widget::on_pushButtonIsempty_clicked()
{
    QString str1 = ui->comboBoxStr1->currentText();
    ui->checkBox->setChecked(str1.isEmpty());
}



void Widget::on_pushButtonContains_clicked()
{
    QString str1 = ui->comboBoxStr1->currentText();
    QString str2 = ui->comboBoxStr2->currentText();
    //CaseSensitive 区分大小写
    //CaseInsensitive 不区分大小写
    ui->checkBox->setChecked(str1.contains(str2, Qt::CaseSensitive));
}

void Widget::on_pushButtonSection_clicked()
{
    // section(分隔符,起始编号,结束编号) 字符串分割
    QString str1 = ui->comboBoxStr1->currentText();
    QString str2 = ui->comboBoxStr2->currentText();

    QString str = "value1,value2,value3";
    str.section(",", 1, 2); // value2,value3
}

三、SpinBox使用

QSpinBox和QDoubleSpinBox都是QAsbstractSpinBox的子类

1、属性

  • prefix:数字显示的缀,如$
  • suffix:数字显示的后缀,如Kg
  • minimum:数值范围的最小值
  • maximum:数值范围的最大值
  • singlestep:单机有测上下调整按钮的单步改变值,如2,则每次改变2
  • value:当前显示的值
  • displayintgerBase:QSpinBox特有属性,显示整数使用的进制,例如2,显示二进制
  • decimals:QDoubleSpinBox特有属性,显示数值的小数位,例如2,显示小数点后两位小数

2、使用SpinBox实现工具

(1)创建项目

(2)添加组件

在这里插入图片描述

(3)添加信号与槽

#include "widget.h"
#include "ui_widget.h"

Widget::Widget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget)
{
    ui->setupUi(this);
}

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

void Widget::on_pushButton_clicked()
{
    int num = ui->spinBoxNum->value();
    float price = ui->doubleSpinBoxPrice->value();
    float total = num*price;
    ui->doubleSpinBoxTotal->setValue(total);
}

void Widget::on_btnDec_clicked()
{
    int nValue = ui->spinBoxDec->value();
    ui->spinBoxBin->setValue(nValue);
    ui->spinBoxHex->setValue(nValue);
}

void Widget::on_btnBin_clicked()
{
    int nValue = ui->spinBoxBin->value();
    ui->spinBoxDec->setValue(nValue);
    ui->spinBoxHex->setValue(nValue);
}

void Widget::on_btnHex_clicked()
{
    int nValue = ui->spinBoxHex->value();
    ui->spinBoxBin->setValue(nValue);
    ui->spinBoxDec->setValue(nValue);
}

void Widget::on_spinBoxNum_valueChanged(int arg1)
{
    Q_UNUSED(arg1);
    on_pushButton_clicked();
}

void Widget::on_doubleSpinBoxPrice_valueChanged(double arg1)
{
    Q_UNUSED(arg1);
    on_pushButton_clicked();
}

四、数字输入和显示组件

数显组件
  • QSlider:滑动条,用于数值输入
  • QScrollBar:卷滚条,用于数值输入,用于卷滚区域
  • QProgressBar:进入条,一般用于显示数值百分比
  • QDial:表盘式数值输入组件,可以通过转动表针获取输入值
  • QLCDNumber:模仿LCD(数码管)数字显示组件,可以显示整数或浮点数,整数可以显示不同进制。

1、实现数字输入和输出工具

(1)创建项目(基于widget)

(2)添加组件

在这里插入图片描述

(3)QTextEdit底色设置

在这里插入图片描述

(4)添加信号与槽

#include "widget.h"
#include "ui_widget.h"

Widget::Widget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget)
{
    ui->setupUi(this);
}

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


void Widget::on_horizontalSliderRed_valueChanged(int value)
{
    Q_UNUSED(value)
    QPalette palette = ui->textEdit->palette();
    QColor color;
    color.setRgb(ui->horizontalSliderRed->value(),
                 ui->horizontalSliderGreen->value(),
                 ui->horizontalSliderBlue->value());
    palette.setColor(QPalette::Base, color);
    ui->textEdit->setPalette(palette);
}

void Widget::on_horizontalSliderGreen_valueChanged(int value)
{
    Q_UNUSED(value)
    QPalette palette = ui->textEdit->palette();
    QColor color;
    color.setRgb(ui->horizontalSliderRed->value(),
                 ui->horizontalSliderGreen->value(),
                 ui->horizontalSliderBlue->value());
    palette.setColor(QPalette::Base, color);
    ui->textEdit->setPalette(palette);
}

void Widget::on_horizontalSliderBlue_valueChanged(int value)
{
    Q_UNUSED(value)
    QPalette palette = ui->textEdit->palette();
    QColor color;
    color.setRgb(ui->horizontalSliderRed->value(),
                 ui->horizontalSliderGreen->value(),
                 ui->horizontalSliderBlue->value());
    palette.setColor(QPalette::Base, color);
    ui->textEdit->setPalette(palette);
}

void Widget::on_horizontalSlider_5_valueChanged(int value)
{
    ui->progressBarH->setValue(value);
    ui->horizontalScrollBar->setValue(value);
}

void Widget::on_verticalSlider_valueChanged(int value)
{
    ui->progressBarV->setValue(value);
    ui->verticalScrollBar->setValue(value);
}

void Widget::on_dial_valueChanged(int value)
{
    ui->lcdNumber->display(value);
}

void Widget::on_rbtnDec_clicked()
{
    ui->lcdNumber->setDigitCount(3);
    ui->lcdNumber->setDecMode();
}

void Widget::on_rbtnBin_clicked()
{
    ui->lcdNumber->setDigitCount(3);
    ui->lcdNumber->setBinMode();
}

void Widget::on_rbtnOct_clicked()
{
    ui->lcdNumber->setDigitCount(3);
    ui->lcdNumber->setOctMode();
}

void Widget::on_rbtnHex_clicked()
{
    ui->lcdNumber->setDigitCount(3);
    ui->lcdNumber->setHexMode();
}

五、时间日期和定时器

时间函数
  • QTime:时间数据类型,如15:24.20
  • QDate:日期数据类型,如2024-1-1
  • QDataTime:日期时间数据类型,如2024-1-1 15:24.20
  • QdateEdit:编辑和显示日期的组件
  • QDateTimeEdit:编辑和显示日期时间的组件
  • QCalendarWidget:一个用日历形式选择日期的组件
  • QTimer:定时器,如果周期为100,则每100毫秒会发射一次timeout信号

实现日期设置与显示工具

在这里插入图片描述

(1)创建项目(基于Widget)

(2)添加组件

在这里插入图片描述

(3)添加信号与槽

#include "widget.h"
#include "ui_widget.h"

Widget::Widget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget)
{
    ui->setupUi(this);

    m_fTimer = new QTimer(this);
    m_fTimer->setInterval(1000);    // 每1000毫秒发出一个信号
    m_fTimer->stop();

    connect(m_fTimer, SIGNAL(timeout()), this, SLOT(on_timer_timeout()));
}

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

void Widget::on_btnGetCurrTime_clicked()
{
    QDateTime curDateTime = QDateTime::currentDateTime();
    ui->timeEdit->setTime(curDateTime.time());
    ui->lineEditTime->setText(curDateTime.toString("hh:mm:ss"));
    ui->dateEdit->setDate(curDateTime.date());
    ui->lineEditDate->setText(curDateTime.toString("yyyy-MM-dd"));
    ui->dateTimeEdit->setDateTime(curDateTime);
    ui->lineEditDateTime->setText(curDateTime.toString("yyyy-MM-dd hh:mm:ss"));
}

void Widget::on_btnSetTime_clicked()
{
    QString str = ui->lineEditTime->text();
    QTime time = QTime::fromString(str, "hh:mm:ss");
    ui->timeEdit->setTime(time);
}

void Widget::on_btnSetDate_clicked()
{
    QString str = ui->lineEditDate->text();
    QDate date = QDate::fromString(str, "yyyy-MM-dd");
    ui->dateEdit->setDate(date);
}

void Widget::on_btnSetDateTime_clicked()
{
    QString str = ui->lineEditDateTime->text();
    QDateTime dateTime = QDateTime::fromString(str, "yyyy-MM-dd hh:mm:ss");
    ui->dateTimeEdit->setDateTime(dateTime);
}

void Widget::on_calendarWidget_selectionChanged()
{
    QDate date = ui->calendarWidget->selectedDate();
    ui->lineEditSelectDate->setText(date.toString("yyyy年MM月dd"));
}

void Widget::on_timer_timeout()
{
    ui->lcdNumberHour->display(QTime::currentTime().hour());
    ui->lcdNumberMinute->display(QTime::currentTime().minute());
    ui->lcdNumberSecond->display(QTime::currentTime().second());
    int value = ui->progressBar->value();
    if(++value > 100)
    {
        value = 0;
    }
    ui->progressBar->setValue(value);
}

void Widget::on_btnSetTimer_clicked()
{
    m_fTimer->setInterval(ui->spinBoxTimer->value());
}

void Widget::on_btnStart_clicked()
{
    m_fTimer->start();
    ui->btnStart->setEnabled(false);
    ui->btnStop->setEnabled(true);
    ui->btnSetTimer->setEnabled(false);
    m_fTimeCounter.start();
}

void Widget::on_btnStop_clicked()
{
    m_fTimer->stop();
    ui->btnStart->setEnabled(true);
    ui->btnStop->setEnabled(false);
    ui->btnSetTimer->setEnabled(true);

    int tmMsec = m_fTimeCounter.elapsed();
    int sec = tmMsec/1000;
    int mSec = tmMsec%1000;
    QString str = QString::asprintf("时间流逝:%d秒%.d毫秒", sec, mSec);
    ui->labelCount->setText(str);
}

六、QComBox和QPlainEdit

1、实现工具

在这里插入图片描述

(1)创建项目,基于Widget

(2)添加组件

在这里插入图片描述

(3)添加资源文件图片

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

(4)添加信号与槽

#include "widget.h"
#include "ui_widget.h"
#include <QTextDocument>
#include <QTextBlock>
#include <QMenu>

Widget::Widget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget)
{
    ui->setupUi(this);
}

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

void Widget::on_btnInitCom_clicked()
{
    QIcon icon(":images/icons/blod.png");
    ui->comboBox->clear();
    for(int i=0;i<20;i++)
    {
        ui->comboBox->addItem(icon, QString::asprintf("Item %d", i));
    }
}

void Widget::on_btnClearCom_clicked()
{
    ui->comboBox->clear();
}

void Widget::on_btnInitCity_clicked()
{
    ui->comboBoxCity->clear();
    QIcon icon(":images/icons/cut.png");
    QMap<QString, int> mapCityZone;
    mapCityZone["北京"] = 10;
    mapCityZone["天津"] = 20;
    mapCityZone["上海"] = 30;
    foreach (auto str, mapCityZone.keys()) {
        ui->comboBoxCity->addItem(icon,
                                  str, mapCityZone[str]);
    }
}

void Widget::on_checkBoxEnEdit_clicked(bool checked)
{
    ui->comboBox->setEditable(checked);
}

void Widget::on_comboBox_currentIndexChanged(const QString &arg1)
{
    if(!arg1.isEmpty()){
        ui->plainTextEdit->appendPlainText(arg1);
    }
}

void Widget::on_comboBoxCity_currentIndexChanged(const QString &arg1)
{
    if(!arg1.isEmpty()){
        ui->plainTextEdit->appendPlainText(arg1+"区号:"+
                                           ui->comboBoxCity->currentData().toString());
    }

}

void Widget::on_checkBox_clicked(bool checked)
{
    ui->plainTextEdit->setReadOnly(checked);
}

void Widget::on_btnClearText_clicked()
{
    ui->plainTextEdit->clear();
}

void Widget::on_btnAdd_clicked()
{
    ui->comboBox->clear();
    QIcon icon(":images/icons/blod.png");
    QTextDocument *doc = ui->plainTextEdit->document();
    int num = doc->blockCount();
    for (int var = 0; var < num; ++var) {
        ui->comboBox->addItem(icon, doc->findBlockByNumber(var).text());
    }
}

七、QListWidget和QToolButton

Qt中用于项(Item)处理的组件有两类:Item Views和ItemWidgets

在这里插入图片描述

1、List Widget支持右击菜单

(1)方法一,属性

在这里插入图片描述

(2)方法二、程序

ui->listWidget->setContextMentPolicy(Qt::CustomContextMent)

2、实现工具

在这里插入图片描述

(1)创建项目,基于QMainWindow

(2)移除状态栏和工具栏

在这里插入图片描述
在这里插入图片描述

(3)添加资源文件(图标)

在这里插入图片描述

(4)添加Action与工具栏

在这里插入图片描述

(5)添加Tool Box和Tab Widget

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

(6)添加Tool Button

在这里插入图片描述

(7)ToolButton添加下拉功能

在这里插入图片描述

(8)工具栏按钮添加菜单

    // 工具栏添加菜单
    QMenu *menu = new QMenu(this);
    menu->addAction(ui->actSelAll);
    menu->addAction(ui->actSelInvs);
    menu->addAction(ui->actSelNone);
    ui->actSelMenu->setMenu(menu);
    ui->mainToolBar->addAction(ui->actSelMenu);
    ui->tBtnSelItem->setDefaultAction(ui->actSelMenu);

在这里插入图片描述

(9)给QListWidget添加右键菜单支持

在这里插入图片描述

(10)添加信号与槽

#include "mainwindow.h"
#include "ui_mainwindow.h"

#include <QMenu>

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    setCentralWidget(ui->splitter); //将分裂器水平布局(Tool Box和Tab Widget)作为界面主体

    // 将ToolButton与action绑定
    ui->tBtnListIni->setDefaultAction(ui->actListIni);
    ui->tBtnListClear->setDefaultAction(ui->actListClear);
    ui->tBtnListAdd->setDefaultAction(ui->actListAppend);
    ui->tBtnListInsert->setDefaultAction(ui->actInsert);
    ui->tBtnListDelete->setDefaultAction(ui->actListDelete);

    ui->tBtnSelAll->setDefaultAction(ui->actSelAll);
    ui->tBtnSelInv->setDefaultAction(ui->actSelInvs);
    ui->tBtnSelNone->setDefaultAction(ui->actSelNone);

    // 工具栏添加菜单
    QMenu *menu = new QMenu(this);
    menu->addAction(ui->actSelAll);
    menu->addAction(ui->actSelInvs);
    menu->addAction(ui->actSelNone);
    ui->actSelMenu->setMenu(menu);
    ui->mainToolBar->addAction(ui->actSelMenu);
    ui->tBtnSelItem->setDefaultAction(ui->actSelMenu);

    // 添加分隔符
    ui->mainToolBar->addSeparator();
    // 添加退出工具
    ui->mainToolBar->addAction(ui->actQuit);
}

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

void MainWindow::on_toolBox_currentChanged(int index)
{   // 将toolBox与tabWidget绑定
    ui->tabWidget->setCurrentIndex(index);
}

void MainWindow::on_actListIni_triggered()
{
    ui->listWidget->clear();
    QListWidgetItem *aItem;
    QIcon icon(":/images/images/paste.png");
    bool bCheck = ui->checkBoxEdit->isChecked();

    for (int var = 0; var < 20; ++var) {
        QString str = QString::asprintf("Item %d", var);
        aItem = new QListWidgetItem(str);
        aItem->setIcon(icon);
        aItem->setCheckState(Qt::Checked);
        if(bCheck) {
            aItem->setFlags(Qt::ItemIsSelectable|Qt::ItemIsEditable|
                            Qt::ItemIsUserCheckable|Qt::ItemIsEnabled);
        }
        else {
            aItem->setFlags(Qt::ItemIsSelectable|
                            Qt::ItemIsUserCheckable|Qt::ItemIsEnabled);
        }
        ui->listWidget->addItem(aItem);
    }
}

void MainWindow::on_actListClear_triggered()
{
    ui->listWidget->clear();
}

void MainWindow::on_actInsert_triggered()
{
    QListWidgetItem *aItem;
    QIcon icon(":/images/images/paste.png");
    bool bCheck = ui->checkBoxEdit->isChecked();

    aItem = new QListWidgetItem("new Inserted Item");
    aItem->setIcon(icon);
    aItem->setCheckState(Qt::Checked);
    if(bCheck) {
        aItem->setFlags(Qt::ItemIsSelectable|Qt::ItemIsEditable|
                        Qt::ItemIsUserCheckable|Qt::ItemIsEnabled);
    }
    else {
        aItem->setFlags(Qt::ItemIsSelectable|
                        Qt::ItemIsUserCheckable|Qt::ItemIsEnabled);
    }
    ui->listWidget->insertItem(ui->listWidget->currentRow(), aItem);
}

void MainWindow::on_actListAppend_triggered()
{
    QListWidgetItem *aItem;
    QIcon icon(":/images/images/paste.png");
    bool bCheck = ui->checkBoxEdit->isChecked();

    aItem = new QListWidgetItem("new Append Item");
    aItem->setIcon(icon);
    aItem->setCheckState(Qt::Checked);
    if(bCheck) {
        aItem->setFlags(Qt::ItemIsSelectable|Qt::ItemIsEditable|
                        Qt::ItemIsUserCheckable|Qt::ItemIsEnabled);
    }
    else {
        aItem->setFlags(Qt::ItemIsSelectable|
                        Qt::ItemIsUserCheckable|Qt::ItemIsEnabled);
    }
    ui->listWidget->addItem(aItem);
}

void MainWindow::on_actListDelete_triggered()
{
    QListWidgetItem *aItem = ui->listWidget->takeItem(ui->listWidget->currentRow());
    delete aItem;
}

void MainWindow::on_actSelAll_triggered()
{
    int count = ui->listWidget->count();
    for (int var = 0; var < count; ++var) {
        QListWidgetItem *aItem = ui->listWidget->item(var);
        aItem->setCheckState(Qt::Checked);
    }
}

void MainWindow::on_actSelNone_triggered()
{
    int count = ui->listWidget->count();
    for (int var = 0; var < count; ++var) {
        QListWidgetItem *aItem = ui->listWidget->item(var);
        aItem->setCheckState(Qt::Unchecked);
    }
}

void MainWindow::on_actSelInvs_triggered()
{
    int count = ui->listWidget->count();
    for (int var = 0; var < count; ++var) {
        QListWidgetItem *aItem = ui->listWidget->item(var);
        if(aItem->checkState() == Qt::Checked) {
            aItem->setCheckState(Qt::Unchecked);
        }
        else {
            aItem->setCheckState(Qt::Checked);
        }

    }
}

void MainWindow::on_checkBoxEdit_clicked(bool checked)
{
    int count = ui->listWidget->count();
    for (int var = 0; var < count; ++var) {
        QListWidgetItem *aItem = ui->listWidget->item(var);
        if(checked){
            aItem->setFlags(Qt::ItemIsSelectable|Qt::ItemIsEditable|
                            Qt::ItemIsUserCheckable|Qt::ItemIsEnabled);
        }
        else{
            aItem->setFlags(Qt::ItemIsSelectable|
                            Qt::ItemIsUserCheckable|Qt::ItemIsEnabled);
        }


    }
}

void MainWindow::on_listWidget_currentItemChanged(QListWidgetItem *current, QListWidgetItem *previous)
{
    QString str;
    if(NULL != current){
        if(NULL == previous){
            str = "当前项:"+current->text();
        }
        else{
            str = "前一项:"+previous->text() + " 当前项:"+current->text();
        }
        ui->lineEditCurrItem->setText(str);
    }
}

void MainWindow::on_listWidget_customContextMenuRequested(const QPoint &pos)
{
    Q_UNUSED(pos)

    QMenu *menu = new QMenu(this);
    menu->addAction(ui->actListIni);
    menu->addAction(ui->actListClear);
    menu->addAction(ui->actInsert);
    menu->addAction(ui->actListAppend);
    menu->addAction(ui->actListDelete);
    menu->addSeparator();
    menu->addAction(ui->actSelAll);
    menu->addAction(ui->actSelInvs);
    menu->addAction(ui->actSelNone);

    menu->exec(QCursor::pos()); //在鼠标光标位置显示右键菜单
    delete menu; //手动创建的指针必须手动删除
}

八、QTreeWidget和QDockWidget

1、实现工具

在这里插入图片描述

(1)创建项目,基于QMainWindow

(2)添加QTreeWidget和QDockWidget

在这里插入图片描述
在这里插入图片描述
停靠位置设置
在这里插入图片描述

(3)添加action

在这里插入图片描述

(4)将工具变为不可使用

在这里插入图片描述

(5)添加图片显示区域

在这里插入图片描述

(6)添加信号与槽

#include "mainwindow.h"
#include "ui_mainwindow.h"


MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    ui->statusBar->addWidget(&labFileName);
}

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

void MainWindow::on_actDockVisible_toggled(bool arg1)
{
    ui->dockWidget->setVisible(arg1);
}

void MainWindow::on_actDockFloat_toggled(bool arg1)
{
    ui->dockWidget->setFloating(arg1);
}

void MainWindow::on_dockWidget_topLevelChanged(bool topLevel)
{ // 是否停靠在主界面中
    ui->actDockFloat->setChecked(topLevel);
}

void MainWindow::on_dockWidget_visibilityChanged(bool visible)
{ // 是否可见
    ui->actDockFloat->setVisible(visible);
}

#include <QFileDialog>
void MainWindow::on_actAddFolfer_triggered()
{
    // 获取当前目录
    QString fullname = QFileDialog::getExistingDirectory();
    if(fullname.isEmpty()) {
        return;
    }
    QString dir = fullname.right(fullname.length()-fullname.lastIndexOf("/")-1);
    QTreeWidgetItem *parItem = ui->treeWidget->currentItem();
    if(nullptr == parItem) {
        // 当没有选中时,上一步获取为空,会导致奔溃,这里默认选中第一项
        parItem = ui->treeWidget->topLevelItem(0);
    }
    QTreeWidgetItem *item = new QTreeWidgetItem(itGroupItem);
    QIcon icon(":/images/images/bold.png");
    item->setIcon(colItem, icon);
    item->setText(colItem, dir);
    item->setText(colItemType, "type:group");
    item->setFlags(Qt::ItemIsSelectable|Qt::ItemIsAutoTristate|
                   Qt::ItemIsEnabled|Qt::ItemIsUserCheckable);
    item->setCheckState(colItem, Qt::Checked);
    parItem->addChild(item);
}

void MainWindow::on_actAddFile_triggered()
{
    QStringList files = QFileDialog::getOpenFileNames(this, "选择一个会多个文件", "",
                                                      "Images(*.png)");
    QTreeWidgetItem *parItem = nullptr;
    QTreeWidgetItem *item = ui->treeWidget->currentItem();

    if(nullptr == item) {
        // 当没有选中时,上一步获取为空,会导致奔溃,这里默认选中第一项
        item = ui->treeWidget->topLevelItem(0);
    }

    if(item->type() == itImageItem){
        parItem = item->parent();
    }
    else {
        parItem = item;
    }

    foreach(auto file, files){
        QTreeWidgetItem *item = new QTreeWidgetItem(itImageItem);
        QIcon icon(":/images/images/copy.png");
        item->setIcon(colItem, icon);
        QString str = file.right(file.length()-file.lastIndexOf("/")-1);
        item->setText(colItem, str);
        item->setText(colItemType, "type:imagesFile");
        item->setFlags(Qt::ItemIsSelectable|Qt::ItemIsAutoTristate|
                       Qt::ItemIsEnabled|Qt::ItemIsUserCheckable);
        item->setCheckState(colItem, Qt::Checked);
        item->setData(colItem, Qt::UserRole, file);

        parItem->addChild(item);
    }
}

void MainWindow::on_treeWidget_currentItemChanged(QTreeWidgetItem *current, QTreeWidgetItem *previous)
{
    Q_UNUSED(previous)
    if(current == nullptr){
        return;
    }
    int var = current->type();
    switch (var) {
    case itTopItem:
        ui->actAddFile->setEnabled(true);
        ui->actAddFolfer->setEnabled(true);
        ui->actDeleteItem->setEnabled(true);
        break;
    case itGroupItem:
        ui->actAddFile->setEnabled(true);
        ui->actAddFolfer->setEnabled(true);
        ui->actDeleteItem->setEnabled(true);
        break;
    case itImageItem:
        ui->actAddFile->setEnabled(true);
        ui->actAddFolfer->setEnabled(false);
        ui->actDeleteItem->setEnabled(true);

        // 显示图片和状态栏显示文件路径
        labFileName.setText(current->data(colItem, Qt::UserRole).toString());
        currPixmap.load(current->data(colItem, Qt::UserRole).toString());
        on_actSuitW_triggered();


        // 使能工具栏
        ui->actZoomIn->setEnabled(true);
        ui->actZoomOut->setEnabled(true);

        ui->actSuitW->setEnabled(true);
        ui->actSuitH->setEnabled(true);
        ui->actRealSize->setEnabled(true);

        break;
    default:
        break;
    }
}

void MainWindow::on_actSuitW_triggered()
{
    int w = ui->scrollArea->width();
    int realW = currPixmap.width();
    pixRatio = (float)w/realW;
    QPixmap pix = currPixmap.scaledToWidth(w-30);
    ui->label->setPixmap(pix);
}

void MainWindow::changeItemCaption(QTreeWidgetItem *item)
{
    QString str = "*"+item->text(colItem);
    item->setText(colItem, str);
    for (int var = 0; var < item->childCount(); ++var) {
        changeItemCaption( item->child(var) );
    }
}

void MainWindow::on_actScanItems_triggered()
{
    for (int var = 0; var < ui->treeWidget->topLevelItemCount(); ++var) {
        changeItemCaption(ui->treeWidget->topLevelItem(var));
    }
}

void MainWindow::on_actDeleteItem_triggered()
{
    QTreeWidgetItem *item = ui->treeWidget->currentItem();
    if(item == nullptr){
        return;
    }
    QTreeWidgetItem *parItem = item->parent();
    parItem->removeChild(item);
    delete item;
}

void MainWindow::on_actSuitH_triggered()
{
    int h = ui->scrollArea->height();
    int realH = currPixmap.height();
    pixRatio = (float)h/realH;
    QPixmap pix = currPixmap.scaledToHeight(h-30);
    ui->label->setPixmap(pix);
}

void MainWindow::on_actZoomIn_triggered()
{
    pixRatio *= 1.2;
    int w = pixRatio*currPixmap.width();
    int h = pixRatio*currPixmap.height();
    QPixmap pix = currPixmap.scaled(w, h);
    ui->label->setPixmap(pix);
}

void MainWindow::on_actZoomOut_triggered()
{
    pixRatio /= 1.2;
    int w = pixRatio*currPixmap.width();
    int h = pixRatio*currPixmap.height();
    QPixmap pix = currPixmap.scaled(w, h);
    ui->label->setPixmap(pix);
}

void MainWindow::on_actRealSize_triggered()
{
    pixRatio = 1;
    ui->label->setPixmap(currPixmap);
}

九、QTableWidget使用

1、实现工具

在这里插入图片描述

(1)创建项目,基于QWidget

(2)添加资源文件(图标)

(3)添加组件

在这里插入图片描述

(4)添加信号与曹

#include "widget.h"
#include "ui_widget.h"



Widget::Widget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget)
{
    ui->setupUi(this);
}

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

void Widget::on_btnSetTable_clicked()
{
    QTableWidgetItem *headerItem;
    QStringList headerText;
    headerText<<"姓 名"<<"性 别"<<"出生日期"<<"民 族"<<"分 数"<<"是否是党员";
    ui->tableWidget->setColumnCount(headerText.count());
    for (int var = 0; var < ui->tableWidget->columnCount(); ++var) {
        headerItem = new QTableWidgetItem(headerText.at(var));
        QFont font = ui->tableWidget->font();
        font.setBold(true);
        font.setPointSize(12);
        headerItem->setFont(font);
        headerItem->setTextColor(Qt::red);
        ui->tableWidget->setHorizontalHeaderItem(var, headerItem);
    }
}

void Widget::on_btnSetRowNum_clicked()
{
    int rowNum = ui->spinBox->value();
    ui->tableWidget->setRowCount(rowNum);

    if(ui->checkBoxRowColor->isChecked()){
        ui->tableWidget->setAlternatingRowColors(true);
    }
    else {
        ui->tableWidget->setAlternatingRowColors(false);
    }
}

void Widget::on_checkBoxRowColor_clicked(bool checked)
{
    ui->tableWidget->setAlternatingRowColors(checked);
}

void Widget::createItemsRow(int rowNo, QString strName, QString strSex, QDate dBirth, QString strNation, bool bPM, int nScore)
{
    QTableWidgetItem *item;
    unsigned int uStudID = 10000;
    // name
    item = new QTableWidgetItem(strName, ctName);
    item->setTextAlignment(Qt::AlignHCenter|Qt::AlignVCenter);
    item->setData(Qt::UserRole, uStudID++);
    ui->tableWidget->setItem(rowNo, colName, item);
    // sex
    item = new QTableWidgetItem(strSex, ctSex);
    item->setTextAlignment(Qt::AlignHCenter|Qt::AlignVCenter);
    QIcon icon;
    if(strSex.compare("男")){
        icon.addFile(":/images/copy.png");
    }
    else{
        icon.addFile(":/images/paste.png");
    }
    item->setIcon(icon);
    ui->tableWidget->setItem(rowNo, colSex, item);
    // birth
    item = new QTableWidgetItem(dBirth.toString("yyyy-MM-dd"), ctBirth);
    item->setTextAlignment(Qt::AlignHCenter|Qt::AlignVCenter);
    ui->tableWidget->setItem(rowNo, colBirth, item);
    // nation
    item = new QTableWidgetItem(strNation, ctNation);
    item->setTextAlignment(Qt::AlignHCenter|Qt::AlignVCenter);
    ui->tableWidget->setItem(rowNo, colNation, item);
    // scope
    item = new QTableWidgetItem(QString::asprintf("%d",nScore), ctScope);
    item->setTextAlignment(Qt::AlignHCenter|Qt::AlignVCenter);
    ui->tableWidget->setItem(rowNo, colScope, item);
    // party
    item = new QTableWidgetItem("党员", ctParty);
    if(bPM){
        item->setCheckState(Qt::Checked);
    }
    else{
        item->setCheckState(Qt::Unchecked);
    }
    item->setTextAlignment(Qt::AlignHCenter|Qt::AlignVCenter);
    item->setBackgroundColor(Qt::yellow);
    ui->tableWidget->setItem(rowNo, colParty, item);

}


void Widget::on_btnInitTable_clicked()
{
    QString strName, strSex;
    bool bParty=false;
    QDate dBirth;
    dBirth.setDate(1999, 1,11);

    ui->tableWidget->clearContents();
    for (int var = 0; var < ui->tableWidget->rowCount(); ++var) {
        strName = QString::asprintf("学生%d", var);
        if(var % 3 == 0){
            strSex = "女";
        }
        else{
            strSex = "男";
        }
        dBirth.addDays(15);
        bParty = var%2==1?true:false;
        createItemsRow(var, strName, strSex, dBirth, "汉族", bParty, var+60);
    }
}

void Widget::on_btnInsertRow_clicked()
{
    int nRow = ui->tableWidget->currentRow();
    ui->tableWidget->insertRow(nRow);
    createItemsRow(nRow, "新学生", "男",QDate::fromString("1999-01-11","yyyy-MM-dd"),
                   "汉族", true, 89);
}

void Widget::on_btnAddRow_clicked()
{
    int nRow = ui->tableWidget->rowCount();
    ui->tableWidget->insertRow(nRow);
    createItemsRow(nRow, "新学生", "男",QDate::fromString("1999-01-11","yyyy-MM-dd"),
                   "汉族", true, 89);
}

void Widget::on_btnDeleteRow_clicked()
{
    ui->tableWidget->removeRow(ui->tableWidget->currentRow());
}

void Widget::on_btnAutoH_clicked()
{
    ui->tableWidget->resizeRowsToContents();
}

void Widget::on_btnAutoW_clicked()
{
    ui->tableWidget->resizeColumnsToContents();
}

void Widget::on_btnReadTable_clicked()
{
    ui->plainTextEdit->clear();
    QString str;
    QTableWidgetItem *cellItem;
    for (int row = 0; row < ui->tableWidget->rowCount(); ++row) {
        str = "";
        for (int col = 0; col < ui->tableWidget->columnCount()-1; ++col) {
            cellItem = ui->tableWidget->item(row, col);
            str += cellItem->text() + " ";
        }
        cellItem = ui->tableWidget->item(row, colParty);
        if(cellItem->checkState() == Qt::Checked){
            str += "党员";
        }
        else{
            str += "群众";
        }
        ui->plainTextEdit->appendPlainText(str);
    }
}

void Widget::on_checkBoxTableEditdble_clicked(bool checked)
{
    if(checked){
        ui->tableWidget->setEditTriggers(QAbstractItemView::DoubleClicked|
                                         QAbstractItemView::SelectedClicked);
    }
    else{
        ui->tableWidget->setEditTriggers(QAbstractItemView::NoEditTriggers);
    }
}

void Widget::on_checkBoxHeaderH_clicked(bool checked)
{
    ui->tableWidget->horizontalHeader()->setVisible(checked);
}

void Widget::on_checkBoxHeaderV_clicked(bool checked)
{
    ui->tableWidget->verticalHeader()->setVisible(checked);
}

void Widget::on_radioButton_2_clicked()
{
    ui->tableWidget->setSelectionBehavior(QAbstractItemView::SelectRows);
}

void Widget::on_radioButton_clicked()
{
    ui->tableWidget->setSelectionBehavior(QAbstractItemView::SelectItems);
}
文章来源:https://blog.csdn.net/liutit/article/details/135441174
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。