I have the following code (implemented in the mouseReleaseEvent) to detect when the user has selected lines of text:
QTextCursor cursor = this->textCursor();
int start = cursor.selectionStart();
int end = cursor.selectionEnd();
if(!cursor.hasSelection())
return; // No selection available
qWarning() << "start: " << start << " end: " << end << endl;
the problem is: I need the line numbers where the selection begins and ends. I've been struggling with blocks and solved nothing, can you please give me a clue?
It is possible, that it isn't the best solution, but it seems to work for me. The variable selectedLines will contain, how many lines are selected.
QTextCursor cursor = ui->plainTextEdit->textCursor();
int selectedLines = 0; //<--- this is it
if(!cursor.selection().isEmpty())
{
QString str = cursor.selection().toPlainText();
selectedLines = str.count("\n")+1;
}
I hope, that it will be helpful :)
I see easy way to use chain of 2 QTextCursor methods - setPosition and blockNumber.
QTextCursor cursor = this->textCursor();
int start = cursor.selectionStart();
int end = cursor.selectionEnd();
if(!cursor.hasSelection())
return; // No selection available
cursor.setPosition(start);
int firstLine = cursor.blockNumber();
cursor.setPosition(end, QTextCursor::KeepAnchor);
int lastLine = cursor.blockNumber();
qWarning() << "start: " << firstLine << " end: " << lastLine << endl;
UPD:
cursor.setPosition(start);
cursor.block().layout()->lineForTextPosition(start).lineNumber();
// or
cursor.block().layout()->lineAt(<relative pos from start of block>).lineNumber();
Set position to begin of selection. Get current block, get layout of block and use Qt API for getting line number. I doesn't know which line number returned is absolute for whole document or for layout. If only for layout, you need some additional process for calculate line numbers for previous blocks.
for (QTextBlock block = cursor.block(). previous(); block.isValid(); block = block.previous())
lines += block.lineCount();
Related
I am currently working on a simple console application that is to become a text-based RPG game based on economy. I have an 80x20 (character cells) window that will work as my display.
I have been experimenting with the FillConsoleOutputCharacter() API function, which seems to work as desired for clearing the console.
Before I use the function, I have simple output using wcout to display certain characteristics, such as the screen buffer size and the window size; but after outputting with FillConsoleOutputCharacter(), I notice that wcout does not output as it should.
I have the API function nested in another function named clearConsole(), and have noticed that output using wcout works as it should after leaving the function, but not after the call to FillConsoleOutputCharacter() (within the function).
Here is the function:
void clearConsole(HANDLE screen)
{
DWORD cCharsWritten;
CONSOLE_SCREEN_BUFFER_INFO bufferInfo;
DWORD dwConsoleSz;
if(!GetConsoleScreenBufferInfo(screen, &bufferInfo))
{
return;
}
dwConsoleSz = bufferInfo.dwSize.X * bufferInfo.dwSize.Y; /* This should be equivalent to the number of character cells in the buffer. */
/* Now we fill the entire screen with blanks. */
if(!FillConsoleOutputCharacter(
screen,
L' ',
dwConsoleSz,
cursorHome,
&cCharsWritten
));
{
return;
}
/* Then we get the current text attribute (maybe unnecessary?) */
if(!GetConsoleScreenBufferInfo(screen, &bufferInfo)) /* Perhaps the ScreenBuffer needs to be set again, see SetConsoleCursorPosition. */
{
return;
}
/* And set the buffer's attributes accordingly. */
if(!FillConsoleOutputAttribute(
screen,
bufferInfo.wAttributes,
dwConsoleSz,
cursorHome,
&cCharsWritten
))
{
return;
}
if(!SetConsoleCursorPosition(screen, bufferInfo.dwCursorPosition))
/*Research is needed regarding this function as it does not seem to move the cursor. */
{
wcout << L"SetConsoleCursorPosition failed. Error Code: " << GetLastError();
system("pause");
}
wcout << L"Screen Buffer Size: " << bufferInfo.dwSize.X << L',' << bufferInfo.dwSize.Y << L'\n' << L"Cursor Position: " <<
bufferInfo.dwCursorPosition.X << L',' << bufferInfo.dwCursorPosition.Y << L'\n' <<
L"Buffer Top X: " << bufferInfo.srWindow.Left << L' ' << L"Buffer Top Y: " << bufferInfo.srWindow.Top << L'\n' << L"Buffer Bottom X : " << bufferInfo.srWindow.Right << L' ' << L"Buffer Bottom Y: " << bufferInfo.srWindow.Bottom << L'\n';
wcout << L"hello from clearConsole" << L'\n';
/* wcout stops working from within this function after FillConsoleOutputCharacter is
called. But for some odd reason it begins working again after the function ends.
*/
Sleep(1000);
return;
}
What could be the cause for this?
I have experimented with moving the wcout lines around within the nesting function, and have seen that it works before the call to the API function, but not after. A strange malfunction. Flushing wcout (or the output stream) does not solve the issue, either.
Setting the cursor back to (0,0) does not seem to place the cursor back at the top left corner of the console, either. screen is a global variable set to STD_OUTPUT_HANDLE.
EDIT: Also, trying to set the cursor back to (0,0) using a global COORD object cursorHome in the call to SetConsoleCursorPosition() before writing to output does not seem to work, either.
EDIT: Setting the cursor's position after the call to clearConsole() works as well. What could be the cause of this strange behavior?
After multiple tests. It is caused by a very minor error - the ; after FillConsoleOutputCharacter().
/* Now we fill the entire screen with blanks. */
if(!FillConsoleOutputCharacter(
screen,
L' ',
dwConsoleSz,
cursorHome,
&cCharsWritten
)); // <-- HERE
{
return;
}
It cuts off the front and back connection and destroys the logic. It means that whatever value is returned by FillConsoleOutputCharacter() has nothing to do with the content in { }.
Just delete it.
I would like to change the position of the lineEdit (or even a PushButton if it's not possible with the lineEdit) from my Qt application, according to the input given.
So let's say that I want the x position to be 150 pixels, then I would insert 150 into the lineEdit.
Is there any way to do this?
I've already tried this:
void DrawTest::on_lineEdit_returnPressed()
{
QString x = ui->lineEdit->text();
qDebug() << "x: " << x;
QString style = "QLineEdit {"
":" +ui->lineEdit->text()+ "px;"
"background-color: #FF00FF;"
"};";
qDebug() << "Style: " << style;
ui->lineEdit->setStyleSheet(style);
}
It depends on how the QLineEdit is initially positioned. Is it placed within a layout? If so, you won't be able to place it at an absolute position.
But if it does not belong to any layout, you can just use the move method:
ui->lineEdit->move(x, y);
Here's the docs.
I am using HDFql to create an HDF5 file. I am creating a group and putting some data into it and that works fine. I then add an attribute to the file (which also seems to work, since it shows up when I inspect the HDF5 file with an HDF editor), but I can't figure out how to read the value of the attribute. Here is a minimal example:
#include <iostream.h>
#include <HDFql.hpp>
int main (int argc, const char * argv[]) {
char script[1024];
//Create the HDF5 file and the group "test"
HDFql::execute("CREATE TRUNCATE FILE /tmp/test.h5");
HDFql::execute("USE FILE /tmp/test.h5");
HDFql::execute("CREATE GROUP test");
//Generate some arbitrary data and place it in test/data
int data_length = 1000;
int data[data_length];
for(int i=0; i<data_length; i++) {data[i] = i;}
sprintf(script, "CREATE DATASET test/data AS INT(%d) VALUES FROM MEMORY %d",
data_length, HDFql::variableTransientRegister(data));
HDFql::execute(script);
//Create an attribute called "channels" and give it an arbitrary value of 11
HDFql::execute("CREATE ATTRIBUTE test/data/channels AS INT VALUES(11)");
//Show the attribute
HDFql::execute("SHOW ATTRIBUTE test/data/channels");
//Try to move the cursor to the attribute
HDFql::cursorLast();
//If that worked, print the attribute contents
if(HDFql::cursorGetInt())
{
std::cout << "channels = " << *HDFql::cursorGetInt() << std::endl;
} else
{
std::cout << "Couldn't find attribute" << std::endl;
}
HDFql::execute("CLOSE FILE");
}
I would expect the output to the console to be channels = 11, instead I am getting channels = 1953719668. Curiously, if I call cursorGetChar instead, the return value is "t", and if I say
std::cout << "channels = " << HDFql::cursorGetChar() << std::endl;
the output becomes channels = test/data/channels.
So I think I have misunderstood how exactly HDFql cursors work. So my question is: what is wrong with my code? And why is my code wrong?
Many thanks!
When you do SHOW ATTRIBUTE test/data/channels you are basically testing for the existence of an attribute named channels stored in test/data. Since this attribute exists, function HDFql::execute returns HDFql::Success and the cursor is populated with the string test/data/channels. On the other hand, if the attribute didn't exist, function HDFql::execute would have returned HDFql::ErrorNotFound and the cursor would be empty.
To read the value stored in attribute test/data/channels do the following instead:
HDFql::execute("SELECT FROM test/data/channels");
HDFql::cursorFirst();
std::cout << "channels = " << *HDFql::cursorGetInt() << std::endl;
i have this project due however i am unsure of how to parse the data by the word, part of speech and its definition... I know that i should make use of the tab spacing to read it but i have no idea how to implement it. here is an example of the file
Recollection n. The power of recalling ideas to the mind, or the period within which things can be recollected; remembrance; memory; as, an event within my recollection.
Nip n. A pinch with the nails or teeth.
Wodegeld n. A geld, or payment, for wood.
Xiphoid a. Of or pertaining to the xiphoid process; xiphoidian.
NB: Each word and part of speech and definition is one line in a text file.
If you can be sure that the definition will always follow the first period on a line, you could use an implementation like this. But it will break if there are ever more than 2 periods on a single line.
string str = "";
vector<pair<string,string>> v; // <word,definition>
while(getline(fileStream, str, '.')) { // grab line, deliminated '.'
str[str.length() - 1] = ""; // get rid of n, v, etc. from word
v.push_back(make_pair<string,string>(str,"")); // push the word
getline(fileStream, str, '.'); // grab the next part of the line
v.back()->second = str; // push definition into last added element
}
for(auto x : v) { // check your results
cout << "word -> " << x->first << endl;
cout << "definition -> " << x->second << endl << endl;
}
The better solution would be to learn Regular Expressions. It's a complicated topic but absolutely necessary if you want to learn how to parse text efficiently and properly:
http://www.cplusplus.com/reference/regex/
As part of a bigger application I am working on a class for reading input from a text file for use in the initialization of the program. Now I am myself fairly new to programming, and I only started to learn C++ in December, so I would be very grateful for some hints and ideas on how to get started! I apologise in advance for a rather long wall of text.
The text file format is "keyword-driven" in the following way:
There are a rather small number of main/section keywords (currently 8) that need to be written in a given order. Some of them are optional, but if they are included they should adhere to the given ordering.
Example:
Suppose there are 3 potential keywords ordered like as follows:
"KEY1" (required)
"KEY2" (optional)
"KEY3" (required)
If the input file only includes the required ones, the ordering should be:
"KEY1"
"KEY3"
Otherwise it should be:
"KEY1"
"KEY2"
"KEY3"
If all the required keywords are present, and the total ordering is ok, the program should proceed by reading each section in the sequence given by the ordering.
Each section will include a (possibly large) amount of subkeywords, some of which are optional and some of which are not, but here the order does NOT matter.
Lines starting with characters '*' or '--' signify commented lines, and they should be ignored (as well as empty lines).
A line containing a keyword should (preferably) include nothing else than the keyword. At the very least, the keyword must be the first word appearing there.
I have already implemented parts of the framework, but I feel my approach so far has been rather ad-hoc. Currently I have manually created one method per section/main keyword , and the first task of the program is to scan the file for to locate these keywords and pass the necessary information on to the methods.
I first scan through the file using an std::ifstream object, removing empty and/or commented lines and storing the remaining lines in an object of type std::vector<std::string>.
Do you think this is an ok approach?
Moreover, I store the indices where each of the keywords start and stop (in two integer arrays) in this vector. This is the input to the above-mentioned methods, and it would look something like this:
bool readMAINKEY(int start, int stop);
Now I have already done this, and even though I do not find it very elegant, I guess I can keep it for the time being.
However, I feel that I need a better approach for handling the reading inside of each section, and my main issue is how should I store the keywords here? Should they be stored as arrays within a local namespace in the input class or maybe as static variables in the class? Or should they be defined locally inside relevant functions? Should I use enums? The questions are many!
Now I've started by defining the sub-keywords locally inside each readMAINKEY() method, but I found this to be less than optimal. Ideally I want to reuse as much code as possible inside each of these methods, calling upon a common readSECTION() method, and my current approach seems to lead to much code duplication and potential for error in programming. I guess the smartest thing to do would simply be to remove all the (currently 8) different readMAINKEY() methods, and use the same function for handling all kinds of keywords. There is also the possibility for having sub-sub-keywords etc. as well (i.e. a more general nested approach), so I think maybe this is the way to go, but I am unsure on how it would be best to implement it?
Once I've processed a keyword at the "bottom level", the program will expect a particular format of the following lines depending on the actual keyword. In principle each keyword will be handled differently, but here there is also potential for some code reuse by defining different "types" of keywords depending on what the program expects to do after triggering the reading of it. Common task include e.g. parsing an integer or a double array, but in principle it could be anything!
If a keyword for some reason cannot be correctly processed, the program should attempt as far as possible to use default values instead of terminating the program (if reasonable), but an error message should be written to a logfile. For optional keywords, default values will of course also be used.
In order to summarise, therefore, my main questions are the following:
1. Do you think think my approach of storing the relevant lines in a std::vector<std::string> to be reasonable?
This will of course require me to do a lot of "indexing work" to keep track of where in the vector the different keywords are located. Or should I work more "directly" with the original std::ifstream object? Or something else?
2. Given such a vector storing the lines of the text file, how I can I best go about detecting the keywords and start reading the information following them?
Here I will need to take account of possible ordering and whether a keyword is required or not. Also, I need to check if the lines following each "bottom level" keyword is in the format expected in each case.
One idea I've had is to store the keywords in different containers depending on whether they are optional or not (or maybe use object(s) of type std::map<std::string,bool>), and then remove them from the container(s) if correctly processed, but I am not sure exactly how I should go about it..
I guess there is really a thousand different ways one could answer these questions, but I would be grateful if someone more experienced could share some ideas on how to proceed. Is there e.g. a "standard" way of doing such things? Of course, a lot of details will also depend on the concrete application, but I think the general format indicated here can be used in a lot of different applications without a lot of tinkering if programmed in a good way!
UPDATE
Ok, so let my try to be more concrete. My current application is supposed to be a reservoir simulator, so as part of the input I need information about the grid/mesh, about rock and fluid properties, about wells/boundary conditions throughout the simulation and so on. At the moment I've been thinking about using (almost) the same set-up as the commercial Eclipse simulator when it comes to input, for details see
http://petrofaq.org/wiki/Eclipse_Input_Data.
However, I will probably change things a bit, so nothing is set in stone. Also, I am interested in making a more general "KeywordReader" class that with slight modifications can be adapted for use in other applications as well, at least it can be done in a reasonable amount of time.
As an example, I can post the current code that does the initial scan of the text file and locates the positions of the main keywords. As I said, I don't really like my solution very much, but it seems to work for what it needs to do.
At the top of the .cpp file I have the following namespace:
//Keywords used for reading input:
namespace KEYWORDS{
/*
* Main keywords and corresponding boolean values to signify whether or not they are required as input.
*/
enum MKEY{RUNSPEC = 0, GRID = 1, EDIT = 2, PROPS = 3, REGIONS = 4, SOLUTION = 5, SUMMARY =6, SCHEDULE = 7};
std::string mainKeywords[] = {std::string("RUNSPEC"), std::string("GRID"), std::string("EDIT"), std::string("PROPS"),
std::string("REGIONS"), std::string("SOLUTION"), std::string("SUMMARY"), std::string("SCHEDULE")};
bool required[] = {true,true,false,true,false,true,false,true};
const int n_key = 8;
}//end KEYWORDS namespace
Then further down I have the following function. I am not sure how understandable it is though..
bool InputReader::scanForMainKeywords(){
logfile << "Opening file.." << std::endl;
std::ifstream infile(filename);
//Test if file was opened. If not, write error message:
if(!infile.is_open()){
logfile << "ERROR: Could not open file! Unable to proceed!" << std::endl;
std::cout << "ERROR: Could not open file! Unable to proceed!" << std::endl;
return false;
}
else{
logfile << "Scanning for main keywords..." << std::endl;
int nkey = KEYWORDS::n_key;
//Initially no keywords have been found:
startIndex = std::vector<int>(nkey, -1);
stopIndex = std::vector<int>(nkey, -1);
//Variable used to control that the keywords are written in the correct order:
int foundIndex = -1;
//STATISTICS:
int lineCount = 0;//number of non-comment lines in text file
int commentCount = 0;//number of commented lines in text file
int emptyCount = 0;//number of empty lines in text file
//Create lines vector:
lines = std::vector<std::string>();
//Remove comments and empty lines from text file and store the result in the variable file_lines:
std::string str;
while(std::getline(infile,str)){
if(str.size()>=1 && str.at(0)=='*'){
commentCount++;
}
else if(str.size()>=2 && str.at(0)=='-' && str.at(1)=='-'){
commentCount++;
}
else if(str.size()==0){
emptyCount++;
}
else{
//Found a non-empty, non-comment line.
lines.push_back(str);//store in std::vector
//Start by checking if the first word of the line is one of the main keywords. If so, store the location of the keyword:
std::string fw = IO::getFirstWord(str);
for(int i=0;i<nkey;i++){
if(fw.compare(KEYWORDS::mainKeywords[i])==0){
if(i > foundIndex){
//Found a valid keyword!
foundIndex = i;
startIndex[i] = lineCount;//store where the keyword was found!
//logfile << "Keyword " << fw << " found at line " << lineCount << " in lines array!" << std::endl;
//std::cout << "Keyword " << fw << " found at line " << lineCount << " in lines array!" << std::endl;
break;//fw cannot equal several different keywords at the same time!
}
else{
//we have found a keyword, but in the wrong order... Terminate program:
std::cout << "ERROR: Keywords have been entered in the wrong order or been repeated! Cannot continue initialisation!" << std::endl;
logfile << "ERROR: Keywords have been entered in the wrong order or been repeated! Cannot continue initialisation!" << std::endl;
return false;
}
}
}//end for loop
lineCount++;
}//end else (found non-comment, non-empty line)
}//end while (reading ifstream)
logfile << "\n";
logfile << "FILE STATISTICS:" << std::endl;
logfile << "Number of commented lines: " << commentCount << std::endl;
logfile << "Number of non-commented lines: " << lineCount << std::endl;
logfile << "Number of empty lines: " << emptyCount << std::endl;
logfile << "\n";
/*
Print lines vector to screen:
for(int i=0;i<lines.size();i++){
std:: cout << "Line nr. " << i << " : " << lines[i] << std::endl;
}*/
/*
* So far, no keywords have been entered in the wrong order, but have all the necessary ones been found?
* Otherwise return false.
*/
for(int i=0;i<nkey;i++){
if(KEYWORDS::required[i] && startIndex[i] == -1){
logfile << "ERROR: Incorrect input of required keywords! At least " << KEYWORDS::mainKeywords[i] << " is missing!" << std::endl;;
logfile << "Cannot proceed with initialisation!" << std::endl;
std::cout << "ERROR: Incorrect input of required keywords! At least " << KEYWORDS::mainKeywords[i] << " is missing!" << std::endl;
std::cout << "Cannot proceed with initialisation!" << std::endl;
return false;
}
}
//If everything is in order, we also initialise the stopIndex array correctly:
int counter = 0;
//Find first existing keyword:
while(counter < nkey && startIndex[counter] == -1){
//Keyword doesn't exist. Leave stopindex at -1!
counter++;
}
//Store stop index of each keyword:
while(counter<nkey){
int offset = 1;
//Find next existing keyword:
while(counter+offset < nkey && startIndex[counter+offset] == -1){
offset++;
}
if(counter+offset < nkey){
stopIndex[counter] = startIndex[counter+offset]-1;
}
else{
//reached the end of array!
stopIndex[counter] = lines.size()-1;
}
counter += offset;
}//end while
/*
//Print out start/stop-index arrays to screen:
for(int i=0;i<nkey;i++){
std::cout << "Start index of " << KEYWORDS::mainKeywords[i] << " is : " << startIndex[i] << std::endl;
std::cout << "Stop index of " << KEYWORDS::mainKeywords[i] << " is : " << stopIndex[i] << std::endl;
}
*/
return true;
}//end else (file opened properly)
}//end scanForMainKeywords()
You say your purpose is to read initialization data from a text file.
Seems you need to parse (syntax analyze) this file and store the data under the right keys.
If the syntax is fixed and each construction starts with a keyword, you could write a recursive descent (LL1) parser creating a tree (each node is a stl vector of sub-branches) to store your data.
If the syntax is free, you might pick JSON or XML and use an existing parsing library.