QT(二).计算器(4)

QTextCodec::setCodecForTr

用来设定转化的字符集

void QTextCodec::setCodecForTr ( QTextCodec * c ) [static]

Sets the codec used by QObject::tr() on its argument to c. If c is 0 (the default), tr() assumes Latin-1, If the literal quoted text in the program is not in the Latin-1 encoding, this function can be used to set the appropriate encoding

Note: 这是设定要转化的字符集

QTextCodec::codecForName

根据参数搜索已经安装的那么多字符集中最可能的那个字符集的

QTextCodec * QTextCodec::codecForName ( const char * name ) [static]

Searches all installed QTextCodec objects and returns the one which best matches name; the match is case-insensitive. Returns 0 if no codec matching the name name could be found


QWidget

QWidget 是所有UI对象的基类

The QWidget class is the base class of all user interface objects.

它接受鼠标,键盘事件,并且负责定位和显示自身形状

The widget is the atom of the user interface: it receives mouse, keyboard and other events from the window system, and paints a representation of itself on the screen. Every widget is rectangular, and they are sorted in a Z-order. A widget is clipped by its parent and by the widgets in front of it

QWidget::QWidget

QWidget 的构造函数接受一个或两个参数

QWidget::QWidget ( QWidget * parent = 0, Qt::WindowFlags f = 0 )

要创建一个新的窗体时,要使 parent=0 ,否则它就是一个子窗口,如果父窗口注销了,子窗口会随之注销

Constructs a widget which is a child of parent, with widget flags set to f. If parent is 0, the new widget becomes a window. If parent is another widget, this widget becomes a child window inside parent. The new widget is deleted when its parent is deleted. The widget flags argument, f, is normally 0, but it can be set to customize the frame of a window (i.e. parent must be 0). To customize the frame, use a value composed from the bitwise OR of any of the window flags. If you add a child widget to an already visible widget you must explicitly show the child to make it visible.


QDialog

QDialog 是对话窗口的基类,继承自QWidget

The QDialog class is the base class of dialog windows

A dialog window is a top-level window mostly used for short-term tasks and brief communications with the user. QDialogs may be modal or modeless. QDialogs can provide a return value, and they can have default buttons. QDialogs can also have a QSizeGrip in their lower-right corner, using setSizeGripEnabled(). Note that QDialog (an any other widget that has type Qt::Dialog) uses the parent widget slightly differently from other classes in Qt. A dialog is always a top-level widget, but if it has a parent, its default location is centered on top of the parent’s top-level widget (if it is not top-level itself). It will also share the parent’s taskbar entry.

QDialog::QDialog

QDialog 类的构造函数

QDialog::QDialog ( QWidget * parent = 0, Qt::WindowFlags f = 0 )

一般而言,一个对话框是一个最顶层的窗口,如果它不是最顶层的,它将在父窗体的中间进行显示

A dialog is always a top-level widget, but if it has a parent, its default location is centered on top of the parent. It will also share the parent’s taskbar entry. The widget flags f are passed on to the QWidget constructor. If, for example, you don’t want a What’s This button in the title bar of the dialog, pass Qt::WindowTitleHintQt::WindowSystemMenuHint in f


Q_OBJECT 宏

Qt/qobjectdefs.h 中有关于 Q_OBJECT 宏的定义

代码语言:javascript
复制
/* tmake ignore Q_OBJECT */
#define Q_OBJECT \
public: \
    Q_OBJECT_CHECK \
    static const QMetaObject staticMetaObject; \
    Q_OBJECT_GETSTATICMETAOBJECT \
    virtual const QMetaObject *metaObject() const; \
    virtual void *qt_metacast(const char *); \
    QT_TR_FUNCTIONS \
    virtual int qt_metacall(QMetaObject::Call, int, void **); \
private: \
    Q_DECL_HIDDEN static const QMetaObjectExtraData staticMetaObjectExtraData; \
    Q_DECL_HIDDEN static void qt_static_metacall(QObject *, QMetaObject::Call, int, void **);

只有加入了Q_OBJECT,才能使用QT中的signal和slot机制

The Q_OBJECT macro at the beginning of the class definition is necessary for all classes that define signals or slots

如果不加上这个宏,有什么效果呢

可以顺利编译通过,但是如果运行,虽然可以生成界面,但会产生大量的如下报错,各种事件也不会响应

