Practical Qt

本文总结了Qt编程中常见的几个问题及解决办法,包括setValue与signalvalueChanged的关系、QDialog与QWidget的区别、正则表达式的正确使用、QSplitter的布局特性、QString的操作技巧以及QTextStream的使用细节。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

适用Qt版本:4.5.2

1、setValue和signal valueChanged
setValue在两种情况下不触发signal valueChanged:
a:传入一个原有的值。
b:传入一个范围以外的值。
适用于QSpinBox、QSlider、QProgressBar等。

2、QDialog和QWidget
a、QPushButton的default property适用于QDialog,而不是QWidget

3、regular expression
曾经写过这么一句code:
hexEdit->setValidator(new QRegExpValidator(QRegExp("[0-9A-Fa-f]{1, 2}"), hexEdit));
注意在设置字符次数的数字中间有一个空格,该多余空格导致regular expression设置失败。

4、QSplitter
a、一个QSplitter,要么是水平方向上排列多个QWidget(1*column),要么是在垂直方向上排列多个QWidget(row*1);要想获取一个通用的row*column的QWidget组合,可以使用splitter->addWidget(otherSplitter)的方式组合多个splitters。
b、对于上述方法创建的一个QWidget组合,要想同步移动不同QSplitter内的QWidget暂时还是不行的(比如,水平移动索引为(2,3)的QWidget,同时移动列索引为3的所有QWidget)。为了同步,需要添加具体特定的QSplitter(比如splitter)的signal splitterMoved的响应函数;在该函数内部设置:otherSplitter->setSizes(splitter->sizes())。

5、QString
QString提供的功能也许太多了,有些常见用法偶尔也不是那么容易找到的。
a、转换QString为const char *:
    const char *qPrintable(const QString &str),同时需要注意返回值的有效期很短。
b、子字符串:
    QString QString::mid(int start, int size = -1) const

6、QTextStream
QTextStream一个类具有读写两种功能,不像stl中的ifstream、ofstream两者各司其职;另外使用stl中的fstream只需提供一个文件名,而QTextStream则通常还需要创建一个QFile对象。
无论怎样,qt的优势在于它提供了一整套的实现方案,使用它的时候,是保持一种统一的风格,而最好不要在Qt和stl之间反复的转变。
读写文件时典型用法如下:
    QFile file(fname);
    if(!file.open(QFile::ReadOnly) || !file.exists())
    {
        qWarning("Open file error!");
        return;
    }
    QTextStream fileStream(&file);
    
读写stdin、stdout、stderr(FILE *)要简单一些:
    QTextStream cin(stdin, QIODevice::ReadOnly);
    QTextStream cout(stdout, QIODevice::WriteOnly);
    QTextStream cerr(stderr, QIODevice::WriteOnly);
注意:读写stdin、stdout时,请注意务必要链接正确的库,即debug版本对应debug版本的lib文件,release亦是如此;否则很可能会出现令人难以琢磨的crash。

### QT EventLoop Usage and Examples In the context of Qt, an event loop is a fundamental concept that allows applications to process events such as user input or system signals. The `QEventLoop` class provides functions to enter the main event loop and exit it when required. A typical application contains at least one instance of `QApplication`, which creates an internal `QEventLoop`. This object processes all incoming events from various sources like mouse clicks, keyboard presses, timer timeouts, etc., dispatching them appropriately within your program's structure[^1]. To demonstrate how this works: #### Basic Example with QCoreApplication For console-based programs where no GUI elements are involved, use `QCoreApplication`. ```cpp #include <QCoreApplication> int main(int argc, char *argv[]) { QCoreApplication app(argc, argv); QObject obj; QTimer::singleShot(0,&obj,[&](){ qDebug()<<"Hello World!"; app.quit(); }); return app.exec(); // Starts the event processing. } ``` This code snippet initializes a simple non-GUI application using `QCoreApplication`. It schedules printing "Hello World!" immediately after starting up by connecting a lambda function to a single-shot timer signal before entering into the event loop via calling `app.exec()`. #### Customizing Behavior Using Direct Control Over QEventLoop Sometimes more control over execution flow might be necessary; here comes direct manipulation through explicit creation of `QEventLoop` objects useful. ```cpp void someFunction() { bool conditionMet = false; while (!conditionMet){ QEventLoop localLoop; connect(someObject,SIGNAL(signal()),this,SLOT(slotThatSetsCondition())); if (localLoop.exec() == 0 && conditionMet ) break ; } } ``` Here, instead of relying on global loops provided by QApplication/QGuiApplication classes, custom logic can determine whether continuing iteration makes sense based upon certain conditions being met inside slots connected during each pass around the loop body. --related questions-- 1. How does integrating third-party libraries affect handling events in Qt? 2. What mechanisms exist for managing multiple threads alongside the primary event loop in Qt applications? 3. Can you provide detailed explanations about different types of timers available under Qt framework along with practical coding samples demonstrating their uses? 4. In what scenarios would someone prefer creating separate instances of QEventLoop rather than utilizing those already present due to inheritance from higher-level abstractions like QApplication? 5. Is there any performance impact associated with nesting several layers deep calls involving exec methods across diverse parts of large scale projects built atop Qt library ecosystem?
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值