目录
- 前言
- QT
- 小记
- 1. 菜单栏、工具栏、状态栏
- 2. 自定义的对话框
- 3. 任务管理器
- 4. 链接数据库mysql,sqlite
- 5. Widgets Gallery Example 代码学习:
- 999.Controls
- QT-For-Python
- 1. Demo
- QT-Quick
- 1. HelloWorld
- 2. 简单表单
前言
记录有关qt的案例。
QT小记
知识点:1. ui_widget.h:类的名称是Ui_widget.h,根据组件、信号与信号槽自动生成。2. 数学运算函数在 头文件中定义3. 消息显示: qDebug,qWarning、qCritical、qFatal、qInfo 4. 全局宏:QT_VERSION、QT_VERSION_STR、5. 容器:QList、QStack和QQueue;QMap、QMultiMap、QHash、QMultiHash和QSet。6. QGridLayout类添加组件的函数是addWidget():7. QAbstractButton的autoExclusive属性:如果启用了自动独占性,属于同一个父部件的可检查按钮将互斥。8. QGroupBox的flat属性:可以最小化区域框的空间消耗。在大多数样式中,启用这个属性会移除框架的左边缘、右边缘和底边。9. Sql模块对Cmake文件添加: find_package(Qt${QT_VERSION_MAJOR} COMPONENTS Sql REQUIRED)在target_link_libraries中添加Qt${QT_VERSION_MAJOR}::Sql代码:1. 编码格式#include //添加头文件QTextCodec::setCodecForTr(QTextCodec::codecForLocale()); //设置编码QTextCodec::setCodecForTr(QTextCodec::codecForName("GB2312"));2. tr()函数 =>随国际化变化。ui->pushButton->setText(tr("新窗口"));4. 常用控件属性设置:if(ui->usrLineEdit->text().trimmed() == tr("admin")&& ui->pwdLineEdit->text() == tr("123456"))QLabel *lab; //声明this->lab=new QLabel("hello,world",this);ui->firstBtn->setText("新窗口");QMessageBox::warning(this, tr("Waring"),tr("error!"), QMessageBox::Yes); ui->pwdLineEdit->clear();ui->usrLineEdit->setFocus();5. 菜单设置:// 创建新的动作 添加图标 设置快捷键QAction *openAction = new QAction(tr("&Open"), this);QIcon icon(":/myImages/images/close.png");openAction->setIcon(icon);openAction->setShortcut(QKeySequence(tr("Ctrl+O")));ui->menu_F->addAction(openAction);6. 其他://记事本打开myResources.qrc //文件(&F)//添加资源文件=>/myImages=>images=>需要的图标文件粘贴进去=>可以别名是一个XML文档表明将菜单的快捷键设置为了Alt+ Ficon(":/myImages/close");7. qDebug("111"+str); qDebug()<plainTextEdit->font();font.setBold(checked);//font.setItalic(checked);font.setUnderline(checked);ui->plainTextEdit->setFont(font);QPalette plet=ui->plainTextEdit->palette();if(ui->radioButton_black->isChecked()) plet.setColor(QPalette::Text,Qt::black);if(ui->radioButton_blue->isChecked()) plet.setColor(QPalette::Text,Qt::blue);if(ui->radioButton_red->isChecked()) plet.setColor(QPalette::Text,Qt::red);ui->plainTextEdit->setPalette(plet);QPushButton btn("button");QObject::connect(&btn,&QPushButton::clicked,&QApplication::quit);QObject::connect(&btn,&QPushButton::clicked,[](bool) { qDebug() <setText ("图片保存为:"+ fileName);}10. 布局分布管理 stretchlayoutStretch:0,0,0,表示3个组件平均分配宽度layoutStretch:0,0,1,表示前两个组件达到合适宽度后不再增加宽度,其余的空间都分配给第三个组件layoutStretch:1,1,2,表示前两个组件达到合适宽度后将尽量满足1:1:2的比例11. 分割条允许用户通过拖动子widget之间的边界来控制子widget的大小。QSplitter *splitter = new QSplitter(parent);QListView *listview = new QListView;QTreeView *treeview = new QTreeView;QTextEdit *textedit = new QTextEdit;splitter->addWidget(listview);splitter->addWidget(treeview);splitter->addWidget(textedit);//splitter->setOrientation(Qt::Vertical);12. foreachQList values;foreach (QString str, values) qDebug() << str;13.// 移除帮助按钮。windowFlags() 当前窗口的标志位(flags)、取反,按位与运算setWindowFlags(windowFlags() & ~Qt::WindowContextHelpButtonHint);//用户使用键盘快捷键时,可以通过按下 "Alt + S" 来聚焦到 styleComboBox。auto styleLabel = createWidget1(tr("&Style:"), "styleLabel");styleLabel->setBuddy(styleComboBox);//全局快捷键:new QShortcut(tr("Ctrl+p"), this, this, &WidgetGallery::demo);demo是一个信号//参数带入,版本宏setWindowTitle(tr("Widget Gallery Qt %1").arg(QT_VERSION_STR));qDebug() << "Qt version: " << QT_VERSION;qDebug() << "Qt major version: " << QT_VERSION_MAJOR;qDebug() << "Qt minor version: " << QT_VERSION_MINOR;qDebug() << "Qt patch version: " << QT_VERSION_PATCH;999. QMetaObject类int main(int argc, char *argv[]){ QApplication a(argc, argv); //QObject::metaObject返回类关联的元对象 QObject *btn = new QPushButton; qDebug()<metaObject()->className(); //返回“QPushButton” QPushButton *btnPush=qobject_cast(btn);//qobject_cast类似于标准C++中的dynamic_cast qDebug()<metaObject()->className(); QTimer *timer = new QTimer(); //QTimer是QObject的子类 qDebug()<inherits("QTimer"); //返回true qDebug()<inherits("QObject"); //返回true qDebug()<inherits("QAbstrctButton");//返回false //superClass返回父类的元对象 qDebug()<metaObject()->superClass()->className();}1000:属性系统:Q_PROPERTY(bool focus READ hasFocus) Q_PROPERTY(bool enabled READ isEnabled WRITE setEnabled) Q_PROPERTY(QCursor cursor READ cursor WRITE SetCursor RESET unsetCursor) int main(int argc, char *argv[]){ QApplication a(argc, argv); QPushButton *button = new QPushButton; QObject *object = button; bool isFlat = object->property("flateee").toBool(); qDebug()<setProperty("flateee",true); isFlat = object->property("flateee").toBool(); qDebug()<metaObject(); int index=meta->indexOfProperty("down"); QMetaProperty prop=meta->property(index); bool res=prop.isWritable(); qDebug()<<" down(QPushButton) isWritable?: "<<res;}1001:类的附加信息Q_OBJECT Q_CLASSINFO("author","Wang") Q_CLASSINFO("compay","UPC")Q_CLASSINFO("version","3.0.1")QMyWidget * myWidget = new QMyWidget;qDebug()<metaObject()->classInfo(0).name();qDebug()<metaObject()->classInfo(0).value(); qDebug()<metaObject()->classInfo(1).name(); qDebug()<metaObject()->classInfo(1).value();1002. 自定义信号及其使用:class QPerson:public QObject { Q_OBJECT private: int m_age = 10; public: void incAge(); signals: void ageChanged(int value); }; void QPerson::incAge() { m_age++; emit ageChanged(m_age); //发射信号 1003:容器:QList list; //定义一个float类型的数据列表QList list={1,2,3,4,5};//初始化列表数据QList list(100); //初始化列表元素个数为100,所有元素默认为0QList strList(10,"pass");//10个元素,每个元素都被初始化为passQList list;list<<"Monday"<<"Tuesday"<<"Wednesday"<<"Thursday";list.append("Friday");QString str1=list[0]; //QList::const_reference QList::operator[](qsizetype i) constQString str2=list.at(1); //------------QMap map;map["one"] = 1;map["three"] = 3;map["seven"] = 7map.insert("twelve", 12);int num1 = map["one"];//如果在map中没有指定键的项,这些函数返回一个默认构造的值。int num2 = map["thirteen"];int num3 = map.value("thirteen");//还有一个value()重载方法,如果指定的键不存在,则使用第二个参数作为默认值 int num4 = map.value("thirteen",13);
1. 菜单栏、工具栏、状态栏
QApplication a(argc, argv);MainWindow mainWindow;// 创建菜单栏QMenuBar *menuBar = mainWindow.menuBar();QMenu *fileMenu = menuBar->addMenu("文件");QMenu *editMenu = menuBar->addMenu("编辑");// 创建工具栏QToolBar *toolBar = mainWindow.addToolBar("工具栏");toolBar->addAction("打开");toolBar->addAction("保存");toolBar->addSeparator();toolBar->addAction("剪切");toolBar->addAction("复制");toolBar->addAction("粘贴");// 创建状态栏QStatusBar *statusBar = mainWindow.statusBar();statusBar->showMessage("准备就绪");mainWindow.setGeometry(100, 100, 800, 600); // 设置主窗口的位置和大小mainWindow.setWindowTitle("Qt 示例应用程序");mainWindow.show();
2. 自定义的对话框
#include #include #include #include #include #include #include #include #include #include #include #include #include #include class CustomDialog : public QDialog{public: CustomDialog(QWidget *parent = nullptr) : QDialog(parent) { setWindowTitle("自定义对话框"); QLabel *label = new QLabel("请输入文本:", this); lineEdit = new QLineEdit(this); QPushButton *okButton = new QPushButton("确定", this); QPushButton *cancelButton = new QPushButton("取消", this); QVBoxLayout *layout = new QVBoxLayout; layout->addWidget(label); layout->addWidget(lineEdit); layout->addWidget(okButton); layout->addWidget(cancelButton); setLayout(layout); connect(okButton, &QPushButton::clicked, this, &CustomDialog::accept); connect(cancelButton, &QPushButton::clicked, this, &CustomDialog::reject); } QString getText() const { return lineEdit->text(); }private: QLineEdit *lineEdit;};int main(int argc, char *argv[]){ QApplication app(argc, argv); QMainWindow mainWindow; QMenuBar *menuBar = mainWindow.menuBar(); QMenu *fileMenu = menuBar->addMenu("文件"); QMenu *editMenu = menuBar->addMenu("编辑"); QToolBar *toolBar = mainWindow.addToolBar("工具栏"); QTextEdit *textEdit = new QTextEdit(&mainWindow); mainWindow.setCentralWidget(textEdit); QStatusBar *statusBar = mainWindow.statusBar(); // 在菜单栏和工具栏中添加操作 QAction *openAction = fileMenu->addAction("打开"); QAction *saveAction = fileMenu->addAction("保存"); fileMenu->addSeparator(); QAction *customDialogAction = editMenu->addAction("自定义对话框"); toolBar->addAction(openAction); toolBar->addAction(saveAction); toolBar->addSeparator(); toolBar->addAction(customDialogAction); QObject::connect(openAction, &QAction::triggered, [&]() { QString fileName = QFileDialog::getOpenFileName(&mainWindow, "打开文件"); if (!fileName.isEmpty()) { QFile file(fileName); if (file.open(QIODevice::ReadOnly | QIODevice::Text)) { textEdit->setPlainText(file.readAll()); file.close(); } } }); QObject::connect(saveAction, &QAction::triggered, [&]() { QString fileName = QFileDialog::getSaveFileName(&mainWindow, "保存文件"); if (!fileName.isEmpty()) { QFile file(fileName); if (file.open(QIODevice::WriteOnly | QIODevice::Text)) { QTextStream out(&file); out <toPlainText(); file.close(); } } }); QObject::connect(customDialogAction, &QAction::triggered, [&]() { CustomDialog dialog(&mainWindow); if (dialog.exec() == QDialog::Accepted) { QString text = dialog.getText(); if (!text.isEmpty()) { statusBar->showMessage("自定义对话框输入: " + text, 5000); } } }); mainWindow.setGeometry(100, 100, 800, 600); mainWindow.setWindowTitle("高级 Qt 示例"); mainWindow.show(); return app.exec();}
3. 任务管理器
#include #include #include #include #include #include #include class TaskManager : public QMainWindow{ Q_OBJECTpublic: TaskManager(QWidget *parent = nullptr) : QMainWindow(parent) { setWindowTitle("任务管理器"); taskList = new QListWidget(this); setCentralWidget(taskList); createMenus(); }private: QListWidget *taskList; void createMenus() { QMenu *taskMenu = menuBar()->addMenu("任务"); QAction *addAction = taskMenu->addAction("添加任务"); connect(addAction, &QAction::triggered, this, &TaskManager::addTask); QAction *removeAction = taskMenu->addAction("删除任务"); connect(removeAction, &QAction::triggered, this, &TaskManager::removeTask); QAction *completeAction = taskMenu->addAction("完成任务"); connect(completeAction, &QAction::triggered, this, &TaskManager::completeTask); }private slots: void addTask() { bool ok; QString taskName = QInputDialog::getText(this, "添加任务", "输入任务名称:", QLineEdit::Normal, "", &ok); if (ok && !taskName.isEmpty()) { taskList->addItem(taskName); } } void removeTask() { QListWidgetItem *selectedItem = taskList->currentItem(); if (selectedItem) { delete selectedItem; } } void completeTask() { QListWidgetItem *selectedItem = taskList->currentItem(); if (selectedItem) { selectedItem->setFlags(selectedItem->flags() | Qt::ItemIsUserCheckable); selectedItem->setCheckState(Qt::Checked); } }};int main(int argc, char *argv[]){ QApplication app(argc, argv); TaskManager taskManager; taskManager.show(); return app.exec();}#include "main.moc" // 使用Qt的元对象系统时需要的moc文件
4. 链接数据库mysql,sqlite
1. cmake:find_package(Qt${QT_VERSION_MAJOR} COMPONENTS Sql REQUIRED)target_link_libraries(20231121_C1 PRIVATE Qt${QT_VERSION_MAJOR}::Widgets Qt${QT_VERSION_MAJOR}::Sql)2. 将本地的mysql:D:\mysql-5.7.37-winx64\lib: libmysql.lib、libmysqld.lib 放置E:\QT\Qt4.6\6.5.2\msvc2019_64\bin目录下;重启qt;3.代码测试://代码:#include "QtSql/qsqlquery.h"#include #include #include #include #include int main(int argc, char *argv[]){ QCoreApplication a(argc, argv); QStringList drivers = QSqlDatabase::drivers(); //获取现在可用的数据库驱动 foreach(QString driver, drivers) qDebug() << driver; // 设置 SQLite 数据库连接 // QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE"); //db.setDatabaseName("mydatabase.db"); QSqlDatabase db = QSqlDatabase::addDatabase("QMYSQL"); db.setHostName("127.0.0.1"); db.setPort(3306); db.setDatabaseName("mydata"); db.setUserName("root"); db.setPassword("123456"); // 打开数据库 if (!db.open()) { qDebug() << "无法打开数据库"; return -1; }// // 在数据库中创建表// QSqlQuery query;// query.exec("CREATE TABLE IF NOT EXISTS tasks (id INTEGER PRIMARY KEY, name TEXT)");// // 插入数据// query.prepare("INSERT INTO tasks (name) VALUES (:name)");// query.bindValue(":name", "完成 Qt 学习");// query.exec();// query.bindValue(":name", "写一个小程序");// query.exec(); // 查询数据 QSqlQuery query; query.exec("SELECT * FROM student"); while (query.next()) { int id = query.value("id").toInt(); QString name = query.value("name").toString(); qDebug() << "任务 ID:" << id << ", 任务名称:" << name; } // 关闭数据库 db.close(); return a.exec();}
5. Widgets Gallery Example 代码学习:
999.Controls
//QPushButtonQPushButton *button = new QPushButton("点击我", &w); button.setText("Click me!"); QObject::connect(&button, &QPushButton::clicked, [&](){ // button被点击时执行的代码 qDebug() <setIcon(QIcon(":/icon.png")); // 设置图标toolButton->setText("工具按钮"); // 设置文本layout->addWidget(toolButton);// 将QToolButton添加到布局中// 设置窗口的布局window.setLayout(layout);//QRadioButtonQRadioButton *radioButton1 = new QRadioButton("选项 1");// 创建三个单选按钮QRadioButton *radioButton2 = new QRadioButton("选项 2");QRadioButton *radioButton3 = new QRadioButton("选项 3");// 将单选按钮添加到布局中layout->addWidget(radioButton1);layout->addWidget(radioButton2);layout->addWidget(radioButton3);//QCheckBoxQCheckBox *checkBox1 = new QCheckBox("选项 1");// 创建三个复选框QCheckBox *checkBox2 = new QCheckBox("选项 2");QCheckBox *checkBox3 = new QCheckBox("选项 3");// 将复选框添加到布局中layout->addWidget(checkBox1);layout->addWidget(checkBox2);layout->addWidget(checkBox3);//QListView// 创建一个QStringListModel,用于存储列表项的数据QStringListModel *model = new QStringListModel;// 添加一些示例数据QStringList items;items << "项1" << "项2" << "项3" << "项4" <setStringList(items);// 创建一个QListView并设置模型QListView *listView = new QListView;listView->setModel(model);//QTreeView// 创建一个QStandardItemModel,用于存储树形数据QStandardItemModel *model = new QStandardItemModel;// 创建一个根节点QStandardItem *rootItem = model->invisibleRootItem();// 创建一些子节点QStandardItem *item1 = new QStandardItem("节点1");QStandardItem *item2 = new QStandardItem("节点2");QStandardItem *item3 = new QStandardItem("节点3");// 将子节点添加到根节点rootItem->appendRow(item1);rootItem->appendRow(item2);rootItem->appendRow(item3);// 创建一个QTreeView并设置模型QTreeView *treeView = new QTreeView;treeView->setModel(model);//QTableView// 创建一个QStandardItemModel,用于存储表格数据QStandardItemModel *model = new QStandardItemModel;// 设置表头model->setHorizontalHeaderLabels({"列1", "列2", "列3"});// 插入一些数据for (int row = 0; row < 5; ++row) { for (int column = 0; column index(row, column, QModelIndex()); model->setData(index, QString("行%1,列%2").arg(row + 1).arg(column + 1)); }}// 创建一个QTableView并设置模型QTableView *tableView = new QTableView;tableView->setModel(model);//QColumnView// 创建一个QFileSystemModel,用于显示文件系统QFileSystemModel *model = new QFileSystemModel;// 设置模型的根目录,这里设置为当前目录model->setRootPath(QDir::currentPath());// 创建一个QColumnView并设置模型QColumnView *columnView = new QColumnView;columnView->setModel(model);//QUndoView用于显示和管理撤销/重做操作的控件// 创建一个QUndoStack来管理操作历史记录QUndoStack undoStack;// 创建一个QUndoView来显示操作历史记录QUndoView undoView(&undoStack);undoView.setEmptyLabel("无可撤销操作");// 创建一个按钮来执行一个示例操作QPushButton button("执行操作");QObject::connect(&button, &QPushButton::clicked, [&]() { // 在这里执行一个示例操作,将其添加到撤销堆栈中 undoStack.push(new QUndoCommand("示例操作"));});//QListWidget// 创建一个QListWidgetQListWidget *listWidget = new QListWidget;// 创建一些示例列表项QListWidgetItem *item1 = new QListWidgetItem("项目1");QListWidgetItem *item2 = new QListWidgetItem("项目2");QListWidgetItem *item3 = new QListWidgetItem("项目3");// 将列表项添加到QListWidgetlistWidget->addItem(item1);listWidget->addItem(item2);listWidget->addItem(item3);//QTreeWidget// 创建一个QTreeWidget,用于显示树形数据QTreeWidget *treeWidget = new QTreeWidget;// 创建树形控件的列标题QStringList headers;headers << "列1" <setHeaderLabels(headers);// 创建根节点QTreeWidgetItem *rootItem = new QTreeWidgetItem(treeWidget);rootItem->setText(0, "根节点");// 创建一些子节点QTreeWidgetItem *item1 = new QTreeWidgetItem(rootItem);item1->setText(0, "子节点1");item1->setText(1, "子节点1的列2");QTreeWidgetItem *item2 = new QTreeWidgetItem(rootItem);item2->setText(0, "子节点2");item2->setText(1, "子节点2的列2");// 将根节点添加到树形控件treeWidget->addTopLevelItem(rootItem);//QTableWidget// 创建一个QTableWidget,用于显示表格数据QTableWidget *tableWidget = new QTableWidget;// 设置表格的行数和列数tableWidget->setRowCount(3); // 3行tableWidget->setColumnCount(2); // 2列// 设置表格的表头QStringList headers;headers << "列1" <setHorizontalHeaderLabels(headers);// 在表格中插入一些数据tableWidget->setItem(0, 0, new QTableWidgetItem("行1列1"));tableWidget->setItem(0, 1, new QTableWidgetItem("行1列2"));tableWidget->setItem(1, 0, new QTableWidgetItem("行2列1"));tableWidget->setItem(1, 1, new QTableWidgetItem("行2列2"));tableWidget->setItem(2, 0, new QTableWidgetItem("行3列1"));tableWidget->setItem(2, 1, new QTableWidgetItem("行3列2"));//QScrollArea// 创建一个QScrollArea用于显示滚动区域QScrollArea *scrollArea = new QScrollArea;// 创建一个大的QWidget,用于放置内容QWidget *contentWidget = new QWidget;// 创建一个垂直布局管理器用于大的QWidgetQVBoxLayout *contentLayout = new QVBoxLayout(contentWidget);// 向大的QWidget添加一些按钮for (int i = 0; i addWidget(button);}// 设置大的QWidget为QScrollArea的视口scrollArea->setWidget(contentWidget);//QToolBox// 创建一个QToolBoxQToolBox *toolBox = new QToolBox;// 创建多个页面并添加到QToolBox中QWidget *page1 = new QWidget;QPushButton *button1 = new QPushButton("按钮 1");page1->setLayout(new QVBoxLayout);page1->layout()->addWidget(button1);toolBox->addItem(page1, "页面 1");QWidget *page2 = new QWidget;QLabel *label2 = new QLabel("标签 2");page2->setLayout(new QVBoxLayout);page2->layout()->addWidget(label2);toolBox->addItem(page2, "页面 2");QWidget *page3 = new QWidget;QLabel *label3 = new QLabel("标签 3");page3->setLayout(new QVBoxLayout);page3->layout()->addWidget(label3);toolBox->addItem(page3, "页面 3");//QTabWidget// 创建一个QTabWidgetQTabWidget *tabWidget = new QTabWidget;// 创建多个选项卡页面并添加到QTabWidget中QWidget *page1 = new QWidget;QPushButton *button1 = new QPushButton("按钮 1");page1->setLayout(new QVBoxLayout);page1->layout()->addWidget(button1);tabWidget->addTab(page1, "选项卡 1");QWidget *page2 = new QWidget;QLabel *label2 = new QLabel("标签 2");page2->setLayout(new QVBoxLayout);page2->layout()->addWidget(label2);tabWidget->addTab(page2, "选项卡 2");QWidget *page3 = new QWidget;QLabel *label3 = new QLabel("标签 3");page3->setLayout(new QVBoxLayout);page3->layout()->addWidget(label3);tabWidget->addTab(page3, "选项卡 3");//QStackedWidget// 创建一个QWidget窗口QWidget window;// 创建一个垂直布局管理器QVBoxLayout *layout = new QVBoxLayout(&window);// 创建一个QStackedWidgetQStackedWidget *stackedWidget = new QStackedWidget;// 创建多个页面并添加到QStackedWidget中QWidget *page1 = new QWidget;QPushButton *button1 = new QPushButton("按钮 1");page1->setLayout(new QVBoxLayout);page1->layout()->addWidget(button1);stackedWidget->addWidget(page1);QWidget *page2 = new QWidget;QLabel *label2 = new QLabel("标签 2");page2->setLayout(new QVBoxLayout);page2->layout()->addWidget(label2);stackedWidget->addWidget(page2);QWidget *page3 = new QWidget;QLabel *label3 = new QLabel("标签 3");page3->setLayout(new QVBoxLayout);page3->layout()->addWidget(label3);stackedWidget->addWidget(page3);// 设置默认显示的页面stackedWidget->setCurrentIndex(0);// 将QStackedWidget添加到布局中layout->addWidget(stackedWidget);// 创建按钮来切换页面QPushButton *nextButton = new QPushButton("下一页");layout->addWidget(nextButton);// 设置窗口的布局window.setLayout(layout);// 连接按钮的点击事件,用于切换页面QObject::connect(nextButton, &QPushButton::clicked, [&]() { int currentIndex = stackedWidget->currentIndex(); int nextPageIndex = (currentIndex + 1) % stackedWidget->count(); stackedWidget->setCurrentIndex(nextPageIndex);});// 设置窗口的大小window.resize(300, 200);// 显示窗口window.show();//QFrame// 创建一个QFrameQFrame *frame = new QFrame;// 设置QFrame的样式,添加边框frame->setFrameStyle(QFrame::Panel | QFrame::Raised);// 创建一些小部件并添加到QFrame中QPushButton *button = new QPushButton("按钮");QLabel *label = new QLabel("标签");QVBoxLayout *frameLayout = new QVBoxLayout(frame);frameLayout->addWidget(button);frameLayout->addWidget(label);//QComboBox// 创建一个QComboBoxQComboBox *comboBox = new QComboBox;// 向QComboBox添加选项comboBox->addItem("选项 1");comboBox->addItem("选项 2");comboBox->addItem("选项 3");// 将QComboBox添加到布局中layout->addWidget(comboBox);//QFontComboBox// 创建一个QWidget窗口QWidget window;// 创建一个垂直布局管理器QVBoxLayout *layout = new QVBoxLayout(&window);// 创建一个QFontComboBoxQFontComboBox *fontComboBox = new QFontComboBox;// 创建一个标签来显示所选字体示例QLabel *label = new QLabel("示例文本");label->setFont(fontComboBox->currentFont());// 连接QFontComboBox的currentFontChanged信号以更新标签的字体QObject::connect(fontComboBox, &QFontComboBox::currentFontChanged, label, [=](const QFont &font) { label->setFont(font);});// 将QFontComboBox和标签添加到布局中layout->addWidget(fontComboBox);layout->addWidget(label);// 设置窗口的布局window.setLayout(layout);// 设置窗口的大小window.resize(300, 200);// 显示窗口window.show();//QLineEdit// 创建一个QLineEdit用于文本输入QLineEdit *lineEdit = new QLineEdit;// 创建一个标签来显示输入的文本QLabel *label = new QLabel("输入的文本:");// 连接QLineEdit的textChanged信号以更新标签的文本QObject::connect(lineEdit, &QLineEdit::textChanged, label, &QLabel::setText);// 将QLineEdit和标签添加到布局中layout->addWidget(lineEdit);layout->addWidget(label);//QTextEdit// 创建一个QTextEdit用于多行文本输入和编辑QTextEdit *textEdit = new QTextEdit;//QPlainTextEdit// 创建一个QPlainTextEdit用于多行文本输入和编辑QPlainTextEdit *plainTextEdit = new QPlainTextEdit;//QSpinBox// 创建一个QSpinBox用于整数值输入QSpinBox *spinBox = new QSpinBox;// 设置QSpinBox的范围spinBox->setMinimum(0);spinBox->setMaximum(100);// 创建一个标签来显示选择的整数值QLabel *label = new QLabel("选择的值:");// 连接QSpinBox的valueChanged信号以更新标签的文本QObject::connect(spinBox, QOverload::of(&QSpinBox::valueChanged), [=](int value) { label->setText("选择的值:" + QString::number(value));});
QT-For-Python1. Demo
self.ui.pushButton.setText("demo")lable=QLabel("Hello World!")lable.show()Signals and Slots:from PySide6.QtCore import Slot@Slot()def say_hello(): print("button")def function(): print("button")button = QPushButton("Click me")button.clicked.connect(say_hello)//functionbutton.show()
QT-Quick1. HelloWorld
//main.cpp:QQmlApplicationEngine engine;engine.load(QUrl(QStringLiteral("qrc:/qt/qml/qtquickapplication1/main.qml")));if (engine.rootObjects().isEmpty()) return -1;//main.qml:import QtQuick 2.9import QtQuick.Window 2.2import QtQuick.ControlsWindow { visible: true width: 640 height: 480 title: "HelloWorld" Text:{ text:"HelloWorld" }}
2. 简单表单
import QtQuick 2.15import QtQuick.Controls 2.15import QtQuick.Layouts 1.15ApplicationWindow { visible: true width: 400 height: 300 title: "Qt Quick App" ColumnLayout { spacing: 10 anchors.centerIn: parent TextField { id: nameField placeholderText: "Enter your name" } RowLayout { spacing: 10 RadioButton { id: maleRadioButton text: "Male" checked: true onClicked: femaleRadioButton.checked = false } RadioButton { id: femaleRadioButton text: "Female" onClicked: maleRadioButton.checked = false } } ComboBox { id: countryComboBox model: ["Country 1", "Country 2", "Country 3"] } TextArea { id: commentsTextArea placeholderText: "Enter your comments" wrapMode: TextEdit.Wrap height: 100 } Button { text: "Submit" font.pixelSize: 16 Layout.columnSpan: 2 Layout.fillWidth: true onClicked: { var nameValue = nameField.text var genderValue = maleRadioButton.checked ? "Male" : "Female" var countryValue = countryComboBox.currentText var commentsValue = commentsTextArea.text console.log("Name: " + nameValue) console.log("Gender: " + genderValue) console.log("Country: " + countryValue) console.log("Comments: " + commentsValue) // 在这里可以将获取到的值进行进一步处理或提交到服务器 } } }}