代码语言:javascript
复制
[emacs@h102 calc]$ ./calc 
Object::connect: No such slot QDialog::append1()
Object::connect:  (sender name:   'pb1')
Object::connect:  (receiver name: 'Calc')
Object::connect: No such slot QDialog::append2()
Object::connect:  (sender name:   'pb2')
Object::connect:  (receiver name: 'Calc')
Object::connect: No such slot QDialog::append3()
Object::connect:  (sender name:   'pb3')
Object::connect:  (receiver name: 'Calc')
Object::connect: No such slot QDialog::append4()
Object::connect:  (sender name:   'pb4')
Object::connect:  (receiver name: 'Calc')
Object::connect: No such slot QDialog::append5()
Object::connect:  (sender name:   'pb5')
Object::connect:  (receiver name: 'Calc')
Object::connect: No such slot QDialog::append6()
Object::connect:  (sender name:   'pb6')
Object::connect:  (receiver name: 'Calc')
Object::connect: No such slot QDialog::append7()
Object::connect:  (sender name:   'pb7')
Object::connect:  (receiver name: 'Calc')
Object::connect: No such slot QDialog::append8()
Object::connect:  (sender name:   'pb8')
Object::connect:  (receiver name: 'Calc')
Object::connect: No such slot QDialog::append9()
Object::connect:  (sender name:   'pb9')
Object::connect:  (receiver name: 'Calc')
Object::connect: No such slot QDialog::append0()
Object::connect:  (sender name:   'pb0')
Object::connect:  (receiver name: 'Calc')
Object::connect: No such slot QDialog::appendP()
Object::connect:  (sender name:   'pbPoint')
Object::connect:  (receiver name: 'Calc')
Object::connect: No such slot QDialog::clear()
Object::connect:  (sender name:   'pbC')
Object::connect:  (receiver name: 'Calc')
Object::connect: No such slot QDialog::del()
Object::connect:  (sender name:   'pbD')
Object::connect:  (receiver name: 'Calc')
Object::connect: No such slot QDialog::add()
Object::connect:  (sender name:   'pbAdd')
Object::connect:  (receiver name: 'Calc')
Object::connect: No such slot QDialog::eq()
Object::connect:  (sender name:   'pbEq')
Object::connect:  (receiver name: 'Calc')
Object::connect: No such slot QDialog::min()
Object::connect:  (sender name:   'pbMin')
Object::connect:  (receiver name: 'Calc')
Object::connect: No such slot QDialog::mul()
Object::connect:  (sender name:   'pbMul')
Object::connect:  (receiver name: 'Calc')
Object::connect: No such slot QDialog::div()
Object::connect:  (sender name:   'pbDiv')
Object::connect:  (receiver name: 'Calc')
Object::connect: No such slot QDialog::mod()
Object::connect:  (sender name:   'pbMod')
Object::connect:  (receiver name: 'Calc')
...
...

QString

QString是Qt中使用很频繁的类,它提供了一个Unicode构成的字符串

The QString class provides a Unicode character string

QString 由 QChars 组成 ,每个字符是16位,即 2 Byte

QString stores a string of 16-bit QChars, where each QChar corresponds one Unicode 4.0 character. (Unicode characters with code values above 65535 are stored using surrogate pairs, i.e., two consecutive QChars.)

之所以选择Unicode是为了兼容

Unicode is an international standard that supports most of the writing systems in use today. It is a superset of ASCII and Latin-1 (ISO 8859-1), and all the ASCII/Latin-1 characters are available at the same code positions.

QString::QString

QString::QString ( const char * str )

使用字符串来构造一个QString对象

Constructs a string initialized with the ASCII string str. The given const char pointer is converted to Unicode using the fromAscii() function

QString::toFloat

将QString的对象转换为float值

Returns the string converted to a float value If a conversion error occurs, *ok is set to false; otherwise *ok is set to true. Returns 0.0 if the conversion fails

代码语言:javascript
复制
     QString str1 = "1234.56";
     str1.toFloat();             // returns 1234.56
 bool ok;
 QString str2 = "R2D2";
 str2.toFloat(&amp;ok);          // returns 0.0, sets ok to false</code></pre></div></div><h4 id="e50bp" name="QString::number">QString::number</h4><p>将数值转化为Qstring对象(或者通过数值来初始化对象)</p><blockquote><p>Returns a string equivalent of the number n according to the specified base</p></blockquote><p>它有如下几种重载</p><div class="rno-markdown-code"><div class="rno-markdown-code-toolbar"><div class="rno-markdown-code-toolbar-info"><div class="rno-markdown-code-toolbar-item is-type"><span class="is-m-hidden">代码语言:</span>javascript</div></div><div class="rno-markdown-code-toolbar-opt"><div class="rno-markdown-code-toolbar-copy"><i class="icon-copy"></i><span class="is-m-hidden">复制</span></div></div></div><div class="developer-code-block"><pre class="prism-token token line-numbers language-javascript"><code class="language-javascript" style="margin-left:0">QString QString::number ( long n, int base = 10 )   [static]

QString QString::number ( ulong n, int base = 10 ) [static]
QString QString::number ( int n, int base = 10 ) [static]
QString QString::number ( uint n, int base = 10 ) [static]
QString QString::number ( qlonglong n, int base = 10 ) [static]
QString QString::number ( qulonglong n, int base = 10 ) [static]
QString QString::number ( double n, char format = 'g', int precision = 6 ) [static]

QString::chop

void QString::chop ( int n )

删除掉字符串末尾的几个字符

Removes n characters from the end of the string, If n is greater than size(), the result is an empty string

QString::append

在字符串末尾追加字符或字符串

Appends the string str onto the end of this string.

这个追加操作非常快,原因是QString有预留空间,不必每次都重新分配整个新的字符串空间

The append() function is typically very fast (constant time), because QString preallocates extra space at the end of the string data so it can grow without reallocating the entire string each time

有如下几种重载形式

代码语言:javascript
复制
QString & QString::append ( const QString & str )
QString & QString::append ( const QLatin1String & str )
QString & QString::append ( const QByteArray & ba )
QString & QString::append ( const char * str )
QString & QString::append ( QChar ch )

QLabel

QLabel 对象可以用来显示文本和图片

The QLabel widget provides a text or image display, No user interaction functionality is provided. The visual appearance of the label can be configured in various ways, and it can be used for specifying a focus mnemonic key for another widget

QLabel 对象可以包含如下类型的对象

Content

Setting

Plain text

Pass a QString to setText().

Rich text

Pass a QString that contains rich text to setText().

A pixmap

Pass a QPixmap to setPixmap().

A movie

Pass a QMovie to setMovie().

A number

Pass an int or a double to setNum(), which converts the number to plain text.

Nothing

The same as an empty plain text. This is the default. Set by clear().


setAlignment

配置对齐方式

void setAlignment ( Qt::Alignment )

This property holds the alignment of the label’s contents

详细的对齐方式可以参阅官方的API文档,大体上分为水平和垂直两类

水平对齐有:

  • Qt::AlignLeft
  • Qt::AlignRight
  • Qt::AlignHCenter
  • Qt::AlignJustify

垂直对齐有:

  • Qt::AlignTop
  • Qt::AlignBottom
  • Qt::AlignVCenter

二维居中:

  • Qt::AlignCenter

connect

qobject.h 中有关于 connect 的声明

代码语言:javascript
复制
inline bool QObject::connect(const QObject *asender, const char *asignal,
const char *amember, Qt::ConnectionType atype) const
{ return connect(asender, asignal, this, amember, atype); }
...
...
static bool connect(const QObject *sender, const char *signal,
const QObject *receiver, const char *member, Qt::ConnectionType =
#ifdef qdoc
Qt::AutoConnection
#else
#ifdef QT3_SUPPORT
Qt::AutoCompatConnection
#else
Qt::AutoConnection
#endif
#endif
);

static bool connect(const QObject *sender, const QMetaMethod &amp;signal,
                    const QObject *receiver, const QMetaMethod &amp;method,
                    Qt::ConnectionType type =

#ifdef qdoc
Qt::AutoConnection
#else
#ifdef QT3_SUPPORT
Qt::AutoCompatConnection
#else
Qt::AutoConnection
#endif
#endif
);

inline bool connect(const QObject *sender, const char *signal,
                    const char *member, Qt::ConnectionType type =

#ifdef qdoc
Qt::AutoConnection
#else
#ifdef QT3_SUPPORT
Qt::AutoCompatConnection
#else
Qt::AutoConnection
#endif
#endif
) const;

这是关于 connect 函数的几种形式

关于参数的格式可以如下表示

connect(sender,SIGNAL(signal()),receiver,SLOT(slot()));

SIGNAL SLOT

qobjectdefs.h 中有关于 SIGNALSLOT 的宏定义

代码语言:javascript
复制
#ifndef QT_NO_DEBUG

define QLOCATION "\0" FILE ":" QTOSTRING(LINE)

ifndef QT_NO_KEYWORDS

define METHOD(a) qFlagLocation("0"#a QLOCATION)

endif

define SLOT(a) qFlagLocation("1"#a QLOCATION)

define SIGNAL(a) qFlagLocation("2"#a QLOCATION)

#else

ifndef QT_NO_KEYWORDS

define METHOD(a) "0"#a

endif

define SLOT(a) "1"#a

define SIGNAL(a) "2"#a

#endif

源码的引用层级比较深,所以详细调用过程可以参看 QT QObject::connect函数的学习 ,讲得比较透彻


总结

掌握如下概念对Qt的学习非常有用

  • 信号

如下类是Qt中常用的类,掌握它们的属性和方法很有必要

  • QApplication
  • QFont
  • QTextCodec
  • QWidget
  • QDialog
  • QString
  • QLabel

以下函数和宏非常重要

  • connect
  • SIGNAL
  • SLOT
  • Q_OBJECT

原文地址http://soft.dog/2017/02/26/qt-basic-02/